From 8cba1da4d305ee7c4a81adbfc34c62e85c6303cc Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sat, 21 Nov 2026 07:50:04 -0600 Subject: [PATCH 01/18] Routine CI maintenance - cibuildwheel v4.3.5, setup-python v7.1.0, create-pull-request v8.1.3 - test.yml: add 3.15t now that conda-forge builds numpy, cffi and cython for it (coverage there is pure Python, so the existing fallback runs the tests without it); replace setup-miniconda's deprecated auto-activate-base and nodefaults channel with auto-activate and conda-remove-defaults - lint.yml: run pre-commit's steps directly, since pre-commit/action's latest release uses actions/cache@v4, which runs on Node.js 20 - pre-commit: validate-pyproject v0.27, flake8 7.5.0, flake8-bugbear 26.11.9, zizmor v1.32.0, check-jsonschema 0.39.0 --- .github/workflows/lint.yml | 15 +++++++++++++-- .github/workflows/test.yml | 12 +++++++----- .github/workflows/update_graphblas.yml | 4 ++-- .github/workflows/wheels.yml | 2 +- .pre-commit-config.yaml | 12 ++++++------ 5 files changed, 29 insertions(+), 16 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index b05ed8a..102520c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -23,7 +23,18 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.11" - - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 + # The steps of pre-commit/action, spelled out because its latest release + # (v3.0.1) uses actions/cache@v4, which runs on the deprecated Node.js 20. + - name: Install pre-commit + run: | + python -m pip install pre-commit + python -m pip freeze --local + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.cache/pre-commit + key: pre-commit-3|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }} + - name: Run pre-commit + run: pre-commit run --show-diff-on-failure --color=always --all-files diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8f16332..abb544b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,8 +29,7 @@ jobs: # os: ["ubuntu-latest"] # source: ["source"] # A trailing "t" means the free-threaded (no-GIL) build of that version. - # TODO: add "3.15t" once conda-forge builds cffi and numpy for cp315t. - python-version: ["3.11", "3.12", "3.13", "3.14", "3.14t", "3.15"] + python-version: ["3.11", "3.12", "3.13", "3.14", "3.14t", "3.15", "3.15t"] steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -63,10 +62,13 @@ jobs: with: auto-update-conda: true environment-file: environment-ci.yml - channels: conda-forge,nodefaults + # setup-miniconda deprecated a `nodefaults` channel here in favor of + # conda-remove-defaults (environment.yml keeps it for conda itself). + channels: conda-forge + conda-remove-defaults: true channel-priority: strict activate-environment: suitesparse-graphblas - auto-activate-base: false + auto-activate: false - name: GraphBLAS (from conda-forge) if: (contains(matrix.source, 'conda-forge')) run: | @@ -98,7 +100,7 @@ jobs: run: | # Cython's coverage plugin (see [tool.coverage.run] in pyproject.toml) # needs coverage's C tracer. Where conda-forge has no compiled build of - # coverage for a Python (3.15, for now), it installs a pure-Python build + # coverage for a Python (3.15t, for now), it installs a pure-Python build # that lacks the tracer. There, loading the plugin raises ImportError and # every `coverage run` dies before it runs anything, so run the tests # directly instead. diff --git a/.github/workflows/update_graphblas.yml b/.github/workflows/update_graphblas.yml index f5c0fb6..ad67e70 100644 --- a/.github/workflows/update_graphblas.yml +++ b/.github/workflows/update_graphblas.yml @@ -33,7 +33,7 @@ jobs: fetch-depth: 0 persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.11" @@ -44,7 +44,7 @@ jobs: shell: bash - name: Create Pull Request - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1 + uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3 with: # See documentation: https://github.com/peter-evans/create-pull-request # Action behavior: https://github.com/peter-evans/create-pull-request#action-behaviour diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 818e255..8e7aee3 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -148,7 +148,7 @@ jobs: brew fetch --retry libomp && brew reinstall libomp echo "MACOSX_DEPLOYMENT_TARGET=$(otool -l "$(brew --prefix libomp)/lib/libomp.dylib" | grep minos | awk '{print $2}')" >> "$GITHUB_ENV" - - uses: pypa/cibuildwheel@8c2dcd2e96041a619f5ff03c9638d7941e2553a4 # v4.3.3 + - uses: pypa/cibuildwheel@f9b966cfadf4109556cadc5bb39ddb72d0ce664e # v4.3.5 with: output-dir: wheelhouse env: diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 86cebb5..671fa60 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -31,7 +31,7 @@ repos: - id: name-tests-test args: ["--pytest-test-first"] - repo: https://github.com/abravalheri/validate-pyproject - rev: '0.26' + rev: 'v0.27' hooks: - id: validate-pyproject name: Validate pyproject.toml @@ -54,15 +54,15 @@ repos: hooks: - id: black - repo: https://github.com/PyCQA/flake8 - rev: 7.4.1 + rev: 7.5.0 hooks: - id: flake8 args: ["--config=.flake8"] additional_dependencies: &flake8_dependencies # These versions need updated manually - - flake8==7.4.1 + - flake8==7.5.0 - flake8-comprehensions==3.17.0 - - flake8-bugbear==26.9.30 + - flake8-bugbear==26.11.9 # - flake8-simplify==0.22.0 - repo: https://github.com/asottile/yesqa rev: v1.5.0 @@ -93,11 +93,11 @@ repos: hooks: - id: actionlint - repo: https://github.com/zizmorcore/zizmor-pre-commit - rev: v1.31.1 + rev: v1.32.0 hooks: - id: zizmor - repo: https://github.com/python-jsonschema/check-jsonschema - rev: 0.38.2 + rev: 0.39.0 hooks: - id: check-dependabot - id: check-github-workflows From 00c209787ec6f0a371268ff9e1416f2bd3c2b1b5 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sat, 21 Nov 2026 07:50:13 -0600 Subject: [PATCH 02/18] Update to SuiteSparse:GraphBLAS 10.5.3 10.5.3 fixes one crash (changing the integer bit-width of a matrix with pending zombies). The regenerated headers and source.c are unchanged, and GB_control.h is the same as in 10.5.2, so suitesparse.sh's comment about which types lack factory kernels still holds. --- GB_VERSION.txt | 2 +- suitesparse.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GB_VERSION.txt b/GB_VERSION.txt index a39233b..1e9c35f 100644 --- a/GB_VERSION.txt +++ b/GB_VERSION.txt @@ -1 +1 @@ -10.5.2 +10.5.3 diff --git a/suitesparse.sh b/suitesparse.sh index d44b5c9..c784656 100755 --- a/suitesparse.sh +++ b/suitesparse.sh @@ -98,7 +98,7 @@ cd "GraphBLAS-${VERSION}/build" || exit # Disable optimizing some rarely-used types for significantly faster builds and significantly smaller wheel size. # Also the build with all types enabled sometimes stalls on GitHub Actions. Probably due to exceeded resource limits. # These can still be used, they'll just have reduced performance (AFAIK similar to UDTs). -# GraphBLAS's own GB_control.h (as of 10.5.2) already disables INT8, INT16, UINT8 and UINT16, so +# GraphBLAS's own GB_control.h (as of 10.5.3) already disables INT8, INT16, UINT8 and UINT16, so # the types left without FactoryKernels here are those four plus FC32, FC64 and UINT32. # shellcheck disable=SC2129 # echo "#define GxB_NO_BOOL 1" >> ../Source/GB_control.h # From 8ea6601f865beca51530a3b55eb34d2f276cf109 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sat, 21 Nov 2026 07:50:16 -0600 Subject: [PATCH 03/18] create_headers.py: stop when the preprocessor fails The preprocessor ran as `gcc ... | sed ... > out` in a shell, whose exit status is sed's. When gcc failed, the script went on to write empty headers and source.c and reported success. It does that with pycparser's PyPI wheels, which leave out the fake libc headers that conda-forge's pycparser ships. Run gcc without a shell and fail on its exit status, do the " complex " -> " _Complex " substitution in Python, and say clearly when the fake libc headers are missing. With conda-forge's pycparser the output is byte-identical. AGENTS.md notes which pycparser to use. --- AGENTS.md | 4 +++- suitesparse_graphblas/create_headers.py | 25 ++++++++++++++++--------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index aeaf36c..51aaafe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,7 +106,9 @@ This script regenerates **`suitesparse_graphblas.h`**, **`suitesparse_graphblas_ and **`source.c`** from an upstream `GraphBLAS.h`. It: - Copies `GraphBLAS.h` from the install, runs the C preprocessor (using pycparser's - `fake_libc_include`), and parses the result with pycparser. + `fake_libc_include`), and parses the result with pycparser. Use conda-forge's pycparser: + the wheels on PyPI leave `fake_libc_include` out. Pass `--graphblas ` + unless GraphBLAS is installed in `sys.prefix`. - Emits a cleaned-up header that cffi can `cdef()`, plus a complex-free variant for platforms (notably MSVC) where `_Complex` types don't work. - Manually tracks `DEFINES`, `CHAR_DEFINES`, `IGNORE_DEFINES`, and `DEPRECATED` sets. diff --git a/suitesparse_graphblas/create_headers.py b/suitesparse_graphblas/create_headers.py index 59d5e8c..9a82471 100644 --- a/suitesparse_graphblas/create_headers.py +++ b/suitesparse_graphblas/create_headers.py @@ -388,9 +388,8 @@ def visit_Struct(self, node): def get_ast(filename): - fake_include = os.path.dirname(pycparser.__file__) + "utils/fake_libc_include" - ast = parse_file(filename, cpp_args=f"-I{fake_include}") - return ast + # filename has already been through the preprocessor + return parse_file(filename) def get_groups(ast): @@ -891,13 +890,21 @@ def main(): # Run it through the preprocessor print(f"Step 2: run preprocessor to create {processed_h}") include = os.path.join(os.path.dirname(pycparser.__file__), "utils", "fake_libc_include") - command = ( - f"gcc -nostdinc -E -I{include} {graphblas_h} " - f"| sed 's/ complex / _Complex /g' > {processed_h}" + if not os.path.isdir(include): + # pycparser's wheels on PyPI leave these headers out; conda-forge's package has them. + raise FileNotFoundError( + f"pycparser's fake libc headers not found: {include}\n" + "Install pycparser from conda-forge, which includes them." + ) + # Not a shell pipeline: a failure in the preprocessor must stop us here, or the steps + # below would write empty headers. + res = subprocess.run( + ["gcc", "-nostdinc", "-E", f"-I{include}", graphblas_h], + stdout=subprocess.PIPE, + check=True, ) - res = subprocess.run(command, shell=True) - if res.returncode != 0: - raise RuntimeError("Subprocess command failed", res) + with open(processed_h, "wb") as f: + f.write(res.stdout.replace(b" complex ", b" _Complex ")) # Create final header file print(f"Step 3: parse header file to create {final_h}") From a4b69a3f77d45a5336fc4ba51b6b35a3f7e8dc97 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sat, 21 Nov 2026 07:50:20 -0600 Subject: [PATCH 04/18] claim_buffer_2d: support subarray dtypes With a subarray dtype such as (" nrows * ncols) if spare else (n == nrows * ncols) + array = claim_buffer_2d(ffi, Ax[0], n, nrows, ncols, dtype, is_c_order) + assert array.shape == (nrows, ncols) + dtype.shape + assert array.dtype == dtype.base + np.testing.assert_array_equal(array, values[:nrows, :ncols]) + # An exact fit owns the buffer, so it can be given back without a copy; otherwise its + # base does. Either way NumPy must free it with the allocator that allocated it. + assert array.flags.owndata != spare + assert can_unclaim_buffer(array if array.flags.owndata else array.base) + + def test_can_unclaim_buffer(): array = np.arange(10) assert can_unclaim_buffer(array) diff --git a/suitesparse_graphblas/utils.pyx b/suitesparse_graphblas/utils.pyx index 1330f7d..04c17e8 100644 --- a/suitesparse_graphblas/utils.pyx +++ b/suitesparse_graphblas/utils.pyx @@ -271,13 +271,17 @@ cpdef ndarray claim_buffer_2d( bint is_c_order, object arena=None, ): - """Like ``claim_buffer``, but return a 2-d ``nrows`` by ``ncols`` array.""" + """Like ``claim_buffer``, but return a 2-d ``nrows`` by ``ncols`` array. + + For a subarray dtype, the element axes come last: shape ``(nrows, ncols) + dtype.shape``. + """ cdef: size_t size = nrows * ncols ndarray array uintptr_t ptr npy_intp dims[2] - int flags = NPY_ARRAY_WRITEABLE + npy_intp strides[2] + npy_intp *strides_ptr = NULL if cdata_size == size: handler = _handler(_resolve_arena(arena)) ptr = int(ffi.cast("uintptr_t", cdata)) @@ -286,18 +290,23 @@ cpdef ndarray claim_buffer_2d( dims[0] = nrows dims[1] = ncols if not is_c_order: - flags |= NPY_ARRAY_F_CONTIGUOUS + # Strides, not NPY_ARRAY_F_CONTIGUOUS: NumPy appends the element axes of a + # subarray dtype, which that flag would make the slowest-varying axes + strides[0] = dtype.itemsize + strides[1] = nrows * dtype.itemsize + strides_ptr = strides Py_INCREF(dtype) array = PyArray_NewFromDescr( - ndarray, dtype, 2, dims, NULL, ptr, flags, NULL + ndarray, dtype, 2, dims, strides_ptr, ptr, NPY_ARRAY_WRITEABLE, NULL ) own_data(array, handler) - elif cdata_size > size: # pragma: no cover + elif cdata_size > size: array = claim_buffer(ffi, cdata, cdata_size, dtype, arena) + # claim_buffer appends the element axes of a subarray dtype; keep them last if is_c_order: - array = array[:size].reshape((nrows, ncols)) + array = array[:size].reshape((nrows, ncols) + dtype.shape) else: - array = array[:size].reshape((ncols, nrows)).T + array = array[:size].reshape((ncols, nrows) + dtype.shape).swapaxes(0, 1) else: # pragma: no cover raise ValueError( f"Buffer size too small: {cdata_size}. " From 9870d35ed4c0436b4f7c4a76bcd163c0a91d884f Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sat, 21 Nov 2026 23:40:24 -0600 Subject: [PATCH 05/18] Build musllinux aarch64 wheels The aarch64 job has skipped musllinux since #106 (2023-10), when NumPy had no musllinux aarch64 wheels and that job ran under QEMU. NumPy has had them since 1.26.2 (2023-11), and the job runs on a native arm runner since #142, so build them in a job of their own, as for x86_64: CIBW_BEFORE_ALL builds GraphBLAS once per container image, and the musl build needs its own. --- .github/workflows/wheels.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 8e7aee3..f69063c 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -85,9 +85,16 @@ jobs: # Linux aarch64 — native ARM runner (no QEMU emulation needed) - os: ubuntu-24.04-arm cibw_archs: "auto" - # numpy wheels not available for aarch64 musllinux + # skip musllinux (built in the next job) cibw_skip: "*musl*" + # Linux aarch64 musllinux, on its own runner for the same reason as x86_64's + - os: ubuntu-24.04-arm + cibw_archs: "auto" + arch_note: "musl" + # skip manylinux (built in the previous job) + cibw_skip: "*many*" + # macOS x86_64 — macos-15-intel is the last Intel macOS runner. # libomp from Homebrew determines the minimum supported macOS version. - os: macos-15-intel From 2c548c4714304746b1d1de1a4d58915db527b7b4 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sat, 21 Nov 2026 23:57:08 -0600 Subject: [PATCH 06/18] claim_buffer, claim_buffer_2d: free the memory if claiming fails GraphBLAS has handed the memory over by the time it is claimed, so if claiming raises (an array too big for NumPy, or a buffer smaller than nrows * ncols), nothing else would free it. Free it with the arena's free function instead. An invalid arena still leaves it alone, since then there is no free function to use. --- suitesparse_graphblas/tests/test_memory.py | 47 +++++++++++++ suitesparse_graphblas/utils.pyx | 79 ++++++++++++++-------- 2 files changed, 97 insertions(+), 29 deletions(-) diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index e6407ac..1abec01 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -233,6 +233,53 @@ def test_claim_buffer(): claim_buffer_2d(ffi, ffi.NULL, 6, 2, 3, int64, True) +# An arena that records the addresses it frees, made once (arenas can't be changed) +_recording_arena = {} + + +def recording_arena(): + if not _recording_arena: + blocks = {} + freed = [] + + @ffi.callback("void *(size_t)") + def malloc(size): + block = ffi.new("char[]", size or 1) + blocks[int(ffi.cast("uintptr_t", block))] = block + return block + + @ffi.callback("void (void *)") + def free(ptr): + address = int(ffi.cast("uintptr_t", ptr)) + blocks.pop(address, None) + freed.append(address) + + k = lib.GxB_NARENAS - 2 # not arena 5: test_can_unclaim_buffer needs it uninitialized + assert lib.GxB_arena_init(k, malloc, ffi.NULL, ffi.NULL, free) == lib.GrB_SUCCESS + _recording_arena.update(k=k, freed=freed, callbacks=(malloc, free)) + return _recording_arena["k"], _recording_arena["freed"] + + +@pytest.mark.skipif(sys.platform == "emscripten", reason="needs cffi callbacks") +def test_claim_buffer_frees_on_error(): + # GraphBLAS has handed the buffer over, so if claiming it fails, nothing else frees it + k, freed = recording_arena() + int64 = np.dtype(np.int64) + huge = sys.maxsize // 4 # too many int64s for NumPy + for claim, match in [ + (lambda ptr: claim_buffer(ffi, ptr, huge, int64, k), "too big"), + (lambda ptr: claim_buffer_2d(ffi, ptr, huge, 1, huge, int64, False, k), "too big"), + (lambda ptr: claim_buffer_2d(ffi, ptr, 5, 2, 3, int64, True, k), "too small"), + ]: + array = empty(6, int64, arena=k) + ptr = ffi.cast("void*", array.ctypes.data) + unclaim_buffer(array, arena=k) # now nothing owns it, as after a GraphBLAS export + freed.clear() + with pytest.raises(ValueError, match=match): + claim(ptr) + assert freed == [int(ffi.cast("uintptr_t", ptr))] + + @pytest.mark.parametrize( "dtype", ["ptr) + + cdef str _why_not_ownable(object array, object handler): # Why GraphBLAS can't take ownership of the data of `array` (to free with `handler`), # or None if it can. @@ -245,18 +252,26 @@ cpdef ndarray claim_buffer(object ffi, object cdata, size_t size, dtype_t dtype, ``arena`` is the GraphBLAS arena that allocated the memory (default: the global data arena); NumPy will free the memory with that arena's allocator. + + The memory is claimed even if this raises: then it is freed, since nothing else owns + it. Only an invalid ``arena`` (or ``cdata``) leaves it alone, since then it can't be. """ cdef: npy_intp dims = size uintptr_t ptr = int(ffi.cast("uintptr_t", cdata)) + int k = _resolve_arena(arena) ndarray array - handler = _handler(_resolve_arena(arena)) + handler = _handler(k) if ptr == 0 and size != 0: raise ValueError(f"Unable to claim {size} elements from a NULL pointer") Py_INCREF(dtype) - array = PyArray_NewFromDescr( - ndarray, dtype, 1, &dims, NULL, ptr, NPY_ARRAY_WRITEABLE, NULL - ) + try: + array = PyArray_NewFromDescr( + ndarray, dtype, 1, &dims, NULL, ptr, NPY_ARRAY_WRITEABLE, NULL + ) + except BaseException: + _free_claimed(k, ptr) + raise own_data(array, handler) return array @@ -274,44 +289,50 @@ cpdef ndarray claim_buffer_2d( """Like ``claim_buffer``, but return a 2-d ``nrows`` by ``ncols`` array. For a subarray dtype, the element axes come last: shape ``(nrows, ncols) + dtype.shape``. + If the buffer holds more than ``nrows * ncols`` elements, the array is a view of a 1-d + array that owns the buffer. + As with ``claim_buffer``, the memory is freed if this raises. """ cdef: size_t size = nrows * ncols + uintptr_t ptr = int(ffi.cast("uintptr_t", cdata)) + int k = _resolve_arena(arena) ndarray array - uintptr_t ptr npy_intp dims[2] npy_intp strides[2] npy_intp *strides_ptr = NULL - if cdata_size == size: - handler = _handler(_resolve_arena(arena)) - ptr = int(ffi.cast("uintptr_t", cdata)) - if ptr == 0 and size != 0: - raise ValueError(f"Unable to claim {size} elements from a NULL pointer") - dims[0] = nrows - dims[1] = ncols - if not is_c_order: - # Strides, not NPY_ARRAY_F_CONTIGUOUS: NumPy appends the element axes of a - # subarray dtype, which that flag would make the slowest-varying axes - strides[0] = dtype.itemsize - strides[1] = nrows * dtype.itemsize - strides_ptr = strides - Py_INCREF(dtype) - array = PyArray_NewFromDescr( - ndarray, dtype, 2, dims, strides_ptr, ptr, NPY_ARRAY_WRITEABLE, NULL - ) - own_data(array, handler) - elif cdata_size > size: - array = claim_buffer(ffi, cdata, cdata_size, dtype, arena) + if cdata_size > size: + array = claim_buffer(ffi, cdata, cdata_size, dtype, k) # claim_buffer appends the element axes of a subarray dtype; keep them last if is_c_order: - array = array[:size].reshape((nrows, ncols) + dtype.shape) - else: - array = array[:size].reshape((ncols, nrows) + dtype.shape).swapaxes(0, 1) - else: # pragma: no cover + return array[:size].reshape((nrows, ncols) + dtype.shape) + return array[:size].reshape((ncols, nrows) + dtype.shape).swapaxes(0, 1) + handler = _handler(k) + if cdata_size < size: + _free_claimed(k, ptr) raise ValueError( f"Buffer size too small: {cdata_size}. " f"Unable to create matrix of size {nrows}x{ncols} = {size}" ) + if ptr == 0 and size != 0: + raise ValueError(f"Unable to claim {size} elements from a NULL pointer") + dims[0] = nrows + dims[1] = ncols + if not is_c_order: + # Strides, not NPY_ARRAY_F_CONTIGUOUS: NumPy appends the element axes of a + # subarray dtype, which that flag would make the slowest-varying axes + strides[0] = dtype.itemsize + strides[1] = nrows * dtype.itemsize + strides_ptr = strides + Py_INCREF(dtype) + try: + array = PyArray_NewFromDescr( + ndarray, dtype, 2, dims, strides_ptr, ptr, NPY_ARRAY_WRITEABLE, NULL + ) + except BaseException: + _free_claimed(k, ptr) + raise + own_data(array, handler) return array From 0e89ff6f56c7d175955f6e1407a3f40b5ebcf185 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sat, 21 Nov 2026 23:57:11 -0600 Subject: [PATCH 07/18] give_buffer: copy elements in the array's memory order GraphBLAS reads the bytes of the buffer it is given, so a copy must hold them in the order the array has them in memory. The copy was in C order unless the array was F-contiguous, which reordered other layouts that fill their data without gaps, such as the column order claim_buffer_2d gives a subarray dtype. Arrays with gaps or a backwards axis are still copied in C order. --- suitesparse_graphblas/tests/test_memory.py | 14 ++++++++++++ suitesparse_graphblas/utils.pyx | 26 +++++++++++++++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index 1abec01..121f382 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -429,6 +429,20 @@ def test_give_buffer(): with pytest.raises(ValueError, match="without copying: it does not own its data"): load(np.arange(10)[::2], copy=False) + # A copy has the elements in the order the array has them in memory, or C order if + # they have gaps + data = np.arange(24, dtype=np.int64) + for array, expected in [ + (data.reshape(2, 3, 4), data), + (data.reshape(4, 3, 2).T, data), + (data.reshape(3, 2, 4).swapaxes(0, 1), data), + (data.reshape(6, 1, 4)[::2].T, data.reshape(6, 1, 4)[::2].T.ravel()), + (np.broadcast_to(data[:4], (3, 4)), np.tile(data[:4], 3)), + (np.asarray(data[5]), data[5:6]), + ]: + with give_buffer(array, copy=True) as (X, nbytes, _): + assert ffi.buffer(X[0], nbytes)[:] == expected.tobytes() + # GraphBLAS didn't take ownership, so the array keeps it array = np.arange(5, dtype=np.int64) v = vector.vector_new(lib.GrB_INT64) diff --git a/suitesparse_graphblas/utils.pyx b/suitesparse_graphblas/utils.pyx index a90f807..b49364f 100644 --- a/suitesparse_graphblas/utils.pyx +++ b/suitesparse_graphblas/utils.pyx @@ -231,6 +231,23 @@ cdef str _why_not_ownable(object array, object handler): ) +cdef list _memory_order(object array): + # The axes of `array` from slowest- to fastest-varying in memory if its elements fill + # its data without gaps, every axis running forwards (C or F order, or, with a subarray + # dtype, the column order of `claim_buffer_2d`), else in C order. Copied in this order, + # its bytes stay the same. + shape = array.shape + strides = array.strides + axes = sorted(range(array.ndim), key=strides.__getitem__, reverse=True) + stride = array.itemsize + for i in reversed(axes): + if shape[i] != 1: + if strides[i] != stride: + return list(range(array.ndim)) + stride *= shape[i] + return axes + + cpdef int call_gxb_init(object ffi, object lib, int mode): # We need to call `GxB_init`, but we didn't compile Cython against GraphBLAS. So, we get it from cffi. # Step 1: ffi.addressof(lib, "GxB_init") @@ -446,6 +463,9 @@ def give_buffer(array, ctype="void*", *, copy=None, arena=None): None (default): hand over the data of ``array`` itself if GraphBLAS can own it (see ``can_unclaim_buffer``), else a copy. True: always hand over a copy, leaving ``array`` unchanged. False: never copy; raise ValueError if GraphBLAS can't own it. + A copy has the elements in the order ``array`` has them in memory, so GraphBLAS + reads the same bytes either way; C order if they have gaps or an axis runs backwards + (e.g., a strided or reversed view). arena : int, optional The GraphBLAS arena that will own the data (default: the global data arena). @@ -482,9 +502,9 @@ def give_buffer(array, ctype="void*", *, copy=None, arena=None): f"GraphBLAS cannot take ownership of the data of this array without copying: {why_not}" ) if copy or why_not is not None: - order = "F" if array.flags.f_contiguous and not array.flags.c_contiguous else "C" - buf = empty(array.shape, array.dtype, order, k) - np.copyto(buf, array, casting="no") + axes = _memory_order(array) + buf = empty([array.shape[i] for i in axes], array.dtype, "C", k) + np.copyto(buf, array.transpose(axes), casting="no") else: buf = array ptr = _ffi.new(f"{ctype}*", _ffi.cast(ctype, PyArray_DATA(buf))) From e27b2aab707704c77ea7e09c9b7748554d78e6aa Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sat, 21 Nov 2026 23:57:13 -0600 Subject: [PATCH 08/18] test_claim_buffer_2d: make exact and spare buffers directly Resizing a matrix to get spare values relied on GraphBLAS keeping the buffer. Instead, pack a buffer of exactly the size to test and export it again, which hands it back unchanged. Also check that giving the claimed array back, as itself or as a copy, gives GraphBLAS the layout it exported. --- suitesparse_graphblas/tests/test_memory.py | 44 +++++++++++++--------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index 121f382..5849f1c 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -292,39 +292,47 @@ def test_claim_buffer_2d(dtype, is_c_order, spare): # element axes last. dtype = np.dtype(dtype) nrows, ncols = (2, 3) if is_c_order else (3, 2) - i = np.arange(3)[:, None, None] - j = np.arange(3)[None, :, None] + i = np.arange(nrows)[:, None, None] + j = np.arange(ncols)[None, :, None] k = np.arange(max(1, dtype.itemsize // dtype.base.itemsize)) - values = (100 * i + 10 * j + k).astype(dtype.base).reshape((3, 3) + dtype.shape) - shape = (3, 3) if spare else (nrows, ncols) + values = (100 * i + 10 * j + k).astype(dtype.base).reshape((nrows, ncols) + dtype.shape) T = grb_type.grb_type_new(dtype.itemsize) - A = matrix.matrix_new(T[0], *shape) + A = matrix.matrix_new(T[0], nrows, ncols) matrix.matrix_set_format(A, lib.GxB_BY_ROW if is_c_order else lib.GxB_BY_COL) - for r in range(shape[0]): - for c in range(shape[1]): + for r in range(nrows): + for c in range(ncols): x = ffi.from_buffer(values[r, c : c + 1]) check_status(A, lib.GrB_Matrix_setElement_UDT(A[0], x, r, c)) - if spare: - # Dropping the last row of a by-row matrix (or column of a by-column one) keeps its - # buffer, which then has spare values at the end - check_status(A, lib.GrB_Matrix_resize(A[0], nrows, ncols)) + export = lib.GxB_Matrix_export_FullR if is_c_order else lib.GxB_Matrix_export_FullC + pack = lib.GxB_Matrix_pack_FullR if is_c_order else lib.GxB_Matrix_pack_FullC Ax = ffi.new("void**") Ax_size = ffi.new("GrB_Index*") - export = lib.GxB_Matrix_export_FullR if is_c_order else lib.GxB_Matrix_export_FullC - info = export( - A, T, ffi.new("GrB_Index*"), ffi.new("GrB_Index*"), Ax, Ax_size, ffi.NULL, ffi.NULL - ) - check_status(A, info) + args = (T, ffi.new("GrB_Index*"), ffi.new("GrB_Index*"), Ax, Ax_size, ffi.NULL, ffi.NULL) + check_status(A, export(A, *args)) + # Pack the values GraphBLAS laid out back in a buffer of exactly the size to test (with + # room for two more if `spare`), which export then hands back as it is + nbytes = nrows * ncols * dtype.itemsize + buf = empty(nbytes + 2 * spare * dtype.itemsize, np.uint8) + buf[:nbytes] = claim_buffer(ffi, Ax[0], Ax_size[0], np.dtype(np.uint8))[:nbytes] + A = matrix.matrix_new(T[0], nrows, ncols) + with give_buffer(buf) as (X, size, _): + check_status(A, pack(A[0], X, size, False, ffi.NULL)) + check_status(A, export(A, *args)) n = Ax_size[0] // dtype.itemsize - assert (n > nrows * ncols) if spare else (n == nrows * ncols) array = claim_buffer_2d(ffi, Ax[0], n, nrows, ncols, dtype, is_c_order) + assert n == nrows * ncols + 2 * spare assert array.shape == (nrows, ncols) + dtype.shape assert array.dtype == dtype.base - np.testing.assert_array_equal(array, values[:nrows, :ncols]) + np.testing.assert_array_equal(array, values) # An exact fit owns the buffer, so it can be given back without a copy; otherwise its # base does. Either way NumPy must free it with the allocator that allocated it. assert array.flags.owndata != spare assert can_unclaim_buffer(array if array.flags.owndata else array.base) + # Given back, as itself or as a copy, it has the layout GraphBLAS exported + layout = values if is_c_order else values.swapaxes(0, 1) + for copy in [None, True]: + with give_buffer(array, copy=copy) as (X, nbytes, _): + assert ffi.buffer(X[0], nbytes)[:] == np.ascontiguousarray(layout).tobytes() def test_can_unclaim_buffer(): From cc9e862055598258a95213bb79a394232eb29f7f Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sun, 22 Nov 2026 21:29:10 -0600 Subject: [PATCH 09/18] claim_buffer_2d: keep a nested subarray dtype's axes with spare values When the base of a subarray dtype is a subarray dtype too, as with ((" size: - array = claim_buffer(ffi, cdata, cdata_size, dtype, k) - # claim_buffer appends the element axes of a subarray dtype; keep them last + values = claim_buffer(ffi, cdata, cdata_size, dtype, k)[:size] + # claim_buffer appends the element axes of a subarray dtype (more than dtype.shape + # if its base is one too); keep them last + element_shape = values.shape[1:] if is_c_order: - return array[:size].reshape((nrows, ncols) + dtype.shape) - return array[:size].reshape((ncols, nrows) + dtype.shape).swapaxes(0, 1) + return values.reshape((nrows, ncols) + element_shape) + return values.reshape((ncols, nrows) + element_shape).swapaxes(0, 1) handler = _handler(k) if cdata_size < size: _free_claimed(k, ptr) From c9344c513ba3da18f273cae478f4f60d2dccd4b3 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sun, 22 Nov 2026 21:51:55 -0600 Subject: [PATCH 10/18] test_claim_buffer_frees_on_error: skip on PyPy The test's arena allocates and frees with Python cffi callbacks, which utils.pyx calls directly. PyPy runs C extension code holding the GIL, and a cffi callback takes the GIL on entry without checking whether its own thread holds it, so the first call (from `empty`) waits forever. --- suitesparse_graphblas/tests/test_memory.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index 6c972e2..291d08d 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -261,6 +261,13 @@ def free(ptr): @pytest.mark.skipif(sys.platform == "emscripten", reason="needs cffi callbacks") +# PyPy runs C extension code (utils.pyx here) holding the GIL, and a cffi callback takes the +# GIL on entry without checking whether its own thread holds it, so the first call into this +# arena from utils.pyx (`empty`) never returns. +@pytest.mark.skipif( + sys.implementation.name == "pypy", + reason="on PyPy, a cffi callback called from a C extension module deadlocks", +) def test_claim_buffer_frees_on_error(): # GraphBLAS has handed the buffer over, so if claiming it fails, nothing else frees it k, freed = recording_arena() From a8f81791572b9d9151cf5d73ba7b13bdb4dfe2e1 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Sun, 22 Nov 2026 21:55:27 -0600 Subject: [PATCH 11/18] utils: say that on PyPy an arena's functions must be C functions PyPy runs extension modules holding the GIL, and a cffi callback takes the GIL on entry without checking whether its own thread holds it, so a Python callback that psg or NumPy calls as an arena's function waits forever. --- suitesparse_graphblas/utils.pyx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/suitesparse_graphblas/utils.pyx b/suitesparse_graphblas/utils.pyx index ba5a598..2472661 100644 --- a/suitesparse_graphblas/utils.pyx +++ b/suitesparse_graphblas/utils.pyx @@ -20,6 +20,10 @@ array with the array's memory handler (NEP 49). So: ``unclaim_buffer`` are the lower-level pieces. - ``empty`` makes an array that GraphBLAS can always take ownership of. +On PyPy, an arena's functions must be C functions: PyPy runs extension modules (this one, +and NumPy when it frees an array) holding the GIL, and a Python cffi callback they call +waits for the GIL forever. + Each function takes an optional ``arena``. It defaults to GraphBLAS's global data arena (``GxB_ARENA_DATA`` of ``GrB_GLOBAL``; 0 unless changed), which is where GraphBLAS allocates, and where it expects memory it is given to be from, unless the calling thread From d87165de5582adaf66580932e9ed75a6b66030db Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 10:20:51 -0600 Subject: [PATCH 12/18] Pyodide wheels: keep wasm-opt from inlining large single-caller functions At -O2, wasm-opt inlines every function that has one caller, whatever its size, so it inlined the FactoryKernels into the switches that call them. The module had functions of 3.4 MB (GB_AxB_saxpy3), 2.9 MB (GB_add_phase2), 1.2 MB (GB_AxB_saxbit), 1.1 MB (GB_AxB_dot3) and 1.0 MB (GB_AxB_dot2). Once they were hot, Chrome's optimizing compiler spent 4 to 5 GB of memory on them, and the kernels ran on baseline code meanwhile. With --one-caller-inline-max-function-size=1000 the largest GraphBLAS function is about 0.2 MB. In headless Chrome (Pyodide 314.0.8, python-graphblas with graphblas-algorithms), a page with a 1e6-edge graph peaks at 1.2 GB instead of 4.9 to 5.0 GB, PageRank takes 4.1 to 4.3 ms instead of 7.5 to 8.1 ms, and a first BFS takes 0.02 s instead of 0.21 s. The wheel grows from 3.10 MB to 3.84 MB, and the link takes 20 s instead of 99 s. It is a link setting, so it goes in LDFLAGS: in EMCC_CFLAGS, emcc warns at each of the 3,102 GraphBLAS compiles that it is ignored there. The cp313 wheels' Emscripten 4.0.9 (wasm-opt 123) supports the option too. PR builds use GRAPHBLAS_COMPACT, which has no FactoryKernels, so only release builds change. --- .github/workflows/wheels.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index f69063c..a165b66 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -185,9 +185,17 @@ jobs: # finished with GraphBLAS after 30 CPU-minutes; -O2 takes about a minute. emcc # appends EMCC_CFLAGS to every command, so its -O2 is the one that counts (also for # compiling GraphBLAS, which is then smaller and no slower). + # --one-caller-inline-max-function-size=1000 keeps wasm-opt from inlining a large + # function into its only caller. Without it, wasm-opt inlined the FactoryKernels + # into the switches that call them, making functions of up to 3.4 MB (GB_AxB_saxpy3, + # GB_add_phase2, GB_AxB_dot3 and others). Chrome's optimizing compiler then used + # 4 to 5 GB of memory on them, and kernels ran unoptimized meanwhile. With it, the + # largest GraphBLAS function is 0.2 MB, a page using GraphBLAS peaks near 1 GB, + # kernels are as fast or faster, and the wheel is about 0.7 MB larger. It is a + # link setting, so it goes in LDFLAGS (in EMCC_CFLAGS, emcc warns at each compile). CIBW_BEFORE_ALL_PYODIDE: "" CIBW_BEFORE_BUILD_PYODIDE: bash suitesparse.sh ${{ env.GB_VERSION_REF }} - CIBW_ENVIRONMENT_PYODIDE: SUITESPARSE_EMSCRIPTEN=1 GRAPHBLAS_PREFIX=/tmp/graphblas-wasm GraphBLAS_ROOT=/tmp/graphblas-wasm EMCC_CFLAGS=-O2 + CIBW_ENVIRONMENT_PYODIDE: SUITESPARSE_EMSCRIPTEN=1 GRAPHBLAS_PREFIX=/tmp/graphblas-wasm GraphBLAS_ROOT=/tmp/graphblas-wasm EMCC_CFLAGS=-O2 LDFLAGS="-sBINARYEN_EXTRA_PASSES=--one-caller-inline-max-function-size=1000" CIBW_ENVIRONMENT_PASS_LINUX: SUITESPARSE_FASTEST_BUILD From a2bc72e2b51e356768ec0327ecdd5c7386435866 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 10:24:24 -0600 Subject: [PATCH 13/18] CI: time out wheel and test jobs instead of running for 6 hours A PyPy wheel job hung in a test for over an hour before its run was cancelled; without a timeout, GitHub lets a job run for 6 hours. The limits leave room: full release builds take up to 35 minutes, PR builds up to 25, and the conda test jobs a few minutes. --- .github/workflows/test.yml | 3 +++ .github/workflows/wheels.yml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index abb544b..b1072fb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -16,6 +16,9 @@ concurrency: jobs: test: runs-on: ${{ matrix.os }} + # A hung test would otherwise hold the runner for GitHub's default of 6 hours. These + # jobs take a few minutes. + timeout-minutes: 30 defaults: run: # -e: a custom shell gets no errexit, so without it a multi-command step diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index a165b66..78b8093 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -55,6 +55,9 @@ jobs: build_wheels: name: Wheels - ${{ matrix.cibw_archs }} ${{ matrix.arch_note}} - ${{ matrix.os }} runs-on: ${{ matrix.os }} + # A hung test would otherwise hold the runner for GitHub's default of 6 hours. The + # slowest job, a full (release) build on macos-15-intel, has taken up to 35 minutes. + timeout-minutes: 90 strategy: fail-fast: false matrix: From 84e490c6ed67e71e920b8b11eb430dd7e9029142 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 10:42:12 -0600 Subject: [PATCH 14/18] tests: pass when each test runs in several threads at once pytest-run-parallel (`--parallel-threads=N`) runs each test in N threads at once, which finds races on free-threaded Python. Two tests failed under it: - test_claim_buffer_frees_on_error: threads raced to initialize the recording arena (GxB_arena_init returns GrB_INVALID_VALUE for an arena that is already initialized), and shared one list of freed addresses, which one thread cleared while another checked it. Initialize the arena under a lock, and record frees per thread. Fixing the test, rather than running it in one thread, keeps it racing the first use of an arena's memory handler in utils.pyx: without the lock in `_handler`, it fails in 4 threads. - test_run_doctests: doctest replaces sys.stdout and linecache.getlines for the whole process while it runs, so mark it thread_unsafe, which pytest-run-parallel runs in one thread. conftest.py registers the marker when the plugin isn't installed, since --strict-markers and -W error reject an unknown marker. --- suitesparse_graphblas/conftest.py | 10 +++++ suitesparse_graphblas/tests/test_doctest.py | 3 ++ suitesparse_graphblas/tests/test_memory.py | 48 +++++++++++---------- 3 files changed, 39 insertions(+), 22 deletions(-) diff --git a/suitesparse_graphblas/conftest.py b/suitesparse_graphblas/conftest.py index 4e25e1d..17e8144 100644 --- a/suitesparse_graphblas/conftest.py +++ b/suitesparse_graphblas/conftest.py @@ -11,6 +11,16 @@ _set_numpy_warn_if_no_mem_policy = None +def pytest_configure(config): + # The marker tells pytest-run-parallel (`--parallel-threads`) to run a test in one thread. + # The plugin registers it; without the plugin, an unknown marker fails `--strict-markers` + # and `-W error`. + if not config.pluginmanager.hasplugin("run-parallel"): + config.addinivalue_line( + "markers", "thread_unsafe: run the test in one thread under pytest-run-parallel" + ) + + @pytest.fixture(scope="session", autouse=True) def intialize_suitesparse_graphblas(): initialize() diff --git a/suitesparse_graphblas/tests/test_doctest.py b/suitesparse_graphblas/tests/test_doctest.py index 8718558..63e8976 100644 --- a/suitesparse_graphblas/tests/test_doctest.py +++ b/suitesparse_graphblas/tests/test_doctest.py @@ -2,9 +2,12 @@ import importlib import pkgutil +import pytest + from suitesparse_graphblas import api, utils +@pytest.mark.thread_unsafe(reason="doctest patches sys.stdout and linecache process-wide") def test_run_doctests(): # Every module of the functional API, found rather than listed so none is missed: the # wheel builds' test command does not collect doctests, so they run only through here diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index 291d08d..923034e 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -2,6 +2,7 @@ import subprocess import sys import textwrap +import threading import numpy as np import pytest @@ -233,30 +234,33 @@ def test_claim_buffer(): claim_buffer_2d(ffi, ffi.NULL, 6, 2, 3, int64, True) -# An arena that records the addresses it frees, made once (arenas can't be changed) +# An arena that records the addresses it frees, made once (arenas can't be changed). Tests may +# run in several threads at once, so each thread records only its own frees. _recording_arena = {} +_recording_arena_lock = threading.Lock() def recording_arena(): - if not _recording_arena: - blocks = {} - freed = [] - - @ffi.callback("void *(size_t)") - def malloc(size): - block = ffi.new("char[]", size or 1) - blocks[int(ffi.cast("uintptr_t", block))] = block - return block - - @ffi.callback("void (void *)") - def free(ptr): - address = int(ffi.cast("uintptr_t", ptr)) - blocks.pop(address, None) - freed.append(address) - - k = lib.GxB_NARENAS - 2 # not arena 5: test_can_unclaim_buffer needs it uninitialized - assert lib.GxB_arena_init(k, malloc, ffi.NULL, ffi.NULL, free) == lib.GrB_SUCCESS - _recording_arena.update(k=k, freed=freed, callbacks=(malloc, free)) + with _recording_arena_lock: + if not _recording_arena: + blocks = {} + freed = threading.local() + + @ffi.callback("void *(size_t)") + def malloc(size): + block = ffi.new("char[]", size or 1) + blocks[int(ffi.cast("uintptr_t", block))] = block + return block + + @ffi.callback("void (void *)") + def free(ptr): + address = int(ffi.cast("uintptr_t", ptr)) + blocks.pop(address, None) + freed.addresses.append(address) + + k = lib.GxB_NARENAS - 2 # not 5: test_can_unclaim_buffer needs it uninitialized + assert lib.GxB_arena_init(k, malloc, ffi.NULL, ffi.NULL, free) == lib.GrB_SUCCESS + _recording_arena.update(k=k, freed=freed, callbacks=(malloc, free)) return _recording_arena["k"], _recording_arena["freed"] @@ -281,10 +285,10 @@ def test_claim_buffer_frees_on_error(): array = empty(6, int64, arena=k) ptr = ffi.cast("void*", array.ctypes.data) unclaim_buffer(array, arena=k) # now nothing owns it, as after a GraphBLAS export - freed.clear() + freed.addresses = [] with pytest.raises(ValueError, match=match): claim(ptr) - assert freed == [int(ffi.cast("uintptr_t", ptr))] + assert freed.addresses == [int(ffi.cast("uintptr_t", ptr))] @pytest.mark.parametrize( From 71cdedff6c4c1bbafe20d8089318bd98b7d8f8b5 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 10:42:15 -0600 Subject: [PATCH 15/18] CI: also run the tests in 4 threads at once on free-threaded Python Without a GIL, threads run Python code in parallel, and a race in psg, GraphBLAS, or a test shows up only when tests run in threads. On 3.14t and 3.15t, install pytest-run-parallel and run the suite once more with each test in 4 threads at once, 10 times each (locally, 5.5 seconds against 1.3 for the usual run). This adds to the usual run rather than replacing it: pytest-run-parallel ignores warnings that a test raises in its threads, and the usual run turns warnings into errors. --- .github/workflows/test.yml | 11 +++++++++++ AGENTS.md | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b1072fb..6d8b457 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -59,6 +59,9 @@ jobs: cp continuous_integration/environment.yml environment-ci.yml echo " - python=$pyver" >> environment-ci.yml echo " - $variant" >> environment-ci.yml + if [[ $PYVER == *t ]]; then + echo " - pytest-run-parallel" >> environment-ci.yml # see "Test" + fi cat environment-ci.yml - name: Conda uses: conda-incubator/setup-miniconda@be893c923ea9cf1cf7cd510fbdde27c7e18cbdcb # v4.1.0 @@ -118,10 +121,18 @@ jobs: - name: Test env: CYTHON_COVERAGE: true + PYVER: ${{ matrix.python-version }} run: | pytest -s -k test_print_jit_config $COV -m pytest $COV suitesparse_graphblas/tests/test_initialize.py + if [[ $PYVER == *t ]]; then + # Without a GIL, threads run Python code in parallel, so also run each test in 4 + # threads at once, 10 times each, to find races (in psg, GraphBLAS, or a test). + # pytest-run-parallel ignores warnings raised in its threads, so this adds to the + # run above rather than replacing it. + pytest --parallel-threads=4 --iterations=10 + fi - name: create_headers.py check if: (! contains(matrix.os, 'windows')) run: | diff --git a/AGENTS.md b/AGENTS.md index 51aaafe..3ea9a7b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -210,6 +210,14 @@ The file is marked `freethreading_compatible=True`. The package does nothing spe free-threading itself — correctness depends on SuiteSparse:GraphBLAS being thread-safe, which it is required to be. +The free-threaded CI jobs (3.14t and 3.15t in `test.yml`) also run the suite with +pytest-run-parallel, each test in 4 threads at once (`pytest --parallel-threads=4 +--iterations=10`), so tests must be thread-safe: keep state per test or per thread, and guard +one-time setup (such as `GxB_arena_init`) with a lock. Mark a test that can't be, because it +changes process-wide state as `doctest` does, with `@pytest.mark.thread_unsafe(reason=...)`; +`conftest.py` registers the marker when the plugin isn't installed. Doctests always run in +one thread. + ## Style and tooling - Black, isort, flake8 (config in `.flake8`, line length 100, double quotes), pyupgrade From 7f9c89a8efa3a74b6c14230699ae244b8a29af6b Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 10:44:40 -0600 Subject: [PATCH 16/18] Say what utils.pyx does for free-threading The comment at the top of utils.pyx and AGENTS.md said the package does nothing special for free-threading, but making each arena's NumPy memory handler on first use takes a lock, so threads racing that first use share one handler. --- AGENTS.md | 7 ++++--- suitesparse_graphblas/utils.pyx | 9 +++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3ea9a7b..a8b2c25 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -206,9 +206,10 @@ When claiming a buffer from `GxB_*_unload`, use the arena in the returned `handl (`handling - GrB_DEFAULT`), and never claim one with `handling >= GxB_IS_READONLY`: whoever loaded it read-only still owns it. -The file is marked `freethreading_compatible=True`. The package does nothing special for -free-threading itself — correctness depends on SuiteSparse:GraphBLAS being thread-safe, -which it is required to be. +The file is marked `freethreading_compatible=True`. Correctness depends on +SuiteSparse:GraphBLAS being thread-safe, which it is required to be; the one piece of shared +state in `utils.pyx` is the per-arena NumPy memory handler, made once under `_handlers_lock` +so that threads racing its first use share one handler. The free-threaded CI jobs (3.14t and 3.15t in `test.yml`) also run the suite with pytest-run-parallel, each test in 4 threads at once (`pytest --parallel-threads=4 diff --git a/suitesparse_graphblas/utils.pyx b/suitesparse_graphblas/utils.pyx index 2472661..52a01d2 100644 --- a/suitesparse_graphblas/utils.pyx +++ b/suitesparse_graphblas/utils.pyx @@ -1,9 +1,10 @@ # cython: freethreading_compatible=True # -# We don't do anything special to support free-threading, but GraphBLAS C -# libraries are required to be thread-safe, so things should "just work". -# Of course, users writing multithreaded code can find many creative ways -# to fail, but python-suitesparse-graphblas shouldn't crash. +# GraphBLAS C libraries are required to be thread-safe, so free-threading needs +# little here: a lock around making each arena's NumPy memory handler on first +# use (`_handler`), so threads racing that first use share one handler. Of +# course, users writing multithreaded code can find many creative ways to fail, +# but python-suitesparse-graphblas shouldn't crash. """Move memory between GraphBLAS and NumPy without copying. Memory must be freed by the allocator that allocated it. GraphBLAS frees the memory it From 6d9428078642bb164611b1443de6b4858e102a23 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 10:50:43 -0600 Subject: [PATCH 17/18] test_memory: record frees in any thread, not only the test's own Each thread's list of freed addresses existed only once the test had set it, so a free in another thread would raise AttributeError in the cffi callback, which is only printed, and the free would go unseen. Every thread now starts with an empty list. --- suitesparse_graphblas/tests/test_memory.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index 923034e..1021267 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -240,11 +240,18 @@ def test_claim_buffer(): _recording_arena_lock = threading.Lock() +class _FreedInThisThread(threading.local): + # Every thread starts with an empty list, so a free in any thread is recorded: an + # AttributeError in the cffi callback would only be printed, and the free not seen. + def __init__(self): + self.addresses = [] + + def recording_arena(): with _recording_arena_lock: if not _recording_arena: blocks = {} - freed = threading.local() + freed = _FreedInThisThread() @ffi.callback("void *(size_t)") def malloc(size): From 6fdcc40c1b43287af16a9f8d5d811174143cd1a3 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 10:50:46 -0600 Subject: [PATCH 18/18] Name the per-arena state utils.pyx shares between threads The allocator table, the NumPy handler structs and the handler capsules are all filled once under _handlers_lock and only read after that; the comment and AGENTS.md now say so instead of naming just the handler. --- AGENTS.md | 8 +++++--- suitesparse_graphblas/utils.pyx | 9 +++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a8b2c25..cad7326 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -207,9 +207,11 @@ When claiming a buffer from `GxB_*_unload`, use the arena in the returned `handl loaded it read-only still owns it. The file is marked `freethreading_compatible=True`. Correctness depends on -SuiteSparse:GraphBLAS being thread-safe, which it is required to be; the one piece of shared -state in `utils.pyx` is the per-arena NumPy memory handler, made once under `_handlers_lock` -so that threads racing its first use share one handler. +SuiteSparse:GraphBLAS being thread-safe, which it is required to be. The shared mutable state +in `utils.pyx` is per arena: its allocator functions (`arenas`), NumPy handler struct +(`arena_handlers`) and handler capsule (`_handlers`). `_handler` fills them once, under +`_handlers_lock`, so threads racing an arena's first use share one handler; after that they +are only read. The free-threaded CI jobs (3.14t and 3.15t in `test.yml`) also run the suite with pytest-run-parallel, each test in 4 threads at once (`pytest --parallel-threads=4 diff --git a/suitesparse_graphblas/utils.pyx b/suitesparse_graphblas/utils.pyx index 52a01d2..2308bbc 100644 --- a/suitesparse_graphblas/utils.pyx +++ b/suitesparse_graphblas/utils.pyx @@ -1,10 +1,11 @@ # cython: freethreading_compatible=True # # GraphBLAS C libraries are required to be thread-safe, so free-threading needs -# little here: a lock around making each arena's NumPy memory handler on first -# use (`_handler`), so threads racing that first use share one handler. Of -# course, users writing multithreaded code can find many creative ways to fail, -# but python-suitesparse-graphblas shouldn't crash. +# little here: the per-arena state below (`arenas`, `arena_handlers`, +# `_handlers`) is filled once, under `_handlers_lock` (`_handler`), so threads +# racing an arena's first use share one handler, and is only read after that. +# Of course, users writing multithreaded code can find many creative ways to +# fail, but python-suitesparse-graphblas shouldn't crash. """Move memory between GraphBLAS and NumPy without copying. Memory must be freed by the allocator that allocated it. GraphBLAS frees the memory it