Store the Cython random number buffers by value in the random state (fixes restore after a buffer refill) #1896
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #1896"
general
weight: 0.35
mstimberg
Fixes #1893.
As discussed in #1893, the runtime device now owns the
rand()/randn()buffers of the Cython target and stores their content, instead of the address of a buffer allocated (and freed) by the generated code. This removes the dangling pointer that maderestore(restore_random_state=True)read freed memory, or free a block twice, when a buffer was refilled betweenstore()andrestore().Changes
brian2/devices/device.py:RANDOM_BUFFER_SIZE = 20000(moved fromcython_generator.py).RuntimeDevice.rand_bufferandrandn_bufferarenp.zeros(RANDOM_BUFFER_SIZE, dtype=np.float64)arrays instead of a size-1intparray holding a pointer.get_random_stateis unchanged apart from a comment: it now copies the numbers themselves.set_random_statecopies into the existing arrays, since the generated code refers to their data. A state stored by an earlier version (size-1 array holding an address) is never dereferenced: if its index is non-zero, a warning is logged and the index is set to 0, so that the buffer is refilled from the restored numpy state; with index 0 the restore is exact and nothing is logged.brian2/codegen/generators/cython_generator.pyandtemplates/common_group.pyx:_rand/_randnrefill the device's buffer in place withmemcpyfrom a freshnumpy.random.rand(n)/randn(n)array, and no longer callfree(), clearOWNDATAor store an address. The numbers drawn are the same as before (see below).freecimport and thePyArray_CLEARFLAGSdeclaration incommon_group.pyx. Brian's own code no longer uses them, but I did not want to remove names that user-provided Cython implementations might rely on; I can remove them if you prefer.brian2/tests/test_network.py(runtime targets only, skipped for standalone liketest_restore_with_random_state):test_restore_random_state_after_buffer_refills[rand|randn]: stores the state with 51 numbers left in the buffer, then makes three assignments ofRANDOM_BUFFER_SIZE - 51values, each of which refills the buffer, restores, and checks that the three assignments are reproduced exactly.seed()empties the buffers first, so the test does not depend on the tests that ran before it.test_restore_random_state_from_file_in_new_process[rand|randn]: stores the state to a file, then restores it in a new Python process (same preferences, passed throughprefs.as_file) and compares the next assignment.test_restore_random_state_without_buffer_content(codegen independent): a state in the old format with a non-zerorandindex logs one warning and resets that index, while therandnbuffer with index 0 is restored silently.Validation
Linux (WSL Ubuntu 24.04, kernel 6.18), gcc 13.3, Python 3.13.14, numpy 2.5.4, Cython 3.3.0, on master 9f803d0 with the extensions built from source (
setup.py build_ext --inplace). Windows and macOS were not tested locally.RANDOM_BUFFER_SIZEwritten out as 20000, since master does not define it), all five runtime tests fail with Cython: the in-process tests report 51 mismatched elements out of 19949 (the numbers left in the buffer atstore(), read back from freed memory), and the child process of the file tests is killed by a segmentation fault (return code -11).test_restore_random_state_without_buffer_contentalso fails, since master logs no warning. With this branch, the 11 selected runs (codegen independent, Cython, numpy) pass, with the defaultfloat_dtypeand withfloat_dtype=float32.brian2.test(["cython", "numpy"], test_codegen_independent=True, test_in_parallel=[...]), long tests excluded): with this branch, 56 doctests, 436 codegen-independent, 305 Cython and 308 numpy tests pass; on master, 56, 435, 301 and 304 (the difference is the new tests). The only failure,test_base.py::test_version, occurs on both, because the tests ran from a source copy withoutsetuptools_scm. In this run,test_restore_with_random_statepassed on master: whether it crashes depends on the tests that ran before it in the same worker.randndraws beforestore()): master givesidentical=Trueat 0, an abort (double free or corruption) at 19500 andidentical=Falseat 19990; this branch givesidentical=Trueat all three.rand(), 50 000randn(), 500 steps of a noisyNeuronGroup(5e5xidraws) and a 1000-neuronPoissonGroupgive bit-identical values and spikes on master and on this branch..pre-commit-config.yaml):ruff formatleaves the three Python files unchanged andruff checkreports nothing ondevice.pyandcython_generator.py.Compatibility and cost
restore_random_state=Trueby an earlier version:ValueError: could not broadcast input array from shape (20000,) into shape (1,). Restores withoutrestore_random_state=Truedo not read the random state (Network.restore), so they are not affected in either direction.store()in memory shows no measurable difference;store(filename=...)writes 323 kB instead of 3 kB and took 1.5 to 3.5 ms instead of 0.4 to 0.6 ms (per-process medians, 8 processes per version).NeuronGroupdrawing 1e7randnvalues per run (500 refills) took a median of 0.274 s per run with this branch against 0.272 s on master (+0.8 %; 10 processes per version in random order, pinned to one core, 9 runs each). Without pinning, the timings of both versions were bimodal (about 0.27 s or 0.37 s), so unpinned comparisons on this machine were not conclusive.buffer[index:]; I kept the simpler version, but can change it if the state size matters.Relation with #1745
#1745 replaces the buffers by a shared C++ generator and also removes the dangling pointer. As you wrote in #1893, this fix can go in first; the new tests could then serve as acceptance tests for #1745 (except the old-format one). On its head (62829a7), the
randtests pass and eachrandntest fails on one element, becauseget_statewritesstored_gausswith 6 significant digits (details in #1893).This should also remove the flaky heap corruption in
test_restore_with_random_stateseen in the Python 3.15 jobs of #1891.I used an AI assistant (Claude Code) to write the fix and the tests, run the validation and draft this description.