Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 7 additions & 5 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: |
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/update_graphblas.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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
Expand Down
11 changes: 9 additions & 2 deletions .github/workflows/wheels.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
12 changes: 6 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path to GraphBLAS.h>`
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.
Expand Down
2 changes: 1 addition & 1 deletion GB_VERSION.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
10.5.2
10.5.3
2 changes: 1 addition & 1 deletion suitesparse.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 #
Expand Down
25 changes: 16 additions & 9 deletions suitesparse_graphblas/create_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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}")
Expand Down
129 changes: 129 additions & 0 deletions suitesparse_graphblas/tests/test_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
["<i8", ("<i8", (4,)), ("<i4", (2, 3)), (("<i2", (3,)), (2,))],
ids=["i8", "i8x4", "i4x2x3", "nested"],
)
@pytest.mark.parametrize("is_c_order", [True, False])
@pytest.mark.parametrize("spare", [False, True])
def test_claim_buffer_2d(dtype, is_c_order, spare):
# A full matrix of a user-defined type the size of `dtype`, whose element (i, j) holds
# 100 * i + 10 * j + k as its k-th scalar, so that the expected array doesn't depend on
# how GraphBLAS lays out the buffer. With a subarray dtype, the result must have the
# element axes last.
dtype = np.dtype(dtype)
# The element axes and scalar type NumPy makes of `dtype`: for a nested subarray dtype,
# its base's axes follow dtype.shape
element_shape, scalar = np.empty(0, dtype).shape[1:], np.empty(0, dtype).dtype
nrows, ncols = (2, 3) if is_c_order else (3, 2)
i = np.arange(nrows)[:, None, None]
j = np.arange(ncols)[None, :, None]
k = np.arange(dtype.itemsize // scalar.itemsize)
values = (100 * i + 10 * j + k).astype(scalar).reshape((nrows, ncols) + element_shape)
T = grb_type.grb_type_new(dtype.itemsize)
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(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))
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*")
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
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) + element_shape
assert array.dtype == scalar
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():
array = np.arange(10)
assert can_unclaim_buffer(array)
Expand Down Expand Up @@ -334,6 +449,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)
Expand Down
Loading
Loading