From 6e0618d67d857f0aa218ec236531e57c211f9859 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 07:21:43 +0100 Subject: [PATCH 1/4] fix(random): MT19937.SetState refuses a position outside [0, 624] SetState stored Pos as given. Uint32 regenerates the key only when pos == 624, so a negative Pos or one above 624 indexed the 624-word key out of range (and genNext/addState, reached through Jumped, as well). Reported by go-embedded-r while binding R's RNG. SetState now returns an error for such a Pos and leaves the generator unchanged; RandomState.SetState passes it on. Calls that ignored the (previously absent) result still compile. Tests: both bounds refused (-1, -624, 625, 2^40) with the state kept and a draw still safe; Pos 0 and 624 accepted and continuing the stream; FuzzMT19937SetState over Pos and key words (20 s locally, no failure). With the guard disabled the refusal test fails and Uint32 panics with index out of range [-1]. Co-Authored-By: Claude Opus 5.5 --- random/legacy.go | 4 +- random/mt19937.go | 16 +++++-- random/mt19937_state_test.go | 93 ++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 4 deletions(-) create mode 100644 random/mt19937_state_test.go diff --git a/random/legacy.go b/random/legacy.go index 696c282..7fc6f9f 100644 --- a/random/legacy.go +++ b/random/legacy.go @@ -106,7 +106,9 @@ func (r *RandomState) SetState(s LegacyState) error { if err != nil { return err } - m.SetState(s.MT19937State) + if err := m.SetState(s.MT19937State); err != nil { + return err + } r.hasGauss, r.gauss = s.HasGauss, s.Gauss return nil } diff --git a/random/mt19937.go b/random/mt19937.go index 43ad5a2..163f19e 100644 --- a/random/mt19937.go +++ b/random/mt19937.go @@ -1,6 +1,9 @@ package random -import "errors" +import ( + "errors" + "fmt" +) const ( mtN = 624 @@ -155,10 +158,17 @@ func (m *MT19937) Raw() uint64 { return uint64(m.Uint32()) } // State returns the generator's state. func (m *MT19937) State() MT19937State { return MT19937State{m.key, m.pos} } -// SetState replaces the generator's state. -func (m *MT19937) SetState(s MT19937State) { +// SetState replaces the generator's state. Pos must be in [0, 624]: 624 means +// the key is used up and the next draw regenerates it. Any other Pos would make +// Uint32, Jumped and the jump code index outside the key, so it is refused and +// the generator is left unchanged. +func (m *MT19937) SetState(s MT19937State) error { + if s.Pos < 0 || s.Pos > mtN { + return fmt.Errorf("random: MT19937 state position %d outside [0, %d]", s.Pos, mtN) + } m.key = s.Key m.pos = s.Pos + return nil } // SeedSeq returns the SeedSequence the generator was made from, nil after diff --git a/random/mt19937_state_test.go b/random/mt19937_state_test.go new file mode 100644 index 0000000..09bb18e --- /dev/null +++ b/random/mt19937_state_test.go @@ -0,0 +1,93 @@ +package random + +import "testing" + +// TestMT19937SetStateRefusesPosOutOfRange: a Pos outside [0, 624] used to be +// stored as given, and the next Uint32 indexed the 624-word key at -1 or 625 +// (reported by go-embedded-r while binding R's RNG). It is refused now, the +// generator keeps its previous state, and the legacy RandomState passes the +// error on. +func TestMT19937SetStateRefusesPosOutOfRange(t *testing.T) { + for _, pos := range []int{-1, -624, mtN + 1, 1 << 40} { + m := NewMT19937(1) + want := m.State() + if err := m.SetState(MT19937State{Key: want.Key, Pos: pos}); err == nil { + t.Errorf("Pos %d accepted", pos) + continue // a draw from the accepted state would index out of range + } + if got := m.State(); got != want { + t.Errorf("Pos %d: the refused state changed the generator", pos) + continue + } + m.Uint32() // the state is still the valid one + + r := NewRandomState(1) + st, err := r.GetState() + if err != nil { + t.Fatal(err) + } + st.Pos = pos + if err := r.SetState(st); err == nil { + t.Errorf("RandomState: Pos %d accepted", pos) + } + } +} + +// TestMT19937SetStateAcceptsBothEnds: 0 (the whole key unused) and 624 (key +// used up, regenerate on the next draw) are both valid, and each continues +// the stream exactly as the generator it was taken from. +func TestMT19937SetStateAcceptsBothEnds(t *testing.T) { + src := NewMT19937(7) + seen := map[int]bool{} + for i := 0; i < 2*mtN; i++ { + if i == mtN/2 { + src.gen() // a fresh key with pos 0, which no draw ever leaves visible + } + s := src.State() + if s.Pos == 0 || s.Pos == mtN { + seen[s.Pos] = true + m := NewMT19937(0) + if err := m.SetState(s); err != nil { + t.Fatalf("Pos %d refused: %v", s.Pos, err) + } + c := &MT19937{key: src.key, pos: src.pos} + for j := 0; j < 3; j++ { + if a, b := m.Uint32(), c.Uint32(); a != b { + t.Fatalf("Pos %d draw %d: %d != %d", s.Pos, j, a, b) + } + } + } + src.Uint32() + } + if !seen[0] || !seen[mtN] { + t.Fatalf("both ends were not exercised: %v", seen) + } +} + +// FuzzMT19937SetState: whatever Pos and key words are given, SetState either +// refuses or leaves a generator that draws, jumps and draws again without +// panicking. +func FuzzMT19937SetState(f *testing.F) { + for _, p := range []int{-1, 0, 1, mtN - 1, mtN, mtN + 1, -1 << 40, 1 << 40} { + f.Add(p, uint32(5489)) + } + f.Fuzz(func(t *testing.T, pos int, word uint32) { + var s MT19937State + for i := range s.Key { + s.Key[i] = word + uint32(i) + } + s.Pos = pos + m := NewMT19937(1) + if err := m.SetState(s); err != nil { + if pos >= 0 && pos <= mtN { + t.Fatalf("valid Pos %d refused: %v", pos, err) + } + return + } + if pos < 0 || pos > mtN { + t.Fatalf("Pos %d accepted", pos) + } + m.Uint32() + m.Jumped(1).Uint32() + }) +} From c1cc03034fb6e5487483fd71777ed1f2e9090ed7 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 07:33:28 +0100 Subject: [PATCH 2/4] test(random): 32-bit-safe out-of-range positions in the SetState tests 1 << 40 overflows int on 386 and arm, so the test file did not compile on the 32-bit lanes. Use math.MaxInt and math.MinInt, which also cover both extremes on every word size. Co-Authored-By: Claude Opus 5.5 --- random/mt19937_state_test.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/random/mt19937_state_test.go b/random/mt19937_state_test.go index 09bb18e..b2f4d60 100644 --- a/random/mt19937_state_test.go +++ b/random/mt19937_state_test.go @@ -1,6 +1,9 @@ package random -import "testing" +import ( + "math" + "testing" +) // TestMT19937SetStateRefusesPosOutOfRange: a Pos outside [0, 624] used to be // stored as given, and the next Uint32 indexed the 624-word key at -1 or 625 @@ -8,7 +11,7 @@ import "testing" // generator keeps its previous state, and the legacy RandomState passes the // error on. func TestMT19937SetStateRefusesPosOutOfRange(t *testing.T) { - for _, pos := range []int{-1, -624, mtN + 1, 1 << 40} { + for _, pos := range []int{-1, -624, mtN + 1, math.MaxInt, math.MinInt} { m := NewMT19937(1) want := m.State() if err := m.SetState(MT19937State{Key: want.Key, Pos: pos}); err == nil { @@ -68,7 +71,7 @@ func TestMT19937SetStateAcceptsBothEnds(t *testing.T) { // refuses or leaves a generator that draws, jumps and draws again without // panicking. func FuzzMT19937SetState(f *testing.F) { - for _, p := range []int{-1, 0, 1, mtN - 1, mtN, mtN + 1, -1 << 40, 1 << 40} { + for _, p := range []int{-1, 0, 1, mtN - 1, mtN, mtN + 1, math.MinInt, math.MaxInt} { f.Add(p, uint32(5489)) } f.Fuzz(func(t *testing.T, pos int, word uint32) { From 4466955963df4d3ab546685909b131959c1269e7 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 08:18:47 +0100 Subject: [PATCH 3/4] test(random): a refused legacy state leaves Gauss untouched; check SetState errors From the review of #134: - the refusal test now also flips HasGauss/Gauss in the refused state and asserts that GetState after the refusal equals the state before it (NumPy writes gauss before the bit-generator setter refuses; we must not); - api_test.go checks the error that MT19937.SetState now returns. Co-Authored-By: Claude Opus 5.5 --- random/api_test.go | 4 +++- random/mt19937_state_test.go | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/random/api_test.go b/random/api_test.go index e5ce781..8d0a13c 100644 --- a/random/api_test.go +++ b/random/api_test.go @@ -250,7 +250,9 @@ func TestStateRoundTrips(t *testing.T) { d2.SetState(d.State()) check("PCG64DXSM", d, d2) m, m2 := NewMT19937(3), NewMT19937() - m2.SetState(m.State()) + if err := m2.SetState(m.State()); err != nil { + t.Fatal(err) + } check("MT19937", m, m2) ph, ph2 := NewPhilox(3), NewPhilox() ph.Uint64() diff --git a/random/mt19937_state_test.go b/random/mt19937_state_test.go index b2f4d60..eb50f4e 100644 --- a/random/mt19937_state_test.go +++ b/random/mt19937_state_test.go @@ -29,9 +29,19 @@ func TestMT19937SetStateRefusesPosOutOfRange(t *testing.T) { if err != nil { t.Fatal(err) } + before := st st.Pos = pos + st.HasGauss, st.Gauss = !st.HasGauss, 0.25 // must not land either if err := r.SetState(st); err == nil { t.Errorf("RandomState: Pos %d accepted", pos) + continue + } + after, err := r.GetState() + if err != nil { + t.Fatal(err) + } + if after != before { + t.Errorf("RandomState: Pos %d refused but the state changed", pos) } } } From 0aa333baf04361532f266fec2f5ef26c1233ffa5 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 29 Nov 2026 08:29:31 +0100 Subject: [PATCH 4/4] docs(random): SetState refuses a position outside [0, 624] (v0.47.0) Co-Authored-By: Claude Opus 5.5 --- docs/random.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/random.md b/docs/random.md index db2c1b9..8e07921 100644 --- a/docs/random.md +++ b/docs/random.md @@ -36,6 +36,13 @@ u, _ := random.Rand(3) // np.random.rand(3) | `rand`, `randn`, `randint`, `random_sample`, `normal`, `uniform`, `choice`, `shuffle`, `permutation`, `binomial`, `poisson`, `standard_normal`, `standard_exponential`, `exponential`, `standard_gamma`, `gamma`, `chisquare`, `lognormal`, `multinomial`, `bytes` | `RandomState` methods of the same names | | `np.random.seed`, `rand`, `randn`, `randint`, `random_sample`, `normal`, `uniform`, `choice`, `shuffle`, `permutation`, `binomial`, `poisson` | package functions over a shared `RandomState` behind a mutex | +`MT19937.SetState` and `RandomState.SetState` return an error for a state +position outside [0, 624], the range NumPy's `MT19937.state` setter accepts +(it raises `ValueError`). A refused state changes nothing, `Gauss` and +`HasGauss` included; NumPy's legacy `set_state` has already stored those when +the position is refused. Since v0.47.0; before that, an out-of-range position +was stored and the next draw indexed the key out of range. + ### Allocation-free scalar draws Every sampler above returns a `*ndarray.Array`. A solver that needs a few draws