GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — BUG: fix SeedSequence.spawn and set_bit_generator thread-safety (gh-32063) by Parth1353 · Pull Request #32463 · numpy/numpy

Conversation

@Parth1353

@Parth1353 Parth1353 commented Aug 30, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Fixes both problems reported in gh-32063.

1. SeedSequence.spawn hands out duplicate spawn keys

spawn read n_children_spawned, constructed the children, and only then
advanced the counter. Constructing a child runs Python code (np.concatenate
inside get_assembled_entropy, plus any subclass __init__), so the GIL can
be released partway through and concurrent spawns start from the same index.
BitGenerator.spawn and Generator.spawn delegate here, so they inherit it.

With the reproducer from the issue, on the GIL-enabled build:

before:  2000 children spawned, 500 unique spawn keys
after:   2000 children spawned, 2000 unique spawn keys

Four threads were getting identical bit generator streams. The fix reserves
the block of keys under a lock before building any child; the children, which
are the expensive part, are still built outside it.

Why a module-level lock rather than one per SeedSequence

The issue discussion suggested giving SeedSequence its own lock. That is not
possible without breaking pickles: adding any attribute to the cdef class
changes the checksum that Cython's auto-generated unpickler validates. Since
BitGenerator.__reduce__ embeds its SeedSequence, every existing pickle of a
SeedSequence, BitGenerator or Generator then fails to load. Verified by
adding a dummy attribute and loading pickles written by the unpatched build:

PickleError: Incompatible checksums (0x3eaa222 vs (...) = (_experiment_lock, entropy, ...))

Only the counter reservation happens under the lock, so a single shared lock
costs nothing measurable.

As a side effect, an out-of-range n_children now raises OverflowError
immediately instead of first trying to build billions of children.

2. set_bit_generator is not thread-safe

Three separate problems.

The swap was not validated before mutating. _initialize_bit_generator
assigned self._bit_generator before checking the capsule, so a rejected
argument dropped the last reference to the bit generator that
self._bitgen.state still points into, and left the singleton wedged. Shown by
subclassing MT19937 with a __del__:

>>> old bit generator DEALLOCATED (its C state is now freed)
raised: 'object' object has no attribute 'capsule'

Subsequent np.random.random() calls read that freed memory; they did not
crash only because the block had not been reused yet. Validation now happens
first, so a failed set_bit_generator is a no-op.

The swap ran unsynchronized. It rewrote the cached bitgen_t (function
pointers plus state pointer) while distribution methods read it with the GIL
released. It now holds the lock of the generator being replaced.

Replacing the lock broke mutual exclusion. This is the part flagged as
needing thought in the issue thread. RandomState uses its bit generator's
lock, so the swap replaces it, and call sites read self.lock well before they
acquire it — cont()/disc() allocate the output array in between. A thread
that read the old lock ends up in the critical section at the same time as one
that acquired the new lock, both using the same cached _bitgen.

I instrumented double_fill to count threads inside the critical section while
another thread swapped bit generators:

max threads inside the critical section
holding the outgoing lock only 4 (3/3 runs)
with this patch 1

The fix gives RandomState a lock handle whose identity never changes. It
acquires whichever lock is current, re-checks afterwards, and retries if a swap
won the race — that retry fired 12042 times in a 3000-swap stress run. Only one
lock is ever held, so it cannot deadlock against code holding a bit generator's
lock directly.

The handle is installed lazily, on the first swap, since the singleton is the
only RandomState that set_bit_generator can reach. Everything else keeps
using the bare lock. A/B/A benchmark, alternating builds to control for drift:

case no handle with handle delta
RandomState.random_sample() scalar 145.9 ns 144.8 ns -0.8%
RandomState.random_sample(10) 371.9 ns 370.0 ns -0.5%
RandomState.random_sample(100_000) 337.8 us 337.2 us -0.2%
RandomState.standard_normal() scalar 188.2 ns 186.8 ns -0.7%
RandomState.randint(0, 100) scalar 1126.7 ns 1127.1 ns +0.0%
Generator.random() scalar 249.2 ns 247.2 ns -0.8%

against a 1.3-2.4% noise floor between two identical builds. Installing the
handle unconditionally instead cost 15% on scalar RandomState.random_sample(),
which is why it is lazy.

Tests

  • test_parallel_seed_sequence_spawn — fails 3/3 without the spawn fix, passes 10/10 with it.
  • test_failed_swap_leaves_singleton_usable (4 cases) and test_set_bit_generator_waits_for_lock — all fail without the mtrand fix.
  • test_parallel_singleton_bit_generator_swap — hammers swaps against concurrent draws.

Full suite: 47815 passed, 0 failed. spin lint clean. Built and tested on
macOS 15.7 arm64, Python 3.12, Accelerate.

Notes

  • No release note fragment, matching BUG: ensure lock is held when accessing or writing to RNG state #32061 which fixed the same class of bug.
  • Existing pickles were explicitly checked and still load.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
Parth1353 and others added 3 commits August 30, 2026 17:57
@Parth1353 @claude
BUG: hand out unique spawn keys from concurrent SeedSequence.spawn
d81ef4f
SeedSequence.spawn read n_children_spawned, constructed the children, and
only then advanced the counter.  Constructing a child runs Python code --
np.concatenate() inside get_assembled_entropy(), plus any subclass
__init__ -- so the GIL can be released partway through.  Two threads
spawning from the same SeedSequence therefore observed the same starting
index and returned children with identical spawn keys, i.e. bit
generators producing identical streams.  BitGenerator.spawn and
Generator.spawn delegate here, so they inherited the bug.

Reserve the whole block of spawn keys under a lock before building any
child.  Only the reservation is serialized; the children, which are the
expensive part, are still built outside the lock.

The lock is module-level rather than per-instance because adding an
attribute to the SeedSequence cdef class changes the checksum that
Cython's auto-generated unpickler validates, which makes every existing
pickle of a SeedSequence, BitGenerator or Generator fail to load with
"PickleError: Incompatible checksums".

As a side effect an out-of-range n_children now raises OverflowError
immediately instead of first trying to build billions of children.

See numpygh-32063.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Parth1353 @claude
BUG: validate and lock the RandomState bit generator swap
dee368a
_initialize_bit_generator() assigned self._bit_generator before checking
the capsule, so a rejected argument dropped the last reference to the bit
generator that self._bitgen.state still points into -- freeing it -- and
left the RandomState wedged with an invalid _bit_generator.  Validate
first, so a failed set_bit_generator() is a no-op.

The swap also rewrote the cached bitgen_t struct (function pointers plus
the state pointer) with no synchronization, while distribution methods
read that struct under the bit generator's lock with the GIL released.
Hold the lock of the generator being replaced across the swap, so a draw
already in flight finishes first.

This does not yet give full mutual exclusion across a swap: a thread that
read the old lock before the swap but acquires it afterwards can run
concurrently with a thread holding the new lock.  Closing that needs a
guard that is not itself replaced, as discussed in numpygh-32063.

See numpygh-32063.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Parth1353 @claude
BUG: keep RandomState's lock identity stable across a bit generator swap
bde585c
Holding the outgoing lock across the swap stops a draw already in flight
from seeing a half-written bitgen_t, but it does not give mutual
exclusion.  RandomState uses the lock of its bit generator, so
set_bit_generator replaces that lock, and call sites read self.lock well
before they acquire it -- cont(), disc() and friends allocate the output
array in between.  A thread that read the old lock therefore ends up in
the critical section at the same moment as one that acquired the new
lock, and both use the same cached self._bitgen.  Instrumenting
double_fill() to count threads inside the critical section showed up to
4 at once while another thread swapped bit generators, in every run.

Give RandomState a lock handle whose identity never changes.  It
acquires whichever lock is current, re-checks it afterwards, and retries
if a swap won the race; the same instrumented run then never showed more
than one thread inside the critical section.  Only one lock is ever
held, so this cannot deadlock against code that holds a bit generator's
lock directly.

The handle is installed lazily, on the first swap, because the singleton
is the only RandomState that set_bit_generator can reach.  Every other
instance keeps using the bare lock, so the extra indirection is not on
anybody's path unless they hot-swap.  An A/B/A benchmark puts the change
between -0.8% and 0.0% on scalar and array draws, against a 1.3-2.4%
noise floor between identical builds; installing the handle
unconditionally instead cost 15% on scalar RandomState.random_sample().

See numpygh-32063.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added the 00 - Bug label Aug 30, 2026
@jorenham

jorenham commented Aug 30, 2026

Copy link
Copy Markdown
Member

You ignored the PR template, so I'm going to assume that this PR has been made with agentic AI. This violates our AI policy; we prefer to talk to humans.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jorenham jorenham closed this Aug 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

00 - Bug

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@Parth1353 @jorenham
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.