From 6020094655d7730e9bb1f0e821b3ba902a642b32 Mon Sep 17 00:00:00 2001 From: KainanP Date: Sat, 28 Nov 2026 03:40:06 -0300 Subject: [PATCH 1/2] Use critical sections to make fmpz_mat thread-safe In the free-threaded build, mutating an fmpz_mat that another thread is reading or writing could free or reallocate the entries while FLINT was using them, which crashed with "double free or corruption" or a segfault (gh-224). Take a per-object critical section (cython.critical_section) around every fmpz_mat method that reads or writes the entries, and around the places in other modules that read an fmpz_mat (the fmpq_mat, nmod_mat, arb_mat and acb_mat constructors and contains). Binary operations lock both operands. In the default build with the GIL the critical sections compile to nothing. Run test_python_threads in the free-threaded build too and extend it to cover more operations. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +++--- doc/source/build.rst | 3 +- src/flint/test/test_all.py | 48 ++++++++++++++++++++-------- src/flint/types/acb_mat.pyx | 6 ++-- src/flint/types/arb_mat.pyx | 6 ++-- src/flint/types/fmpq_mat.pyx | 3 +- src/flint/types/fmpz_mat.pyx | 62 +++++++++++++++++++++++++++--------- src/flint/types/nmod_mat.pyx | 6 ++-- 8 files changed, 103 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 58d08f47..ff0d5e8a 100644 --- a/README.md +++ b/README.md @@ -154,10 +154,11 @@ python-flint. As of python-flint 0.7.0, CPython 3.13 [PEP 703](https://peps.python.org/pep-0703/) free-threaded (no-GIL) builds of -python-flint are provided. In the the free-threaded build, mutating matrices or -polynomials from multiple threads can lead to memory corruption. There are some -other known issues with the free-threaded build so it should be considered -experimental. +python-flint are provided. In the the free-threaded build, `fmpz_mat` uses +per-object critical sections so that it can be mutated and read from multiple +threads, but mutating other matrix or polynomial types from multiple threads +can still lead to memory corruption. There are some other known issues with the +free-threaded build so it should be considered experimental. CHANGELOG ========= diff --git a/doc/source/build.rst b/doc/source/build.rst index f2b323a2..ea292e3a 100644 --- a/doc/source/build.rst +++ b/doc/source/build.rst @@ -158,7 +158,8 @@ As of python-flint 0.7.0, CPython ``3.13t`` free-threaded builds are tested in CI but wheels are not provided on PyPI. There are no known issues related to using python-flint in a `PEP 703 `_ free-threaded build but it is likely that mutating objects shared by multiple -threads is not safe. +threads is not safe. The exception is ``fmpz_mat`` whose methods hold a +critical section on the matrices that they read or modify. It is also possible to build and use python-flint for PyPy. Other Python implementations may work but are not tested. diff --git a/src/flint/test/test_all.py b/src/flint/test/test_all.py index e9e124e6..c54b6d1a 100644 --- a/src/flint/test/test_all.py +++ b/src/flint/test/test_all.py @@ -5359,27 +5359,24 @@ def test_python_threads(): # # https://github.com/flintlib/python-flint/issues/224 # - # XXX: This test crashes under the free-threading mode because of memory - # corruption. + # Mutating an fmpz_mat that is shared between threads used to crash the + # free-threaded build because of memory corruption. The fmpz_mat methods + # now hold a critical section on the matrices that they read or write. # - # It is not clear if this should be fixed or if mutating - # matrices/polynomials that are shared between multiple threads should just - # be disallowed. + # Other mutable types (polynomials, other matrix types) are not protected + # yet so mutating those from multiple threads is still unsafe. # # This thread is skipped on Emscripten/WASM builds as we can't start new # threads in Pyodide. - - # Skip the test on the free-threaded build and on WASM... import sys - if (sys.version_info[:2] >= (3, 13) and not sys._is_gil_enabled()) or ( # type: ignore - sys.platform == "emscripten" or platform.machine() in ["wasm32", "wasm64"]): + if sys.platform == "emscripten" or platform.machine() in ["wasm32", "wasm64"]: return from threading import Thread iterations = 10**5 - nthreads = 3 + 1 size = 3 + big = 10**128 M = flint.fmpz_mat([[0]*size for _ in range(size)]) def set_values(): @@ -5388,7 +5385,7 @@ def set_values(): j = random.randrange(M.ncols()) if random.uniform(0, 1) > 0.5: # Bigger than 2**62: - M[i,j] = 10**128 + M[i,j] = big else: # Smaller than 2**62: M[i,j] = 0 @@ -5397,14 +5394,39 @@ def get_dets(): for _ in range(iterations): M.det() - threads = [Thread(target=set_values) for _ in range(nthreads-1)] - threads.append(Thread(target=get_dets)) + def other_reads(): + for _ in range(iterations // 20): + assert M == M + M + M + M - M + M * M + M * 3 + flint.fmpz_mat(M) + flint.fmpq_mat(M) + flint.nmod_mat(M, 7) + M.transpose() + M.rank() + assert M[1, 1] in (0, big) + + errors = [] + + def run(func): + try: + func() + except BaseException as e: + errors.append(e) + + funcs = [set_values] * 3 + [get_dets, other_reads] + threads = [Thread(target=run, args=(f,)) for f in funcs] for t in threads: t.start() for t in threads: t.join() + assert errors == [] + assert all(x in (0, big) for x in M.entries()) + def test_all_tests(): from flint.test.__main__ import collect_all_tests diff --git a/src/flint/types/acb_mat.pyx b/src/flint/types/acb_mat.pyx index 136a194a..f0c07ecb 100644 --- a/src/flint/types/acb_mat.pyx +++ b/src/flint/types/acb_mat.pyx @@ -108,7 +108,8 @@ cdef class acb_mat(flint_mat): m = fmpz_mat_nrows((val).val) n = fmpz_mat_ncols((val).val) acb_mat_init(self.val, m, n) - acb_mat_set_fmpz_mat(self.val, (val).val) + with cython.critical_section(val): + acb_mat_set_fmpz_mat(self.val, (val).val) elif typecheck(val, fmpq_mat): m = fmpq_mat_nrows((val).val) n = fmpq_mat_ncols((val).val) @@ -568,7 +569,8 @@ cdef class acb_mat(flint_mat): if isinstance(t, arb_mat): return bool(acb_mat_contains(s.val, ((acb_mat(t))).val)) if isinstance(t, fmpz_mat): - return bool(acb_mat_contains_fmpz_mat(s.val, (t).val)) + with cython.critical_section(t): + return bool(acb_mat_contains_fmpz_mat(s.val, (t).val)) if isinstance(t, fmpq_mat): return bool(acb_mat_contains_fmpq_mat(s.val, (t).val)) raise TypeError("expected a matrix of compatible type") diff --git a/src/flint/types/arb_mat.pyx b/src/flint/types/arb_mat.pyx index 331f2b79..b358a286 100644 --- a/src/flint/types/arb_mat.pyx +++ b/src/flint/types/arb_mat.pyx @@ -98,7 +98,8 @@ cdef class arb_mat(flint_mat): m = fmpz_mat_nrows((val).val) n = fmpz_mat_ncols((val).val) arb_mat_init(self.val, m, n) - arb_mat_set_fmpz_mat(self.val, (val).val) + with cython.critical_section(val): + arb_mat_set_fmpz_mat(self.val, (val).val) elif typecheck(val, fmpq_mat): m = fmpq_mat_nrows((val).val) n = fmpq_mat_ncols((val).val) @@ -649,7 +650,8 @@ cdef class arb_mat(flint_mat): if isinstance(t, arb_mat): return bool(arb_mat_contains(s.val, (t).val)) if isinstance(t, fmpz_mat): - return bool(arb_mat_contains_fmpz_mat(s.val, (t).val)) + with cython.critical_section(t): + return bool(arb_mat_contains_fmpz_mat(s.val, (t).val)) if isinstance(t, fmpq_mat): return bool(arb_mat_contains_fmpq_mat(s.val, (t).val)) raise TypeError("expected a matrix of compatible type") diff --git a/src/flint/types/fmpq_mat.pyx b/src/flint/types/fmpq_mat.pyx index dbafdf16..0fe67144 100644 --- a/src/flint/types/fmpq_mat.pyx +++ b/src/flint/types/fmpq_mat.pyx @@ -57,7 +57,8 @@ cdef class fmpq_mat(flint_mat): fmpq_mat_init(self.val, fmpz_mat_nrows((val).val), fmpz_mat_ncols((val).val)) - fmpq_mat_set_fmpz_mat(self.val, (val).val) + with cython.critical_section(val): + fmpq_mat_set_fmpz_mat(self.val, (val).val) elif isinstance(val, (list, tuple)): m = len(val) n = 0 diff --git a/src/flint/types/fmpz_mat.pyx b/src/flint/types/fmpz_mat.pyx index d2d9f3b6..2dde2498 100644 --- a/src/flint/types/fmpz_mat.pyx +++ b/src/flint/types/fmpz_mat.pyx @@ -110,7 +110,8 @@ cdef class fmpz_mat(flint_mat): if len(args) == 1: val = args[0] if typecheck(val, fmpz_mat): - fmpz_mat_init_set(self.val, (val).val) + with cython.critical_section(val): + fmpz_mat_init_set(self.val, (val).val) elif isinstance(val, (list, tuple)): m = len(val) n = 0 @@ -146,6 +147,7 @@ cdef class fmpz_mat(flint_mat): else: raise TypeError("fmpz_mat: expected 1-3 arguments") + @cython.critical_section def __bool__(self): return not fmpz_mat_is_zero(self.val) @@ -156,7 +158,8 @@ cdef class fmpz_mat(flint_mat): t = any_as_fmpz_mat(t) if t is NotImplemented: return t - r = fmpz_mat_equal((s).val, (t).val) + with cython.critical_section(s, t): + r = fmpz_mat_equal((s).val, (t).val) if op == 3: r = not r return r @@ -180,7 +183,8 @@ cdef class fmpz_mat(flint_mat): if i < 0 or i >= self.nrows() or j < 0 or j >= self.ncols(): raise IndexError("index %i,%i exceeds matrix dimensions" % (i, j)) x = fmpz.__new__(fmpz) - fmpz_set(x.val, fmpz_mat_entry(self.val, i, j)) + with cython.critical_section(self): + fmpz_set(x.val, fmpz_mat_entry(self.val, i, j)) return x def __setitem__(self, index, value): @@ -189,8 +193,10 @@ cdef class fmpz_mat(flint_mat): if i < 0 or i >= self.nrows() or j < 0 or j >= self.ncols(): raise IndexError("index %i,%i exceeds matrix dimensions" % (i, j)) c = fmpz(value) # XXX - fmpz_set(fmpz_mat_entry(self.val, i, j), (c).val) + with cython.critical_section(self): + fmpz_set(fmpz_mat_entry(self.val, i, j), (c).val) + @cython.critical_section def det(self): """ Returns the determinant of *self* as an *fmpz*. @@ -236,7 +242,8 @@ cdef class fmpz_mat(flint_mat): raise ValueError("incompatible shapes for matrix addition") u = fmpz_mat.__new__(fmpz_mat) fmpz_mat_init(u.val, fmpz_mat_nrows(sval), fmpz_mat_ncols(sval)) - fmpz_mat_add(u.val, sval, tval) + with cython.critical_section(s, t): + fmpz_mat_add(u.val, sval, tval) return u def __sub__(s, t): @@ -253,14 +260,16 @@ cdef class fmpz_mat(flint_mat): raise ValueError("incompatible shapes for matrix subtraction") u = fmpz_mat.__new__(fmpz_mat) fmpz_mat_init(u.val, fmpz_mat_nrows(sval), fmpz_mat_ncols(sval)) - fmpz_mat_sub(u.val, sval, tval) + with cython.critical_section(s, t): + fmpz_mat_sub(u.val, sval, tval) return u cdef __mul_fmpz(self, fmpz c): cdef fmpz_mat u u = fmpz_mat.__new__(fmpz_mat) fmpz_mat_init(u.val, fmpz_mat_nrows(self.val), fmpz_mat_ncols(self.val)) - fmpz_mat_scalar_mul_fmpz(u.val, self.val, c.val) + with cython.critical_section(self): + fmpz_mat_scalar_mul_fmpz(u.val, self.val, c.val) return u def __mul__(s, t): @@ -274,7 +283,8 @@ cdef class fmpz_mat(flint_mat): raise ValueError("incompatible shapes for matrix multiplication") u = fmpz_mat.__new__(fmpz_mat) fmpz_mat_init(u.val, fmpz_mat_nrows(sval), fmpz_mat_ncols(tval)) - fmpz_mat_mul(u.val, sval, tval) + with cython.critical_section(s, t): + fmpz_mat_mul(u.val, sval, tval) return u else: c = any_as_fmpz(t) @@ -307,7 +317,8 @@ cdef class fmpz_mat(flint_mat): sval = &(s).val[0] u = fmpz_mat.__new__(fmpz_mat) fmpz_mat_init(u.val, fmpz_mat_nrows(sval), fmpz_mat_ncols(sval)) - fmpz_mat_scalar_divexact_fmpz(u.val, sval, (t).val) + with cython.critical_section(s): + fmpz_mat_scalar_divexact_fmpz(u.val, sval, (t).val) # XXX: check for exact division - there should be a better way! if u * t != s: raise DomainError("fmpz_mat division is not exact") @@ -335,10 +346,12 @@ cdef class fmpz_mat(flint_mat): """Return whether *self* is an empty *0xN* or *Nx0* matrix.""" return bool(fmpz_mat_is_empty(self.val)) + @cython.critical_section def is_zero(self): """Return whether *self* is a zero matrix.""" return bool(fmpz_mat_is_zero(self.val)) + @cython.critical_section def is_one(self): """Return whether *self* is the identity matrix.""" return bool(fmpz_mat_is_one(self.val)) @@ -352,8 +365,10 @@ cdef class fmpz_mat(flint_mat): elif self.is_empty(): return True else: - return bool(fmpz_equal_si(fmpz_mat_entry(self.val, 0, 0), -1)) + with cython.critical_section(self): + return bool(fmpz_equal_si(fmpz_mat_entry(self.val, 0, 0), -1)) + @cython.critical_section def is_upper_triangular(self): """Return whether *self* is an upper triangular matrix.""" for i in range(1, fmpz_mat_nrows(self.val)): @@ -362,6 +377,7 @@ cdef class fmpz_mat(flint_mat): return False return True + @cython.critical_section def is_lower_triangular(self): """Return whether *self* is a lower triangular matrix.""" for i in range(fmpz_mat_nrows(self.val)): @@ -378,9 +394,10 @@ cdef class fmpz_mat(flint_mat): """Return whether *self* is a scalar multiple of the identity matrix.""" if not (self.is_square() and self.is_diagonal()): return False - for i in range(fmpz_mat_nrows(self.val)): - if not fmpz_equal(fmpz_mat_entry(self.val, i, i), fmpz_mat_entry(self.val, 0, 0)): - return False + with cython.critical_section(self): + for i in range(fmpz_mat_nrows(self.val)): + if not fmpz_equal(fmpz_mat_entry(self.val, i, i), fmpz_mat_entry(self.val, 0, 0)): + return False return True @classmethod @@ -427,6 +444,7 @@ cdef class fmpz_mat(flint_mat): else: raise ValueError("unable to construct Hadamard matrix of size %i" % n) + @cython.critical_section def is_hadamard(self): """ Determines whether *self* is a Hadamard matrix. @@ -490,6 +508,7 @@ cdef class fmpz_mat(flint_mat): fmpz_mat_randrank(mat.val, global_random_state, rank, bits) return mat + @cython.critical_section def rank(self): """ Returns the rank of *self*. @@ -503,6 +522,7 @@ cdef class fmpz_mat(flint_mat): """ return fmpz_mat_rank(self.val) + @cython.critical_section def inv(self, bint integer=False): """ Returns the inverse matrix of *self*, which by default will @@ -553,6 +573,7 @@ cdef class fmpz_mat(flint_mat): fmpz_clear(den) fmpz_mat_clear(tmp) + @cython.critical_section def transpose(self): """ Returns the transpose of *self*. @@ -613,7 +634,8 @@ cdef class fmpz_mat(flint_mat): raise ValueError("need a square system and compatible right hand side") if not integer: v = fmpq_mat(fmpz_mat_nrows((t).val), fmpz_mat_ncols((t).val)) - result = fmpq_mat_solve_fmpz_mat(v.val, self.val, (t).val) + with cython.critical_section(self, t): + result = fmpq_mat_solve_fmpz_mat(v.val, self.val, (t).val) if not result: raise ZeroDivisionError("singular matrix in solve()") return v @@ -622,7 +644,8 @@ cdef class fmpz_mat(flint_mat): fmpz_mat_init(u.val, fmpz_mat_nrows((t).val), fmpz_mat_ncols((t).val)) d = fmpz.__new__(fmpz) - result = fmpz_mat_solve(u.val, d.val, self.val, (t).val) + with cython.critical_section(self, t): + result = fmpz_mat_solve(u.val, d.val, self.val, (t).val) if not fmpz_is_pm1(d.val): raise ValueError("matrix is not invertible over the integers") u *= d @@ -630,6 +653,7 @@ cdef class fmpz_mat(flint_mat): raise ZeroDivisionError("singular matrix in solve()") return u + @cython.critical_section def _fflu(self): """ Fraction-free LU decomposition of *self*. @@ -752,6 +776,7 @@ cdef class fmpz_mat(flint_mat): return P, L, D, U + @cython.critical_section def rref(self, inplace=False): """ Computes the reduced row echelon form (rref) of *self*, @@ -780,6 +805,7 @@ cdef class fmpz_mat(flint_mat): rank = fmpz_mat_rref((res).val, d.val, self.val) return res, d, rank + @cython.critical_section def nullspace(self): """ Computes a basis for the nullspace of the matrix *A* represented @@ -861,6 +887,7 @@ cdef class fmpz_mat(flint_mat): fmpz_lll(u.val, NULL, ctx) return u + @cython.critical_section def hnf(self, bint transform=False): """ Returns the Hermite normal form of *self*, optionally @@ -886,6 +913,7 @@ cdef class fmpz_mat(flint_mat): fmpz_mat_hnf(H.val, self.val) return H + @cython.critical_section def is_hnf(self): """ Determines whether *self* is in Hermite normal form. @@ -897,6 +925,7 @@ cdef class fmpz_mat(flint_mat): """ return bool(fmpz_mat_is_in_hnf(self.val)) + @cython.critical_section def snf(self): """ Returns the Smith normal form of *self*. @@ -912,6 +941,7 @@ cdef class fmpz_mat(flint_mat): fmpz_mat_snf(H.val, self.val) return H + @cython.critical_section def is_snf(self): """ Determines whether *self* is in Smith normal form. @@ -923,6 +953,7 @@ cdef class fmpz_mat(flint_mat): """ return bool(fmpz_mat_is_in_snf(self.val)) + @cython.critical_section def charpoly(self): """Returns the characteristic polynomial of *self* as an *fmpz_poly*. @@ -945,6 +976,7 @@ cdef class fmpz_mat(flint_mat): fmpz_mat_charpoly(u.val, self.val) return u + @cython.critical_section def minpoly(self): """Returns the minimal polynomial of *self* as an *fmpz_poly*. diff --git a/src/flint/types/nmod_mat.pyx b/src/flint/types/nmod_mat.pyx index a1348582..43f19df5 100644 --- a/src/flint/types/nmod_mat.pyx +++ b/src/flint/types/nmod_mat.pyx @@ -67,7 +67,8 @@ cdef any_as_nmod_mat(obj, nmod_t mod): nmod_mat_init(r.val, fmpz_mat_nrows((x).val), fmpz_mat_ncols((x).val), mod.n) - fmpz_mat_get_nmod_mat(r.val, (x).val) + with cython.critical_section(x): + fmpz_mat_get_nmod_mat(r.val, (x).val) return r return NotImplemented @@ -103,7 +104,8 @@ cdef class nmod_mat(flint_mat): if typecheck(val, fmpz_mat): nmod_mat_init(self.val, fmpz_mat_nrows((val).val), fmpz_mat_ncols((val).val), mod) - fmpz_mat_get_nmod_mat(self.val, (val).val) + with cython.critical_section(val): + fmpz_mat_get_nmod_mat(self.val, (val).val) elif isinstance(val, (list, tuple)): m = len(val) n = 0 From 83aebba03fbc0d1e54b149b0135285f763825107 Mon Sep 17 00:00:00 2001 From: KainanP Date: Sat, 28 Nov 2026 03:42:47 -0300 Subject: [PATCH 2/2] Add changelog entry for gh-456 Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index ff0d5e8a..87c8fab3 100644 --- a/README.md +++ b/README.md @@ -172,9 +172,14 @@ Contributors (0.10.0): - Oscar Benjamin (OB) - Ilia Gradina (IG) - Uri K.H. (UKH) +- KainanP (KP) Changes (0.10.0): +- [gh-456](https://github.com/flintlib/python-flint/pull/456), + Make `fmpz_mat` safe to mutate and read from multiple threads in the + free-threaded build by holding per-object critical sections in its methods + (see [gh-224](https://github.com/flintlib/python-flint/issues/224)). (KP) - [gh-435](https://github.com/flintlib/python-flint/issues/435), Fix a memory leak in `str()` (and so in `repr()`, which uses it unless `flint.ctx.pretty` is `False`) of `fmpz_mpoly`, `fmpq_mpoly`,