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..6d8b457 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 @@ -29,8 +32,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 @@ -57,16 +59,22 @@ 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 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 +106,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. @@ -113,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/.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..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: @@ -85,9 +88,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 +158,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: @@ -178,9 +188,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 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..cad7326 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. @@ -204,9 +206,20 @@ 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 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 +--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 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/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/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_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 03ef601..1021267 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -2,11 +2,13 @@ import subprocess import sys import textwrap +import threading import numpy as np 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 +234,130 @@ 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). Tests may +# run in several threads at once, so each thread records only its own frees. +_recording_arena = {} +_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 = _FreedInThisThread() + + @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"] + + +@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.addresses = [] + with pytest.raises(ValueError, match=match): + claim(ptr) + assert freed.addresses == [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 +237,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 +275,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 +309,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 +472,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 +511,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)))