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..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 @@ -148,7 +155,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 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/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 # 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}") diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index 03ef601..291d08d 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -7,6 +7,7 @@ import pytest from suitesparse_graphblas import check_status, exceptions, ffi, lib, matrix, vector +from suitesparse_graphblas.api import grb_type from suitesparse_graphblas.utils import ( can_unclaim_buffer, claim_buffer, @@ -232,6 +233,120 @@ 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") +# 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() + 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. @@ -224,6 +235,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") @@ -245,18 +273,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 @@ -271,38 +307,56 @@ 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``, + followed by the axes of ``dtype.base`` if it is a subarray dtype too. + 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] - int flags = NPY_ARRAY_WRITEABLE - 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: - flags |= NPY_ARRAY_F_CONTIGUOUS - Py_INCREF(dtype) - array = PyArray_NewFromDescr( - ndarray, dtype, 2, dims, NULL, ptr, flags, NULL - ) - own_data(array, handler) - elif cdata_size > size: # pragma: no cover - array = claim_buffer(ffi, cdata, cdata_size, dtype, arena) + npy_intp strides[2] + npy_intp *strides_ptr = NULL + if cdata_size > size: + 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: - array = array[:size].reshape((nrows, ncols)) - else: - array = array[:size].reshape((ncols, nrows)).T - else: # pragma: no cover + 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) 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 @@ -416,6 +470,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). @@ -452,9 +509,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)))