From 2cf8a2d5e9eb8ebfabfb566375c8c58b5b4bc336 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:33:33 -0600 Subject: [PATCH 01/47] Size string buffers from get_SIZE in the operator and monoid get_string binaryop_get_string, unaryop_get_string, indexunaryop_get_string, indexbinaryop_get_string and monoid_get_string read the string into ffi.new("char[256]"), but GrB_*_get_String strcpy the whole string into the caller's buffer. Any longer string overran the buffer and came back cut at 256 characters. A name set with set_string has no length limit, on a monoid as on an operator, and neither has an operator's GxB_JIT_C_DEFINITION. Ask GraphBLAS for the size with *_get_SIZE first and allocate that much. The new tests set a 510-character name on each kind of object and give each kind of operator a definition of about 600 characters, without the JIT, which only reads it. Before the fix, all nine returned only the first 256 characters. --- suitesparse_graphblas/api/binaryop.py | 5 +- suitesparse_graphblas/api/indexbinaryop.py | 5 +- suitesparse_graphblas/api/indexunaryop.py | 5 +- suitesparse_graphblas/api/monoid.py | 5 +- suitesparse_graphblas/api/unaryop.py | 5 +- suitesparse_graphblas/tests/test_api_ops.py | 131 ++++++++++++++++++++ 6 files changed, 151 insertions(+), 5 deletions(-) create mode 100644 suitesparse_graphblas/tests/test_api_ops.py diff --git a/suitesparse_graphblas/api/binaryop.py b/suitesparse_graphblas/api/binaryop.py index cc87358..7faa009 100644 --- a/suitesparse_graphblas/api/binaryop.py +++ b/suitesparse_graphblas/api/binaryop.py @@ -182,7 +182,10 @@ def binaryop_get_string(op, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(op, lib.GrB_BinaryOp_get_SIZE(op[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(op, lib.GrB_BinaryOp_get_String(op[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/indexbinaryop.py b/suitesparse_graphblas/api/indexbinaryop.py index 4d513ae..4ababdb 100644 --- a/suitesparse_graphblas/api/indexbinaryop.py +++ b/suitesparse_graphblas/api/indexbinaryop.py @@ -120,7 +120,10 @@ def indexbinaryop_get_size(op, field): def indexbinaryop_get_string(op, field): """Get an operator option as a string.""" - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(op, lib.GxB_IndexBinaryOp_get_SIZE(op[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(op, lib.GxB_IndexBinaryOp_get_String(op[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/indexunaryop.py b/suitesparse_graphblas/api/indexunaryop.py index b333fc1..f2414c6 100644 --- a/suitesparse_graphblas/api/indexunaryop.py +++ b/suitesparse_graphblas/api/indexunaryop.py @@ -167,7 +167,10 @@ def indexunaryop_get_string(op, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(op, lib.GrB_IndexUnaryOp_get_SIZE(op[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(op, lib.GrB_IndexUnaryOp_get_String(op[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/monoid.py b/suitesparse_graphblas/api/monoid.py index 4706b05..09bfae7 100644 --- a/suitesparse_graphblas/api/monoid.py +++ b/suitesparse_graphblas/api/monoid.py @@ -549,7 +549,10 @@ def monoid_get_string(m, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(m, lib.GrB_Monoid_get_SIZE(m[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(m, lib.GrB_Monoid_get_String(m[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/unaryop.py b/suitesparse_graphblas/api/unaryop.py index f5f4fc3..f26b9eb 100644 --- a/suitesparse_graphblas/api/unaryop.py +++ b/suitesparse_graphblas/api/unaryop.py @@ -166,7 +166,10 @@ def unaryop_get_string(op, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(op, lib.GrB_UnaryOp_get_SIZE(op[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(op, lib.GrB_UnaryOp_get_String(op[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/tests/test_api_ops.py b/suitesparse_graphblas/tests/test_api_ops.py new file mode 100644 index 0000000..5481ede --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_ops.py @@ -0,0 +1,131 @@ +"""User-defined operators of the functional API, made from cffi callbacks.""" + +import pytest + +from suitesparse_graphblas import ffi, lib +from suitesparse_graphblas.api import binaryop, indexbinaryop, indexunaryop, monoid, unaryop + +INT64 = lib.GrB_INT64 + +# GraphBLAS calls these through the function pointers cffi makes for them. They live at +# module level so that they outlive every operator built from them. + + +@ffi.callback("GxB_unary_function") +def _square_plus_half(z, x): + # FP64 <- INT32 + value = ffi.cast("int32_t*", x)[0] + ffi.cast("double*", z)[0] = value * value + 0.5 + + +@ffi.callback("GxB_binary_function") +def _times10_plus(z, x, y): + # INT64 <- INT64, INT64 + ffi.cast("int64_t*", z)[0] = 10 * ffi.cast("int64_t*", x)[0] + ffi.cast("int64_t*", y)[0] + + +@ffi.callback("GxB_index_unary_function") +def _plus_position(z, x, i, j, y): + # INT64 <- INT64 at (i, j), INT64 thunk + x = ffi.cast("int64_t*", x)[0] + y = ffi.cast("int64_t*", y)[0] + ffi.cast("int64_t*", z)[0] = x + 100 * i + 10 * j + y + + +@ffi.callback("GxB_index_binary_function") +def _plus_positions(z, x, ix, jx, y, iy, jy, theta): + # INT64 <- INT64 at (ix, jx), INT64 at (iy, jy), INT64 theta + x = ffi.cast("int64_t*", x)[0] + y = ffi.cast("int64_t*", y)[0] + theta = ffi.cast("int64_t*", theta)[0] + ffi.cast("int64_t*", z)[0] = x + y + theta * (1000 * ix + 100 * jx + 10 * iy + jy) + + +# C definitions of the callbacks, as the JIT would want them +DEFINITIONS = { + "unaryop": ( + "square_plus_half", + "void square_plus_half (double *z, const int32_t *x) " + "{ (*z) = ((double) (*x)) * (*x) + 0.5 ; }", + ), + "binaryop": ( + "times10_plus", + "void times10_plus (int64_t *z, const int64_t *x, const int64_t *y) " + "{ (*z) = 10 * (*x) + (*y) ; }", + ), + "indexunaryop": ( + "plus_position", + "void plus_position (int64_t *z, const int64_t *x, GrB_Index i, GrB_Index j, " + "const int64_t *y) { (*z) = (*x) + 100 * i + 10 * j + (*y) ; }", + ), + "indexbinaryop": ( + "plus_positions", + "void plus_positions (int64_t *z, const int64_t *x, GrB_Index ix, GrB_Index jx, " + "const int64_t *y, GrB_Index iy, GrB_Index jy, const int64_t *theta) " + "{ (*z) = (*x) + (*y) + (*theta) * (1000 * ix + 100 * jx + 10 * iy + jy) ; }", + ), +} + +MODULES = { + "unaryop": unaryop, + "binaryop": binaryop, + "indexunaryop": indexunaryop, + "indexbinaryop": indexbinaryop, + "monoid": monoid, +} + + +def _user_defined(kind): + """Return a new user-defined object of `kind`, without a name.""" + if kind == "unaryop": + return unaryop.unaryop_new(_square_plus_half, lib.GrB_FP64, lib.GrB_INT32) + if kind == "binaryop": + return binaryop.binaryop_new(_times10_plus, INT64, INT64, INT64) + if kind == "indexunaryop": + return indexunaryop.indexunaryop_new(_plus_position, INT64, INT64, INT64) + if kind == "indexbinaryop": + return indexbinaryop.indexbinaryop_new( + _plus_positions, INT64, INT64, INT64, INT64, ffi.NULL, ffi.NULL + ) + assert kind == "monoid" + return monoid.monoid_new_int64(lib.GrB_PLUS_INT64, 0) + + +def _named(kind, name, defn): + """Return a new operator of `kind` with a JIT name and definition.""" + if kind == "unaryop": + return unaryop.unaryop_new_named(_square_plus_half, lib.GrB_FP64, lib.GrB_INT32, name, defn) + if kind == "binaryop": + return binaryop.binaryop_new_named(_times10_plus, INT64, INT64, INT64, name, defn) + if kind == "indexunaryop": + return indexunaryop.indexunaryop_new_named(_plus_position, INT64, INT64, INT64, name, defn) + assert kind == "indexbinaryop" + return indexbinaryop.indexbinaryop_new(_plus_positions, INT64, INT64, INT64, INT64, name, defn) + + +@pytest.mark.parametrize("kind", list(MODULES)) +def test_get_string_long_name(kind): + # GraphBLAS doesn't limit the length of a name the user sets + get_size, get_string, set_string = ( + getattr(MODULES[kind], f"{kind}_{func}") + for func in ("get_size", "get_string", "set_string") + ) + obj = _user_defined(kind) + name = "long_name_" + "x" * 500 + set_string(obj, lib.GrB_NAME, name) + assert get_size(obj, lib.GrB_NAME) == len(name) + 1 + assert get_string(obj, lib.GrB_NAME) == name + + +@pytest.mark.parametrize("kind", list(DEFINITIONS)) +def test_get_string_long_definition(kind): + # A definition is as long as its C code + get_size, get_string = ( + getattr(MODULES[kind], f"{kind}_{func}") for func in ("get_size", "get_string") + ) + name, defn = DEFINITIONS[kind] + defn = f"/* {'x' * 500} */\n{defn}" + op = _named(kind, name, defn) + assert get_string(op, lib.GxB_JIT_C_NAME) == name + assert get_size(op, lib.GxB_JIT_C_DEFINITION) == len(defn) + 1 + assert get_string(op, lib.GxB_JIT_C_DEFINITION) == defn From 59b98cabfa45937375aae8b6459afef1b4fb7867 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:34:37 -0600 Subject: [PATCH 02/47] Size monoid identity and terminal buffers from the monoid's type monoid_identity and monoid_terminal hand GxB_Monoid_identity and GxB_Monoid_terminal a char[256], and GraphBLAS copies one value of the monoid's type into it, of the type's full size. A monoid of a user-defined type larger than 256 bytes overran the buffer on the heap, and the caller got back only the first 256 bytes. Find the size from the monoid's operator's output type and allocate that, but never less than the 256 bytes the functions have always returned, so nothing changes for the built-in types. The new test builds an elementwise-max monoid of a 512-byte type, checks its identity and terminal, and reduces a vector with it; before the fix it failed with "assert 256 >= 512" on the length of the returned identity. --- suitesparse_graphblas/api/monoid.py | 16 ++++++- .../tests/test_api_monoid.py | 42 +++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 suitesparse_graphblas/tests/test_api_monoid.py diff --git a/suitesparse_graphblas/api/monoid.py b/suitesparse_graphblas/api/monoid.py index 09bfae7..1f55125 100644 --- a/suitesparse_graphblas/api/monoid.py +++ b/suitesparse_graphblas/api/monoid.py @@ -580,6 +580,18 @@ def monoid_operator(m): return op[0] +def _value_buffer(m): + """Return a buffer that holds one value of the monoid's type.""" + op = ffi.new("GrB_BinaryOp*", monoid_operator(m)) + T = ffi.new("GrB_Type*") + check_status(op, lib.GxB_BinaryOp_ztype(T, op[0])) + size = ffi.new("size_t*") + check_status(T, lib.GxB_Type_size(size, T[0])) + # A user-defined type can be of any size; keep at least the 256 bytes these + # functions have always returned + return ffi.new("char[]", max(size[0], 256)) + + def monoid_identity(m): """Return a buffer containing the identity value of a monoid. @@ -587,7 +599,7 @@ def monoid_identity(m): >>> val = monoid_identity(m) """ - val = ffi.new("char[256]") + val = _value_buffer(m) check_status(m, lib.GxB_Monoid_identity(val, m[0])) return val @@ -605,6 +617,6 @@ def monoid_terminal(m): """ has_terminal = ffi.new("bool*") - val = ffi.new("char[256]") + val = _value_buffer(m) check_status(m, lib.GxB_Monoid_terminal(has_terminal, val, m[0])) return has_terminal[0], val diff --git a/suitesparse_graphblas/tests/test_api_monoid.py b/suitesparse_graphblas/tests/test_api_monoid.py new file mode 100644 index 0000000..19c4823 --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_monoid.py @@ -0,0 +1,42 @@ +"""Monoids of the functional API: the typed constructors, and monoids of user-defined types.""" + +from suitesparse_graphblas import check_status, ffi, lib +from suitesparse_graphblas.api import binaryop, grb_type, monoid, vector + +BIG = 64 # int64s in a value of a large user-defined type + + +@ffi.callback("GxB_binary_function") +def _max_big(z, x, y): + # Elementwise max + x = ffi.cast("int64_t*", x) + y = ffi.cast("int64_t*", y) + z = ffi.cast("int64_t*", z) + for k in range(BIG): + z[k] = max(x[k], y[k]) + + +def test_monoid_of_large_type(): + size = 8 * BIG + T = grb_type.grb_type_new(size) + op = binaryop.binaryop_new(_max_big, T[0], T[0], T[0]) + identity = ffi.new("int64_t[]", [-(2**63)] * BIG) + terminal = ffi.new("int64_t[]", [2**63 - 1] * BIG) + m = monoid.monoid_terminal_new_udt(op[0], identity, terminal) + # GraphBLAS copies one value of the monoid's type, whatever its size + value = monoid.monoid_identity(m) + assert len(ffi.buffer(value)) >= size + assert ffi.buffer(value)[:size] == ffi.buffer(identity)[:] + has_terminal, value = monoid.monoid_terminal(m) + assert has_terminal + assert len(ffi.buffer(value)) >= size + assert ffi.buffer(value)[:size] == ffi.buffer(terminal)[:] + + u = vector.vector_new(T[0], 3) + first = ffi.new("int64_t[]", list(range(BIG))) + last = ffi.new("int64_t[]", list(range(BIG, 0, -1))) + check_status(u, lib.GrB_Vector_setElement_UDT(u[0], first, 0)) + check_status(u, lib.GrB_Vector_setElement_UDT(u[0], last, 2)) + result = ffi.new("int64_t[]", BIG) + check_status(u, lib.GrB_Vector_reduce_UDT(result, ffi.NULL, m[0], u[0], ffi.NULL)) + assert list(result) == [max(k, BIG - k) for k in range(BIG)] From b5b033a516f72bea0ddb524b94e12211d98067f2 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:39:04 -0600 Subject: [PATCH 03/47] Test user-defined operators and select operator errors The doctests use only built-in operators, so nothing ran the constructors of the operator modules, and indexbinaryop had no test at all, since GraphBLAS has no built-in index binary operator. Make an operator of each kind from a cffi callback and check its types and type codes, then use it: a unary operator in apply, a binary operator in eWiseAdd (it applies only where both inputs have an entry), an index unary operator in apply with a thunk, and an index binary operator, bound to a theta, in eWiseMult. The values depend on the row and column indices, so a mix-up of the index arguments would show. Run each constructor both with garbage collection and with free=None, then free by hand. Named operators check the JIT name and definition from str and from bytes, and print them; they aren't used in an operation, which could start the JIT. Also check that GraphBLAS errors come through as exceptions: a NULL type in a constructor, setting a type code, renaming a built-in, and each select operator function with a NULL operator. --- suitesparse_graphblas/tests/test_api_ops.py | 304 ++++++++++++++++++-- 1 file changed, 280 insertions(+), 24 deletions(-) diff --git a/suitesparse_graphblas/tests/test_api_ops.py b/suitesparse_graphblas/tests/test_api_ops.py index 5481ede..790b9ff 100644 --- a/suitesparse_graphblas/tests/test_api_ops.py +++ b/suitesparse_graphblas/tests/test_api_ops.py @@ -2,11 +2,26 @@ import pytest -from suitesparse_graphblas import ffi, lib -from suitesparse_graphblas.api import binaryop, indexbinaryop, indexunaryop, monoid, unaryop +from suitesparse_graphblas import exceptions, ffi, lib +from suitesparse_graphblas.api import ( + binaryop, + indexbinaryop, + indexunaryop, + matrix, + monoid, + scalar, + selectop, + unaryop, + vector, +) +from suitesparse_graphblas.api.utils import _capture_c_output INT64 = lib.GrB_INT64 +# Whether a constructor hands its object to the garbage collector (its default) or leaves +# freeing it to the caller (`free=None`) +GC = [pytest.param(True, id="gc"), pytest.param(False, id="manual")] + # GraphBLAS calls these through the function pointers cffi makes for them. They live at # module level so that they outlive every operator built from them. @@ -75,57 +90,298 @@ def _plus_positions(z, x, ix, jx, y, iy, jy, theta): } -def _user_defined(kind): +def _user_defined(kind, *, gc=True): """Return a new user-defined object of `kind`, without a name.""" + kwargs = {} if gc else {"free": None} if kind == "unaryop": - return unaryop.unaryop_new(_square_plus_half, lib.GrB_FP64, lib.GrB_INT32) + return unaryop.unaryop_new(_square_plus_half, lib.GrB_FP64, lib.GrB_INT32, **kwargs) if kind == "binaryop": - return binaryop.binaryop_new(_times10_plus, INT64, INT64, INT64) + return binaryop.binaryop_new(_times10_plus, INT64, INT64, INT64, **kwargs) if kind == "indexunaryop": - return indexunaryop.indexunaryop_new(_plus_position, INT64, INT64, INT64) + return indexunaryop.indexunaryop_new(_plus_position, INT64, INT64, INT64, **kwargs) if kind == "indexbinaryop": return indexbinaryop.indexbinaryop_new( - _plus_positions, INT64, INT64, INT64, INT64, ffi.NULL, ffi.NULL + _plus_positions, INT64, INT64, INT64, INT64, ffi.NULL, ffi.NULL, **kwargs ) assert kind == "monoid" - return monoid.monoid_new_int64(lib.GrB_PLUS_INT64, 0) + return monoid.monoid_new_int64(lib.GrB_PLUS_INT64, 0, **kwargs) -def _named(kind, name, defn): +def _named(kind, name, defn, *, gc=True): """Return a new operator of `kind` with a JIT name and definition.""" + kwargs = {} if gc else {"free": None} if kind == "unaryop": - return unaryop.unaryop_new_named(_square_plus_half, lib.GrB_FP64, lib.GrB_INT32, name, defn) + return unaryop.unaryop_new_named( + _square_plus_half, lib.GrB_FP64, lib.GrB_INT32, name, defn, **kwargs + ) if kind == "binaryop": - return binaryop.binaryop_new_named(_times10_plus, INT64, INT64, INT64, name, defn) + return binaryop.binaryop_new_named(_times10_plus, INT64, INT64, INT64, name, defn, **kwargs) if kind == "indexunaryop": - return indexunaryop.indexunaryop_new_named(_plus_position, INT64, INT64, INT64, name, defn) + return indexunaryop.indexunaryop_new_named( + _plus_position, INT64, INT64, INT64, name, defn, **kwargs + ) assert kind == "indexbinaryop" - return indexbinaryop.indexbinaryop_new(_plus_positions, INT64, INT64, INT64, INT64, name, defn) + return indexbinaryop.indexbinaryop_new( + _plus_positions, INT64, INT64, INT64, INT64, name, defn, **kwargs + ) + + +def _func(kind, name): + """Return the function `_` of the module for `kind`.""" + return getattr(MODULES[kind], f"{kind}_{name}") + + +def _free(kind, obj, gc): + """Free `obj` if it isn't garbage collected, and check that it's gone.""" + if not gc: + _func(kind, "free")(obj) + assert obj[0] == ffi.NULL + + +def _entries(A): + """Return the entries of an INT64 matrix as sorted (row, col, value) tuples.""" + rows, cols, values = matrix.matrix_extract_tuples_int64(A) + return sorted(zip(rows.tolist(), cols.tolist(), values.tolist())) @pytest.mark.parametrize("kind", list(MODULES)) def test_get_string_long_name(kind): # GraphBLAS doesn't limit the length of a name the user sets - get_size, get_string, set_string = ( - getattr(MODULES[kind], f"{kind}_{func}") - for func in ("get_size", "get_string", "set_string") - ) obj = _user_defined(kind) name = "long_name_" + "x" * 500 - set_string(obj, lib.GrB_NAME, name) - assert get_size(obj, lib.GrB_NAME) == len(name) + 1 - assert get_string(obj, lib.GrB_NAME) == name + _func(kind, "set_string")(obj, lib.GrB_NAME, name) + assert _func(kind, "get_size")(obj, lib.GrB_NAME) == len(name) + 1 + assert _func(kind, "get_string")(obj, lib.GrB_NAME) == name @pytest.mark.parametrize("kind", list(DEFINITIONS)) def test_get_string_long_definition(kind): # A definition is as long as its C code - get_size, get_string = ( - getattr(MODULES[kind], f"{kind}_{func}") for func in ("get_size", "get_string") - ) name, defn = DEFINITIONS[kind] defn = f"/* {'x' * 500} */\n{defn}" op = _named(kind, name, defn) + assert _func(kind, "get_string")(op, lib.GxB_JIT_C_NAME) == name + assert _func(kind, "get_size")(op, lib.GxB_JIT_C_DEFINITION) == len(defn) + 1 + assert _func(kind, "get_string")(op, lib.GxB_JIT_C_DEFINITION) == defn + + +@pytest.mark.parametrize("gc", GC) +def test_unaryop_new(gc): + op = _user_defined("unaryop", gc=gc) + assert unaryop.unaryop_xtype(op) == lib.GrB_INT32 + assert unaryop.unaryop_ztype(op) == lib.GrB_FP64 + assert unaryop.unaryop_xtype_name(op) == "int32_t" + assert unaryop.unaryop_ztype_name(op) == "double" + assert unaryop.unaryop_get_int32(op, lib.GrB_INP0_TYPE_CODE) == lib.GrB_INT32_CODE + assert unaryop.unaryop_get_int32(op, lib.GrB_OUTP_TYPE_CODE) == lib.GrB_FP64_CODE + assert unaryop.unaryop_get_string(op, lib.GrB_NAME) == "" + unaryop.unaryop_wait(op) + + u = vector.vector_new(lib.GrB_INT32, 4) + vector.set_int32(u, 3, 1) + vector.set_int32(u, -2, 3) + w = vector.vector_new(lib.GrB_FP64, 4) + vector.vector_apply(w, op[0], u) + indices, values = vector.vector_extract_tuples_fp64(w) + assert indices.tolist() == [1, 3] + assert values.tolist() == [9.5, 4.5] + _free("unaryop", op, gc) + + +@pytest.mark.parametrize("gc", GC) +def test_binaryop_new(gc): + op = _user_defined("binaryop", gc=gc) + assert binaryop.binaryop_xtype(op) == INT64 + assert binaryop.binaryop_ytype(op) == INT64 + assert binaryop.binaryop_ztype(op) == INT64 + assert binaryop.binaryop_xtype_name(op) == "int64_t" + assert binaryop.binaryop_ytype_name(op) == "int64_t" + assert binaryop.binaryop_ztype_name(op) == "int64_t" + for field in (lib.GrB_INP0_TYPE_CODE, lib.GrB_INP1_TYPE_CODE, lib.GrB_OUTP_TYPE_CODE): + assert binaryop.binaryop_get_int32(op, field) == lib.GrB_INT64_CODE + binaryop.binaryop_wait(op) + + A = matrix.matrix_new(INT64, 2, 2) + B = matrix.matrix_new(INT64, 2, 2) + matrix.set_int64(A, 3, 0, 0) + matrix.set_int64(B, 4, 0, 0) + matrix.set_int64(B, 7, 0, 1) + matrix.set_int64(A, 5, 1, 1) + C = matrix.matrix_new(INT64, 2, 2) + # The operator applies only where both have an entry + matrix.matrix_ewise_add(C, op[0], A, B) + assert _entries(C) == [(0, 0, 34), (0, 1, 7), (1, 1, 5)] + _free("binaryop", op, gc) + + +@pytest.mark.parametrize("gc", GC) +def test_binaryop_new_indexop(gc): + idxop = _user_defined("indexbinaryop") + theta = scalar.scalar_new(INT64) + scalar.set_int64(theta, 2) + kwargs = {} if gc else {"free": None} + op = binaryop.binaryop_new_indexop(idxop[0], theta[0], **kwargs) + assert binaryop.binaryop_ztype(op) == INT64 + + A = matrix.matrix_new(INT64, 3, 3) + B = matrix.matrix_new(INT64, 3, 3) + matrix.set_int64(A, 1, 1, 2) + matrix.set_int64(B, 2, 1, 2) + matrix.set_int64(A, 3, 2, 0) + matrix.set_int64(B, 4, 2, 0) + matrix.set_int64(A, 5, 0, 0) + C = matrix.matrix_new(INT64, 3, 3) + # x + y + theta * (1000 * ix + 100 * jx + 10 * iy + jy), where both have an entry + matrix.matrix_ewise_mult(C, op[0], A, B) + assert _entries(C) == [(1, 2, 1 + 2 + 2 * 1212), (2, 0, 3 + 4 + 2 * 2020)] + _free("binaryop", op, gc) + + +@pytest.mark.parametrize("gc", GC) +def test_indexunaryop_new(gc): + op = _user_defined("indexunaryop", gc=gc) + assert indexunaryop.indexunaryop_xtype_name(op) == "int64_t" + assert indexunaryop.indexunaryop_ytype_name(op) == "int64_t" + assert indexunaryop.indexunaryop_ztype_name(op) == "int64_t" + for field in (lib.GrB_INP0_TYPE_CODE, lib.GrB_INP1_TYPE_CODE, lib.GrB_OUTP_TYPE_CODE): + assert indexunaryop.indexunaryop_get_int32(op, field) == lib.GrB_INT64_CODE + indexunaryop.indexunaryop_wait(op) + + A = matrix.matrix_new(INT64, 3, 3) + matrix.set_int64(A, 1, 1, 2) + matrix.set_int64(A, 5, 2, 0) + thunk = scalar.scalar_new(INT64) + scalar.set_int64(thunk, 7) + C = matrix.matrix_new(INT64, 3, 3) + # x + 100 * i + 10 * j + thunk + matrix.matrix_apply_indexop(C, op[0], A, thunk) + assert _entries(C) == [(1, 2, 128), (2, 0, 212)] + _free("indexunaryop", op, gc) + + +@pytest.mark.parametrize("gc", GC) +def test_indexbinaryop_new(gc): + name, defn = DEFINITIONS["indexbinaryop"] + op = _named("indexbinaryop", name, defn, gc=gc) + for field in ( + lib.GrB_INP0_TYPE_CODE, + lib.GrB_INP1_TYPE_CODE, + lib.GrB_OUTP_TYPE_CODE, + lib.GxB_THETA_TYPE_CODE, + ): + assert indexbinaryop.indexbinaryop_get_int32(op, field) == lib.GrB_INT64_CODE + for field in ( + lib.GrB_INP0_TYPE_STRING, + lib.GrB_INP1_TYPE_STRING, + lib.GrB_OUTP_TYPE_STRING, + lib.GxB_THETA_TYPE_STRING, + ): + assert indexbinaryop.indexbinaryop_get_string(op, field) == "GrB_INT64" + indexbinaryop.indexbinaryop_wait(op) + _free("indexbinaryop", op, gc) + + +@pytest.mark.parametrize("kind", list(DEFINITIONS)) +@pytest.mark.parametrize("gc", GC) +@pytest.mark.parametrize("encode", [False, True], ids=["str", "bytes"]) +def test_new_named(kind, gc, encode): + # Only the strings: using an operator that has a definition could start the JIT + name, defn = DEFINITIONS[kind] + if encode: + op = _named(kind, name.encode(), defn.encode(), gc=gc) + else: + op = _named(kind, name, defn, gc=gc) + get_string = _func(kind, "get_string") assert get_string(op, lib.GxB_JIT_C_NAME) == name - assert get_size(op, lib.GxB_JIT_C_DEFINITION) == len(defn) + 1 assert get_string(op, lib.GxB_JIT_C_DEFINITION) == defn + assert get_string(op, lib.GrB_NAME) == "" + _free(kind, op, gc) + + +@pytest.mark.parametrize("kind", list(MODULES)) +def test_set_int32_not_allowed(kind): + # The types of an operator or a monoid are fixed when it's made + get_int32 = _func(kind, "get_int32") + obj = _user_defined(kind) + code = get_int32(obj, lib.GrB_OUTP_TYPE_CODE) + with pytest.raises(exceptions.InvalidValue): + _func(kind, "set_int32")(obj, lib.GrB_OUTP_TYPE_CODE, lib.GrB_BOOL_CODE) + assert get_int32(obj, lib.GrB_OUTP_TYPE_CODE) == code + + +@pytest.mark.parametrize( + ("kind", "name"), + [ + ("unaryop", "GrB_AINV_INT64"), + ("binaryop", "GrB_PLUS_INT64"), + ("indexunaryop", "GrB_VALUEEQ_INT64"), + ("monoid", "GrB_PLUS_MONOID_INT64"), + ], +) +def test_set_string_of_builtin(kind, name): + # A built-in keeps its name + ctype = { + "unaryop": "GrB_UnaryOp*", + "binaryop": "GrB_BinaryOp*", + "indexunaryop": "GrB_IndexUnaryOp*", + "monoid": "GrB_Monoid*", + }[kind] + obj = ffi.new(ctype, getattr(lib, name)) + with pytest.raises(exceptions.InvalidValue): + _func(kind, "set_string")(obj, lib.GrB_NAME, "renamed") + assert _func(kind, "get_string")(obj, lib.GrB_NAME) == name + + +@pytest.mark.parametrize( + "new", + [ + lambda: unaryop.unaryop_new(_square_plus_half, ffi.NULL, lib.GrB_INT32), + lambda: binaryop.binaryop_new(_times10_plus, ffi.NULL, INT64, INT64), + lambda: indexunaryop.indexunaryop_new(_plus_position, ffi.NULL, INT64, INT64), + lambda: indexbinaryop.indexbinaryop_new( + _plus_positions, ffi.NULL, INT64, INT64, INT64, ffi.NULL, ffi.NULL + ), + lambda: binaryop.binaryop_new_indexop(ffi.NULL, ffi.NULL), + ], + ids=["unaryop", "binaryop", "indexunaryop", "indexbinaryop", "binaryop_indexop"], +) +def test_new_fails(new): + with pytest.raises(exceptions.NullPointer): + new() + + +@pytest.mark.thread_unsafe(reason="redirects the process's stdout file descriptor") +@pytest.mark.parametrize("kind", list(DEFINITIONS)) +def test_print(kind): + name, defn = DEFINITIONS[kind] + op = _named(kind, name, defn) + out = _capture_c_output(_func(kind, "print"), op, "my_op", lib.GxB_COMPLETE) + assert "my_op (user-defined)" in out + assert f"z={name}(" in out + assert defn in out + + def fprint_silent_then_short(): + # A capture that gets no output at all fails on Emscripten, where reading the empty + # pipe raises BlockingIOError + _func(kind, "fprint")(op, ffi.NULL, "silent_op", lib.GxB_SILENT) + _func(kind, "fprint")(op, ffi.NULL, b"short_op", lib.GxB_SHORT) + + out = _capture_c_output(fprint_silent_then_short) + assert "silent_op" not in out + assert "short_op (user-defined)" in out + + +@pytest.mark.parametrize( + "func", + [ + selectop.selectop_xtype, + selectop.selectop_ttype, + selectop.selectop_print, + lambda op: selectop.selectop_fprint(op, ffi.NULL), + ], + ids=["xtype", "ttype", "print", "fprint"], +) +def test_selectop_null(func): + # These check the status themselves, rather than with check_status + with pytest.raises(exceptions.NullPointer, match="GxB_SelectOp_.* failed with info=-2"): + func(ffi.new("GxB_SelectOp*")) From eb4cbc9657d79f60f3f413988851bba118822f13 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:42:18 -0600 Subject: [PATCH 04/47] Test every typed monoid constructor The doctests make one monoid per type, always garbage collected and always from the operator of a known monoid. GraphBLAS ignores the identity and terminal given with such an operator and uses its own, so the doctests can't tell whether the values reach GraphBLAS. Build each typed monoid, with and without a terminal, from FIRST, which isn't a known monoid, with identities and terminals at the ends of the type's range. Read them back, check that an empty vector reduces to the identity, and run each constructor both with garbage collection and with free=None. The large user-defined type's monoid now also goes through monoid_new_udt, and a monoid whose operator has a bool output fails with DomainMismatch. --- .../tests/test_api_monoid.py | 88 +++++++++++++++++-- 1 file changed, 82 insertions(+), 6 deletions(-) diff --git a/suitesparse_graphblas/tests/test_api_monoid.py b/suitesparse_graphblas/tests/test_api_monoid.py index 19c4823..5171a73 100644 --- a/suitesparse_graphblas/tests/test_api_monoid.py +++ b/suitesparse_graphblas/tests/test_api_monoid.py @@ -1,8 +1,36 @@ """Monoids of the functional API: the typed constructors, and monoids of user-defined types.""" -from suitesparse_graphblas import check_status, ffi, lib +import math + +import pytest + +from suitesparse_graphblas import check_status, exceptions, ffi, lib, libget, supports_complex from suitesparse_graphblas.api import binaryop, grb_type, monoid, vector +# Whether a constructor hands its monoid to the garbage collector (its default) or leaves +# freeing it to the caller (`free=None`) +GC = [pytest.param(True, id="gc"), pytest.param(False, id="manual")] + +needs_complex = pytest.mark.skipif(not supports_complex(), reason="no complex types") + +# suffix, C type, identity, terminal. GraphBLAS ignores the identity and terminal given with +# the operator of a known monoid, such as MAX, so these monoids use FIRST, which isn't one. +TYPES = [ + ("bool", "bool", True, False), + ("int8", "int8_t", -(2**7), 2**7 - 1), + ("int16", "int16_t", -(2**15), 2**15 - 1), + ("int32", "int32_t", -(2**31), 2**31 - 1), + ("int64", "int64_t", -(2**63), 2**63 - 1), + ("uint8", "uint8_t", 2**8 - 1, 1), + ("uint16", "uint16_t", 2**16 - 1, 1), + ("uint32", "uint32_t", 2**32 - 1, 1), + ("uint64", "uint64_t", 2**64 - 1, 1), + ("fp32", "float", -math.inf, 2.25), + ("fp64", "double", -math.inf, 1e300), + pytest.param("fc32", "GxB_FC32_t", 1.5 - 2j, -3 + 0.5j, marks=needs_complex), + pytest.param("fc64", "GxB_FC64_t", 1.5 - 2j, -3 + 1e300j, marks=needs_complex), +] + BIG = 64 # int64s in a value of a large user-defined type @@ -16,21 +44,60 @@ def _max_big(z, x, y): z[k] = max(x[k], y[k]) -def test_monoid_of_large_type(): +@pytest.mark.parametrize("gc", GC) +@pytest.mark.parametrize("with_terminal", [False, True], ids=["new", "terminal_new"]) +@pytest.mark.parametrize(("suffix", "ctype", "identity", "terminal"), TYPES) +def test_monoid_new(gc, with_terminal, suffix, ctype, identity, terminal): + op = libget(f"GrB_FIRST_{suffix.upper()}") + kwargs = {} if gc else {"free": None} + if with_terminal: + new = getattr(monoid, f"monoid_terminal_new_{suffix}") + m = new(op, identity, terminal, **kwargs) + else: + m = getattr(monoid, f"monoid_new_{suffix}")(op, identity, **kwargs) + assert monoid.monoid_operator(m) == op + code = libget(f"GrB_{suffix.upper()}_CODE") + assert monoid.monoid_get_int32(m, lib.GrB_OUTP_TYPE_CODE) == code + value = monoid.monoid_identity(m) + assert ffi.cast(f"{ctype}*", value)[0] == identity + has_terminal, value = monoid.monoid_terminal(m) + assert has_terminal == with_terminal + if with_terminal: + assert ffi.cast(f"{ctype}*", value)[0] == terminal + + # An empty vector reduces to the identity + u = vector.vector_new(libget(f"GrB_{suffix.upper()}"), 2) + result = ffi.new(f"{ctype}*") + reduce = libget(f"GrB_Vector_reduce_{suffix.upper()}") + check_status(u, reduce(result, ffi.NULL, m[0], u[0], ffi.NULL)) + assert result[0] == identity + if not gc: + monoid.monoid_free(m) + assert m[0] == ffi.NULL + + +@pytest.mark.parametrize("gc", GC) +@pytest.mark.parametrize("with_terminal", [False, True], ids=["new", "terminal_new"]) +def test_monoid_of_large_type(gc, with_terminal): size = 8 * BIG T = grb_type.grb_type_new(size) op = binaryop.binaryop_new(_max_big, T[0], T[0], T[0]) identity = ffi.new("int64_t[]", [-(2**63)] * BIG) terminal = ffi.new("int64_t[]", [2**63 - 1] * BIG) - m = monoid.monoid_terminal_new_udt(op[0], identity, terminal) + kwargs = {} if gc else {"free": None} + if with_terminal: + m = monoid.monoid_terminal_new_udt(op[0], identity, terminal, **kwargs) + else: + m = monoid.monoid_new_udt(op[0], identity, **kwargs) # GraphBLAS copies one value of the monoid's type, whatever its size value = monoid.monoid_identity(m) assert len(ffi.buffer(value)) >= size assert ffi.buffer(value)[:size] == ffi.buffer(identity)[:] has_terminal, value = monoid.monoid_terminal(m) - assert has_terminal - assert len(ffi.buffer(value)) >= size - assert ffi.buffer(value)[:size] == ffi.buffer(terminal)[:] + assert has_terminal == with_terminal + if with_terminal: + assert len(ffi.buffer(value)) >= size + assert ffi.buffer(value)[:size] == ffi.buffer(terminal)[:] u = vector.vector_new(T[0], 3) first = ffi.new("int64_t[]", list(range(BIG))) @@ -40,3 +107,12 @@ def test_monoid_of_large_type(): result = ffi.new("int64_t[]", BIG) check_status(u, lib.GrB_Vector_reduce_UDT(result, ffi.NULL, m[0], u[0], ffi.NULL)) assert list(result) == [max(k, BIG - k) for k in range(BIG)] + if not gc: + monoid.monoid_free(m) + assert m[0] == ffi.NULL + + +def test_monoid_new_fails(): + # The operator's inputs and output must have the same type + with pytest.raises(exceptions.DomainMismatch): + monoid.monoid_new_int64(lib.GrB_LT_INT64, 0) From f812c33bd3889c61f163d5e75b003988da0c534d Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:42:22 -0600 Subject: [PATCH 05/47] Test building and extracting matrices and vectors of each type The doctests extract tuples only from objects that have entries, so nothing took the path for an empty one, and the free=None paths of matrix_new, matrix_dup, vector_new and vector_dup never ran. For each type, extract from an empty matrix and vector and check the dtypes, then build one from values at the ends of the type's range and extract them again. Make and duplicate a matrix and a vector without garbage collection and free them by hand. --- .../tests/test_api_matrix_vector.py | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 suitesparse_graphblas/tests/test_api_matrix_vector.py diff --git a/suitesparse_graphblas/tests/test_api_matrix_vector.py b/suitesparse_graphblas/tests/test_api_matrix_vector.py new file mode 100644 index 0000000..c5ef022 --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_matrix_vector.py @@ -0,0 +1,89 @@ +"""Matrices and vectors of the functional API: building and extracting each type.""" + +import numpy as np +import pytest + +from suitesparse_graphblas import ffi, lib, libget, supports_complex +from suitesparse_graphblas.api import matrix, vector + +needs_complex = pytest.mark.skipif(not supports_complex(), reason="no complex types") + +# suffix, NumPy dtype, three values +TYPES = [ + ("bool", np.bool_, [True, False, True]), + ("int8", np.int8, [-(2**7), 0, 2**7 - 1]), + ("int16", np.int16, [-(2**15), 0, 2**15 - 1]), + ("int32", np.int32, [-(2**31), 0, 2**31 - 1]), + ("int64", np.int64, [-(2**63), 0, 2**63 - 1]), + ("uint8", np.uint8, [0, 1, 2**8 - 1]), + ("uint16", np.uint16, [0, 1, 2**16 - 1]), + ("uint32", np.uint32, [0, 1, 2**32 - 1]), + ("uint64", np.uint64, [0, 1, 2**64 - 1]), + ("fp32", np.float32, [-1.5, 0.0, 2.25]), + ("fp64", np.float64, [-1.5, 0.0, 1e300]), + pytest.param("fc32", np.complex64, [1.5 - 2j, 0j, -3 + 0.5j], marks=needs_complex), + pytest.param("fc64", np.complex128, [1.5 - 2j, 0j, -3 + 1e300j], marks=needs_complex), +] + + +@pytest.mark.parametrize(("suffix", "dtype", "values"), TYPES) +def test_matrix_build_and_extract_tuples(suffix, dtype, values): + extract = getattr(matrix, f"matrix_extract_tuples_{suffix}") + A = matrix.matrix_new(libget(f"GrB_{suffix.upper()}"), 3, 4) + for array, expected in zip(extract(A), [np.uint64, np.uint64, dtype]): + assert array.dtype == expected + assert array.size == 0 + + rows = np.array([2, 0, 1], dtype=np.uint64) + cols = np.array([1, 3, 0], dtype=np.uint64) + build = getattr(matrix, f"matrix_build_{suffix}") + build(A, rows, cols, np.array(values, dtype=dtype), 3, libget(f"GrB_FIRST_{suffix.upper()}")) + assert matrix.matrix_nvals(A) == 3 + rows, cols, vals = extract(A) + assert vals.dtype == dtype + entries = sorted(zip(rows.tolist(), cols.tolist(), vals.tolist())) + assert entries == [(0, 3, values[1]), (1, 0, values[2]), (2, 1, values[0])] + + +@pytest.mark.parametrize(("suffix", "dtype", "values"), TYPES) +def test_vector_build_and_extract_tuples(suffix, dtype, values): + extract = getattr(vector, f"vector_extract_tuples_{suffix}") + v = vector.vector_new(libget(f"GrB_{suffix.upper()}"), 5) + for array, expected in zip(extract(v), [np.uint64, dtype]): + assert array.dtype == expected + assert array.size == 0 + + indices = np.array([4, 0, 2], dtype=np.uint64) + build = getattr(vector, f"vector_build_{suffix}") + build(v, indices, np.array(values, dtype=dtype), 3, libget(f"GrB_FIRST_{suffix.upper()}")) + assert vector.vector_nvals(v) == 3 + indices, vals = extract(v) + assert vals.dtype == dtype + entries = sorted(zip(indices.tolist(), vals.tolist())) + assert entries == [(0, values[1]), (2, values[2]), (4, values[0])] + + +def test_matrix_without_gc(): + A = matrix.matrix_new(lib.GrB_INT64, 2, 3, free=None) + matrix.set_int64(A, 7, 1, 2) + B = matrix.matrix_dup(A, free=None) + matrix.matrix_free(A) + assert A[0] == ffi.NULL + # The copy has its own data + assert matrix.matrix_shape(B) == (2, 3) + assert matrix.get_int64(B, 1, 2) == 7 + matrix.matrix_free(B) + assert B[0] == ffi.NULL + + +def test_vector_without_gc(): + v = vector.vector_new(lib.GrB_INT64, 3, free=None) + vector.set_int64(v, 7, 2) + w = vector.vector_dup(v, free=None) + vector.vector_free(v) + assert v[0] == ffi.NULL + # The copy has its own data + assert vector.vector_size(w) == 3 + assert vector.get_int64(w, 2) == 7 + vector.vector_free(w) + assert w[0] == ffi.NULL From d8812d29e16c1c85e29946943f41f58f2e704af0 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:42:50 -0600 Subject: [PATCH 06/47] Mark the complex-type checks in matrix, vector and monoid as no branch The typed functions for FC32 and FC64 are defined under "if supports_complex():", which is always true: the cffi build always declares GraphBLAS.h's complex types (on MSVC through its own complex types). The false branch can't be taken, so coverage reported each check as a partial branch that no test could cover. --- suitesparse_graphblas/api/matrix.py | 2 +- suitesparse_graphblas/api/monoid.py | 2 +- suitesparse_graphblas/api/vector.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/api/matrix.py b/suitesparse_graphblas/api/matrix.py index 157d733..b6166e5 100644 --- a/suitesparse_graphblas/api/matrix.py +++ b/suitesparse_graphblas/api/matrix.py @@ -1873,7 +1873,7 @@ def get_fp64(A, i, j): return value[0] -if supports_complex(): +if supports_complex(): # pragma: no branch (the build always declares complex types) def set_fc32(A, value, i, j): """Set an fc32 value to the matrix at row `i` column `j`. diff --git a/suitesparse_graphblas/api/monoid.py b/suitesparse_graphblas/api/monoid.py index 1f55125..d2e3cce 100644 --- a/suitesparse_graphblas/api/monoid.py +++ b/suitesparse_graphblas/api/monoid.py @@ -379,7 +379,7 @@ def monoid_terminal_new_udt(op, identity, terminal, *, free=monoid_free): return m -if supports_complex(): +if supports_complex(): # pragma: no branch (the build always declares complex types) def monoid_new_fc32(op, identity, *, free=monoid_free): """Create a new GrB_Monoid with an fc32 identity. diff --git a/suitesparse_graphblas/api/vector.py b/suitesparse_graphblas/api/vector.py index f123028..5438941 100644 --- a/suitesparse_graphblas/api/vector.py +++ b/suitesparse_graphblas/api/vector.py @@ -1560,7 +1560,7 @@ def get_fp64(v, i): return value[0] -if supports_complex(): +if supports_complex(): # pragma: no branch (the build always declares complex types) def set_fc32(v, value, i): """Set an fc32 value to the vector at position `i`. From 60d5370c78ea75532a948abc571b8d299148fa71 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:46:21 -0600 Subject: [PATCH 07/47] Test binwrite/binread round trips of empty, sparse and iso matrices Round-trip every type, held by row and by column, in each sparsity, for an empty matrix, a 3x4 matrix with an empty row and column, and iso matrices (sparse and full), which nothing tested. Compare the entries exactly, and compare the format, sparsity status and control, switches and iso flag of the result. Test each opener with a str filename, and check the text header. The tests are added after the existing ones, which they leave alone. --- suitesparse_graphblas/tests/test_io.py | 142 +++++++++++++++++++++++++ 1 file changed, 142 insertions(+) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 1134314..2fe7e77 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -3,6 +3,7 @@ import platform from pathlib import Path +import numpy as np import pytest from suitesparse_graphblas import ( @@ -214,3 +215,144 @@ def test_binwrite_failure_keeps_matrix(tmp_path): with pytest.raises(OSError): binary.binwrite(A, tmp_path / "missing_directory" / "matrix.binfile") assert matrix.matrix_nvals(A) == 1 + + +_extract_tuples = { + lib.GrB_BOOL: matrix.matrix_extract_tuples_bool, + lib.GrB_INT8: matrix.matrix_extract_tuples_int8, + lib.GrB_INT16: matrix.matrix_extract_tuples_int16, + lib.GrB_INT32: matrix.matrix_extract_tuples_int32, + lib.GrB_INT64: matrix.matrix_extract_tuples_int64, + lib.GrB_UINT8: matrix.matrix_extract_tuples_uint8, + lib.GrB_UINT16: matrix.matrix_extract_tuples_uint16, + lib.GrB_UINT32: matrix.matrix_extract_tuples_uint32, + lib.GrB_UINT64: matrix.matrix_extract_tuples_uint64, + lib.GrB_FP32: matrix.matrix_extract_tuples_fp32, + lib.GrB_FP64: matrix.matrix_extract_tuples_fp64, +} + +if supports_complex(): + _extract_tuples.update( + { + lib.GxB_FC32: matrix.matrix_extract_tuples_fc32, + lib.GxB_FC64: matrix.matrix_extract_tuples_fc64, + } + ) + +_sparsities = { + lib.GxB_HYPERSPARSE: "hypersparse", + lib.GxB_SPARSE: "sparse", + lib.GxB_BITMAP: "bitmap", + lib.GxB_FULL: "full", +} + +# 3x4, so a matrix held by row and by column differ; "sparse" leaves row 1 and column 2 empty +_shape = (3, 4) +_sparse_indices = [(0, 1), (2, 3), (2, 0)] +_full_indices = [(i, j) for i in range(_shape[0]) for j in range(_shape[1])] + + +def _values(T): + """Four distinct values (two for BOOL) of type T, for entries to cycle through.""" + if T in bool_types: + return [True, False] + if T in signed_integer_types: + return [1, -42, 7, -100] + if T in unsigned_integer_types: + return [1, 42, 7, 200] + if T in real_types: + return [1.0, -42.5, 0.25, 3.0e5] + return [complex(1.0, 1.0), complex(42.0, -42.0), -0.5j, complex(3.0, 0.0)] + + +def _make_matrix(T, kind): + """A matrix of type T: "empty", "sparse", "full", or iso ("iso_sparse", "iso_full").""" + A = matrix.matrix_new(T, *_shape) + indices = {"empty": [], "sparse": _sparse_indices, "iso_sparse": _sparse_indices}.get( + kind, _full_indices + ) + values = _values(T) + setter = _element_setters[T] + for k, (i, j) in enumerate(indices): + value = values[0] if kind.startswith("iso") else values[k % len(values)] + check_status(A, setter(A[0], value, i, j)) + return A + + +def _is_iso(A): + iso = ffi.new("bool*") + check_status(A, lib.GxB_Matrix_iso(iso, A[0])) + return iso[0] + + +def _settings(A): + return { + "format": matrix.matrix_format(A), + "sparsity_status": matrix.matrix_sparsity_status(A), + "sparsity_control": matrix.matrix_sparsity_control(A), + "hyper_switch": matrix.matrix_hyper_switch(A), + "bitmap_switch": matrix.matrix_bitmap_switch(A), + "iso": _is_iso(A), + } + + +def _assert_matrices_equal(A, B): + T = matrix.matrix_type(A) + assert matrix.matrix_type(B) == T + assert matrix.matrix_shape(B) == matrix.matrix_shape(A) + for x, y in zip(_extract_tuples[T](A), _extract_tuples[T](B), strict=True): + np.testing.assert_array_equal(x, y) + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +@pytest.mark.parametrize( + "T", sorted(grb_types, key=binary._ss_typecodes.get), ids=binary._ss_typenames.get +) +def test_binwrite_binread_round_trip(tmp_path, T, sparsity): + path = tmp_path / "matrix.binfile" + for format in (lib.GxB_BY_ROW, lib.GxB_BY_COL): + for kind in ("empty", "sparse", "iso_sparse", "iso_full"): + A = _make_matrix(T, kind) + matrix.matrix_set_format(A, format) + matrix.matrix_set_sparsity_control(A, sparsity) + matrix.matrix_set_hyper_switch(A, 0.25) + matrix.matrix_set_bitmap_switch(A, 0.75) + matrix.matrix_wait(A, lib.GrB_MATERIALIZE) + expected = _settings(A) + # The cases cover what they say: GraphBLAS makes a matrix iso when its values are, + # and holds a matrix with every entry as asked (bitmap stands in for full otherwise) + assert expected["iso"] == kind.startswith("iso") + if kind.endswith("full"): + assert expected["sparsity_status"] == sparsity + + binary.binwrite(A, path) + B = binary.binread(path) + + _assert_matrices_equal(A, B) + assert _settings(B) == expected, (format, kind) + + +_openers = {"open": Path.open, "gzip": gzip.open, "bz2": bz2.open} +if lzma is not None: + _openers["lzma"] = lzma.open + + +@pytest.mark.parametrize("opener", _openers.values(), ids=_openers) +def test_binwrite_binread_opener(tmp_path, opener): + A = _make_matrix(lib.GrB_FP64, "sparse") + matrix.matrix_set_sparsity_control(A, lib.GxB_HYPERSPARSE) + path = str(tmp_path / "matrix.binfile") # a str works as well as a Path + binary.binwrite(A, path, opener=opener, comments="three entries") + B = binary.binread(path, opener=opener) + _assert_matrices_equal(A, B) + + # The file was written through `opener`, and starts with a readable header + with opener(path, "rb") as f: + header = f.read(binary.GRB_HEADER_LEN) + assert header.startswith(b"SuiteSparse:GraphBLAS matrix\n") + lines = header.decode("ascii").split("\n") + for line in ["nrows: 3", "ncols: 4", "nvals: 3", "format: HCSR", "type: GrB_FP64"]: + assert line in lines + assert "three entries" in lines + with Path(path).open("rb") as f: + assert f.read(len(header)).startswith(header) == (opener is Path.open) From 6401beba2b6b4491204380aaa8710a57964ecb52 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:46:25 -0600 Subject: [PATCH 08/47] binwrite: restore the matrix's sparsity control and switches binwrite unpacks the matrix to write its arrays and packs them back, but packing resets the sparsity control, hyper switch and bitmap switch to their defaults, so writing a matrix changed its settings (the file itself had the right ones). This is probably why the round-trip test has its sparsity-control assertion commented out. Set them again after packing. The new test, for each sparsity and for a write that fails, showed before the fix: {'bitmap_switch': 0.0599...} != {'bitmap_switch': 0.75} {'sparsity_control': 15} != {'sparsity_control': 8} {'hyper_switch': 0.0625} != {'hyper_switch': 0.25} --- suitesparse_graphblas/api/io/binary.py | 6 ++++++ suitesparse_graphblas/tests/test_io.py | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 974ecf0..eeb09b8 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -380,6 +380,12 @@ def binwrite(A, filename, comments=None, opener=Path.open): else: raise TypeError("This should never happen") + # Packing resets these to their defaults, so restore them (in the order `binread` sets + # them) + matrix.matrix_set_sparsity_control(A, sparsity_control[0]) + matrix.matrix_set_hyper_switch(A, hyper_switch[0]) + matrix.matrix_set_bitmap_switch(A, bitmap_switch[0]) + def binread(filename, opener=Path.open): """Read a Matrix from ``filename``, written by ``binwrite``. diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 2fe7e77..0ea9559 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -356,3 +356,24 @@ def test_binwrite_binread_opener(tmp_path, opener): assert "three entries" in lines with Path(path).open("rb") as f: assert f.read(len(header)).startswith(header) == (opener is Path.open) + + +@pytest.mark.parametrize("fails", [False, True], ids=["written", "failed"]) +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_binwrite_keeps_matrix_settings(tmp_path, sparsity, fails): + # Packing the arrays back into the matrix resets its sparsity control and switches to the + # defaults, and `binwrite` must leave the matrix as it was, whether or not writing worked + A = _make_matrix(lib.GrB_INT64, "full") + matrix.matrix_set_sparsity_control(A, sparsity) + matrix.matrix_set_hyper_switch(A, 0.25) + matrix.matrix_set_bitmap_switch(A, 0.75) + matrix.matrix_wait(A, lib.GrB_MATERIALIZE) + expected = _settings(A) + path = tmp_path / ("missing_directory" if fails else "") / "matrix.binfile" + if fails: + with pytest.raises(OSError): + binary.binwrite(A, path) + else: + binary.binwrite(A, path) + assert _settings(A) == expected + _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "full")) From cab3099a318db421c21a9404c39241330f5c3dbc Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:46:30 -0600 Subject: [PATCH 09/47] binwrite: repack the matrix when making the header fails binwrite makes the file's header after unpacking the matrix, but outside the try/finally that packs the arrays back. So comments that are not ASCII raised UnicodeEncodeError and left the matrix empty, its arrays lost. The new test showed, before the fix: (shapes (0,), (3,) mismatch) ACTUAL: array([], dtype=uint64) DESIRED: array([0, 2, 2], dtype=uint64) Make the header inside the try. The error is still raised, no file is written, and the matrix is left as it was. --- suitesparse_graphblas/api/io/binary.py | 32 +++++++++++++------------- suitesparse_graphblas/tests/test_io.py | 11 +++++++++ 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index eeb09b8..2f498e5 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -227,23 +227,23 @@ def binwrite(A, filename, comments=None, opener=Path.open): f"{lib.GxB_IMPLEMENTATION_SUB}" ) - vars = dict( # noqa: C408 - suitesparse_version=suitesparse_version, - user_agent="pygraphblas-" + __version__, - nrows=nrows[0], - ncols=ncols[0], - nvals=nvals[0], - nvec=nvec[0], - format=fmt_string, - size=typesize[0], - type=_ss_typenames[matrix_type[0]], - iso=int(is_iso[0]), - comments=comments, - ) - header_content = header_template.format(**vars) - header = f"{header_content: <{GRB_HEADER_LEN}}".encode("ascii") - try: + vars = dict( # noqa: C408 + suitesparse_version=suitesparse_version, + user_agent="pygraphblas-" + __version__, + nrows=nrows[0], + ncols=ncols[0], + nvals=nvals[0], + nvec=nvec[0], + format=fmt_string, + size=typesize[0], + type=_ss_typenames[matrix_type[0]], + iso=int(is_iso[0]), + comments=comments, + ) + header_content = header_template.format(**vars) + header = f"{header_content: <{GRB_HEADER_LEN}}".encode("ascii") + with opener(filename, "wb") as f: fwrite = f.write fwrite(header) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 0ea9559..9a73b92 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -377,3 +377,14 @@ def test_binwrite_keeps_matrix_settings(tmp_path, sparsity, fails): binary.binwrite(A, path) assert _settings(A) == expected _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "full")) + + +def test_binwrite_header_error_keeps_matrix(tmp_path): + # The header (which must be ASCII) is made after the matrix is unpacked, so a failure there + # must also put the arrays back + A = _make_matrix(lib.GrB_INT64, "sparse") + path = tmp_path / "matrix.binfile" + with pytest.raises(UnicodeEncodeError): + binary.binwrite(A, path, comments="café") + assert not path.exists() + _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "sparse")) From 46c02981eccd1fbf6d2618e12b1347dd439aa006 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:46:34 -0600 Subject: [PATCH 10/47] binread: raise EOFError when the header is truncated binread checked the length of the arrays it reads, but not of the header and the fields after it. A short read gave `ffi.from_buffer` too few bytes, and indexing the result read past the end of them. A file cut anywhere in its first 600 bytes or so raised AssertionError (the implementation check), TypeError, or, for a bitmap matrix, returned an empty 0x0 matrix. Cutting a 701-byte bitmap file at each length gave: AssertionError: 516, TypeError: 10, returned a matrix: 31, EOFError: 144 Check every read, and raise EOFError as for truncated arrays. The new test cuts files of each sparsity at every length. --- suitesparse_graphblas/api/io/binary.py | 8 +++++++- suitesparse_graphblas/tests/test_io.py | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 2f498e5..8742d87 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -396,7 +396,13 @@ def binread(filename, opener=Path.open): filename = Path(filename) with opener(filename, "rb") as f: - fread = f.read + + def fread(nbytes): + # A short read would leave `frombuff` pointing past the end of the data + data = f.read(nbytes) + if len(data) != nbytes: + raise EOFError(f"{filename} is truncated") + return data fread(GRB_HEADER_LEN) impl = frombuff("uint64_t*", fread(sizeof("uint64_t"))) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 9a73b92..3e29188 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -388,3 +388,17 @@ def test_binwrite_header_error_keeps_matrix(tmp_path): binary.binwrite(A, path, comments="café") assert not path.exists() _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "sparse")) + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_binread_truncated(tmp_path, sparsity): + A = _make_matrix(lib.GrB_INT64, "sparse") + matrix.matrix_set_sparsity_control(A, sparsity) + path = tmp_path / "matrix.binfile" + binary.binwrite(A, path) + data = path.read_bytes() + _assert_matrices_equal(A, binary.binread(path)) + for size in range(len(data)): + path.write_bytes(data[:size]) + with pytest.raises(EOFError, match="truncated"): + binary.binread(path) From 8004498b5e5e2ca807dd629cf30e9eb7e57c8b18 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:46:38 -0600 Subject: [PATCH 11/47] Test binread's errors for an unknown format or sparsity Patch the format and the sparsity status that binwrite wrote, and check that binread rejects each with its TypeError. --- suitesparse_graphblas/tests/test_io.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 3e29188..b128f08 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -1,6 +1,7 @@ import bz2 import gzip import platform +import struct from pathlib import Path import numpy as np @@ -402,3 +403,27 @@ def test_binread_truncated(tmp_path, sparsity): path.write_bytes(data[:size]) with pytest.raises(EOFError, match="truncated"): binary.binread(path) + + +# Where binwrite puts the matrix's format and sparsity status (int32 each), after the text +# header and the GraphBLAS version +_format_offset = binary.GRB_HEADER_LEN + ffi.sizeof("uint64_t") +_sparsity_offset = _format_offset + ffi.sizeof("GxB_Format_Value") + + +@pytest.mark.parametrize( + "offset, value, message", + [ + (_format_offset, 99, "Unknown format 99"), + (_sparsity_offset, 3, "Unknown sparsity status 3"), + ], + ids=["format", "sparsity"], +) +def test_binread_unknown_field(tmp_path, offset, value, message): + path = tmp_path / "matrix.binfile" + binary.binwrite(_make_matrix(lib.GrB_INT64, "sparse"), path) + data = bytearray(path.read_bytes()) + struct.pack_into("=i", data, offset, value) + path.write_bytes(data) + with pytest.raises(TypeError, match=message): + binary.binread(path) From 8f3028fd3b082b58f46ca1eed4b6bb12252442f9 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:46:42 -0600 Subject: [PATCH 12/47] Exclude binwrite's unreachable branches from coverage The final `else` of the unpacking cases was marked `# pragma nocover`, which the `pragma: no cover` pattern in pyproject.toml does not match. Spell it so, and mark the matching `else` of the packing cases, which can't run because the unpacking cases raised already. --- suitesparse_graphblas/api/io/binary.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 8742d87..71291e8 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -218,7 +218,7 @@ def binwrite(A, filename, comments=None, opener=Path.open): nvec[0] = nrows[0] fmt_string = "FULLR" - else: # pragma nocover + else: # pragma: no cover (defensive: a materialized matrix is one of the above) raise TypeError(f"Unknown Matrix format {format[0]}") suitesparse_version = ( @@ -377,7 +377,7 @@ def binwrite(A, filename, comments=None, opener=Path.open): elif by_row and is_full: check_status(A, lib.GxB_Matrix_pack_FullR(A[0], Ax, Ax_size[0], is_iso[0], NULL)) - else: + else: # pragma: no cover (unreachable: the unpacking above raised already) raise TypeError("This should never happen") # Packing resets these to their defaults, so restore them (in the order `binread` sets From aacf0eed7e90034de2cc82eb881ca851511f14f6 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:46:46 -0600 Subject: [PATCH 13/47] Test that long binwrite comments leave a readable file (xfail) binwrite pads its text header to 512 bytes but doesn't cut it there, so comments of more than about 330 characters make a longer header. binread skips exactly 512 bytes, and the file can't be read: the implementation check fails on the header's text. Whether binwrite should shorten such comments or refuse them is a choice of behavior, so this only marks the test as an expected failure. It passes with either fix, as long as the matrix is left as it was. --- suitesparse_graphblas/tests/test_io.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index b128f08..b5bee58 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -427,3 +427,20 @@ def test_binread_unknown_field(tmp_path, offset, value, message): path.write_bytes(data) with pytest.raises(TypeError, match=message): binary.binread(path) + + +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="binwrite lets comments make the header longer than the 512 bytes binread skips", +) +def test_binwrite_long_comments(tmp_path): + A = _make_matrix(lib.GrB_INT64, "sparse") + path = tmp_path / "matrix.binfile" + try: + binary.binwrite(A, path, comments="x" * binary.GRB_HEADER_LEN) + except ValueError: # refusing such comments would do as well as shortening them + assert not path.exists() + else: + _assert_matrices_equal(A, binary.binread(path)) + _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "sparse")) From 864d42690ca9fb3f736635adb7a74067b0ca808f Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:46:50 -0600 Subject: [PATCH 14/47] Test serialize's compression options, free argument and nthreads Test which compression get_serialize_desc puts on the descriptor (the level is added only for LZ4HC and ZSTD), round-trip matrices and vectors with each compression, and check that the compression and level change the size of the result, so they reach GraphBLAS. Test the `free` argument of deserialize_matrix and deserialize_vector: None or False leaves freeing to the caller, and a callable is called when the result is released. Invalid data raises InvalidObject. `nthreads` doesn't work: serialize sets GxB_NTHREADS on a descriptor, and GraphBLAS 10 has no such descriptor field (the number of threads is a GxB_Context setting), so serialize_matrix and serialize_vector raise InvalidValue whenever it is given. Fixing it means choosing how to use a context, so the test is marked as an expected failure. --- suitesparse_graphblas/tests/test_io.py | 163 ++++++++++++++++++++++++- 1 file changed, 162 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index b5bee58..65ebe25 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -30,7 +30,8 @@ if platform.system() == "Windows": pytest.skip("skipping windows-only tests", allow_module_level=True) -from suitesparse_graphblas.io import binary # isort:skip +from suitesparse_graphblas.exceptions import InvalidObject, InvalidValue # isort:skip +from suitesparse_graphblas.io import binary, serialize # isort:skip NULL = ffi.NULL @@ -444,3 +445,163 @@ def test_binwrite_long_comments(tmp_path): else: _assert_matrices_equal(A, binary.binread(path)) _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "sparse")) + + +def _compression(desc): + value = ffi.new("int32_t*") + check_status(desc, lib.GrB_Descriptor_get_INT32(desc, value, lib.GxB_COMPRESSION)) + return value[0] + + +def test_get_serialize_desc(): + # The default needs no descriptor, whatever the level + assert serialize.get_serialize_desc() is None + assert serialize.get_serialize_desc(None) is None + assert serialize.get_serialize_desc(lib.GxB_COMPRESSION_DEFAULT, 5) is None + # A level is added to the methods that have levels, and ignored by the others + get = serialize.get_serialize_desc + ZSTD, LZ4HC = lib.GxB_COMPRESSION_ZSTD, lib.GxB_COMPRESSION_LZ4HC + assert _compression(get(ZSTD)) == ZSTD + assert _compression(get(ZSTD, 19)) == ZSTD + 19 + assert _compression(get(LZ4HC, 9)) == LZ4HC + 9 + assert _compression(get(lib.GxB_COMPRESSION_LZ4, 9)) == lib.GxB_COMPRESSION_LZ4 + assert _compression(get(lib.GxB_COMPRESSION_NONE, 9)) == lib.GxB_COMPRESSION_NONE + + +_serialize_options = { + "none": (lib.GxB_COMPRESSION_NONE, None), + "default": (lib.GxB_COMPRESSION_DEFAULT, None), + "lz4": (lib.GxB_COMPRESSION_LZ4, None), + "lz4hc": (lib.GxB_COMPRESSION_LZ4HC, None), + "lz4hc-9": (lib.GxB_COMPRESSION_LZ4HC, 9), + "zstd": (lib.GxB_COMPRESSION_ZSTD, None), + "zstd-1": (lib.GxB_COMPRESSION_ZSTD, 1), + "zstd-19": (lib.GxB_COMPRESSION_ZSTD, 19), + "unset": (None, None), +} + + +def _numbered_matrix(n): + """An n-by-n INT64 matrix whose entries are 0, 1, ..., n*n - 1, by row.""" + A = matrix.matrix_new(lib.GrB_INT64, n, n) + rows = np.repeat(np.arange(n, dtype=np.uint64), n) + cols = np.tile(np.arange(n, dtype=np.uint64), n) + values = np.arange(n * n, dtype=np.int64) + matrix.matrix_build_int64(A, rows, cols, values, n * n, lib.GrB_PLUS_INT64) + return A + + +@pytest.mark.parametrize("option", _serialize_options) +def test_serialize_matrix_compression(option): + compression, level = _serialize_options[option] + for kind in ("empty", "sparse", "full", "iso_full"): + A = _make_matrix(lib.GrB_FP64, kind) + data = serialize.serialize_matrix(A, compression, level) + assert data.dtype == np.uint8 + _assert_matrices_equal(A, serialize.deserialize_matrix(data)) + # Anything with the buffer protocol will do + _assert_matrices_equal(A, serialize.deserialize_matrix(data.tobytes())) + + +@pytest.mark.parametrize("option", _serialize_options) +def test_serialize_vector_compression(option): + compression, level = _serialize_options[option] + v = vector.vector_new(lib.GrB_FP64, 5) + vector.set_fp64(v, 1.5, 1) + vector.set_fp64(v, -2.5, 4) + w = serialize.deserialize_vector(serialize.serialize_vector(v, compression, level)) + assert vector.vector_type(w) == lib.GrB_FP64 + assert vector.vector_size(w) == 5 + for x, y in zip( + vector.vector_extract_tuples_fp64(v), vector.vector_extract_tuples_fp64(w), strict=True + ): + np.testing.assert_array_equal(x, y) + + +def test_serialize_compression_reaches_graphblas(): + # The compression and level change the result, so they get to GraphBLAS + A = _numbered_matrix(100) + size = { + option: serialize.serialize_matrix(A, compression, level).nbytes + for option, compression, level in [ + ("none", lib.GxB_COMPRESSION_NONE, None), + ("lz4", lib.GxB_COMPRESSION_LZ4, None), + ("lz4hc-1", lib.GxB_COMPRESSION_LZ4HC, 1), + ("lz4hc-9", lib.GxB_COMPRESSION_LZ4HC, 9), + ("zstd-1", lib.GxB_COMPRESSION_ZSTD, 1), + ("zstd-19", lib.GxB_COMPRESSION_ZSTD, 19), + ] + } + assert size["none"] > 100 * 100 * 8 + assert size["none"] > size["lz4"] > size["zstd-1"] > size["zstd-19"] + assert size["lz4hc-1"] > size["lz4hc-9"] + v = vector.vector_new(lib.GrB_INT64, 1000) + for i in range(0, 1000, 3): + vector.set_int64(v, i, i) + none = serialize.serialize_vector(v, lib.GxB_COMPRESSION_NONE).nbytes + assert none > serialize.serialize_vector(v, lib.GxB_COMPRESSION_ZSTD).nbytes + + +@pytest.mark.parametrize("free", [None, False], ids=["None", "False"]) +def test_deserialize_without_free(free): + # The caller frees the result + A = _make_matrix(lib.GrB_INT64, "sparse") + B = serialize.deserialize_matrix(serialize.serialize_matrix(A), free=free) + _assert_matrices_equal(A, B) + matrix.matrix_free(B) + assert B[0] == NULL + v = vector.vector_new(lib.GrB_INT64, 3) + vector.set_int64(v, 7, 2) + w = serialize.deserialize_vector(serialize.serialize_vector(v), free=free) + assert vector.vector_nvals(w) == 1 + vector.vector_free(w) + assert w[0] == NULL + + +def test_deserialize_with_free(): + # `free` is called with the result once it is released + freed = [] + + def free_matrix(A): + freed.append(matrix.matrix_nvals(A)) + matrix.matrix_free(A) + + def free_vector(v): + freed.append(vector.vector_nvals(v)) + vector.vector_free(v) + + A = _make_matrix(lib.GrB_INT64, "sparse") + B = serialize.deserialize_matrix(serialize.serialize_matrix(A), free=free_matrix) + _assert_matrices_equal(A, B) + v = vector.vector_new(lib.GrB_INT64, 3) + vector.set_int64(v, 7, 2) + w = serialize.deserialize_vector(serialize.serialize_vector(v), free=free_vector) + assert freed == [] + ffi.release(B) + ffi.release(w) + assert freed == [3, 1] + + +def test_deserialize_invalid(): + for deserialize in (serialize.deserialize_matrix, serialize.deserialize_vector): + with pytest.raises(InvalidObject): + deserialize(bytes(64)) + + +@pytest.mark.xfail( + strict=True, + raises=InvalidValue, + reason="serialize sets nthreads on a descriptor, which GraphBLAS 10 rejects with " + "GrB_INVALID_VALUE: the number of threads is a GxB_Context setting now", +) +@pytest.mark.parametrize("kind", ["matrix", "vector"]) +def test_serialize_nthreads(kind): + if kind == "matrix": + A = _make_matrix(lib.GrB_INT64, "sparse") + B = serialize.deserialize_matrix(serialize.serialize_matrix(A, nthreads=1), nthreads=1) + _assert_matrices_equal(A, B) + else: + v = vector.vector_new(lib.GrB_INT64, 3) + vector.set_int64(v, 7, 2) + w = serialize.deserialize_vector(serialize.serialize_vector(v, nthreads=1), nthreads=1) + assert vector.vector_nvals(w) == 1 From eca077fc79384631bf4ec678c1a169dbc75a6106 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:38:50 -0600 Subject: [PATCH 15/47] iterator: describe kount, kseek and the return codes correctly Several docstrings disagreed with GraphBLAS's own description of the iterator (in GraphBLAS.h), and with what the functions return: - row_iterator_kount and col_iterator_kount don't count the entries in the current row or column: they give the number of rows (columns) the iterator holds, nrows (ncols) unless the matrix is hypersparse. - row_iterator_kseek and col_iterator_kseek don't seek the k-th entry of the current row: they seek the k-th row (column) held. - next_col and next_row return GrB_NO_VALUE at the end of a row or column, not GxB_EXHAUSTED; seek_row, seek_col, next_row and next_col return GrB_NO_VALUE for an empty row or column. - The attach functions never return GxB_EXHAUSTED; the row and column iterators raise NotImplementedException for the other format. Three doctests used an iterator before seeking it, which GraphBLAS leaves undefined; one showed next_col moving to the next entry, though it had returned GrB_NO_VALUE. Seek first, and show the return codes. Also say what getp and getpmax mean for a bitmap matrix or vector. --- suitesparse_graphblas/api/iterator.py | 120 +++++++++++++++++++------- 1 file changed, 88 insertions(+), 32 deletions(-) diff --git a/suitesparse_graphblas/api/iterator.py b/suitesparse_graphblas/api/iterator.py index bf47f1a..9382707 100644 --- a/suitesparse_graphblas/api/iterator.py +++ b/suitesparse_graphblas/api/iterator.py @@ -40,8 +40,8 @@ def iterator_new(*, free=iterator_free): def matrix_iterator_attach(it, A, desc=None): """Attach an iterator to a matrix for entry-wise iteration. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED`` (if the matrix - has no entries). Raises on other errors. + Returns ``lib.GrB_SUCCESS``, and raises on errors. The iterator is not at + any entry yet: move it to one with :func:`matrix_iterator_seek`. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -66,7 +66,9 @@ def matrix_iterator_attach(it, A, desc=None): def row_iterator_attach(it, A, desc=None): """Attach an iterator to a matrix for row-wise iteration. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, and raises on errors: ``NotImplementedException`` + if the matrix is held by column. The iterator is not at any row yet: move it + to one with :func:`row_iterator_seek_row` or :func:`row_iterator_kseek`. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -91,7 +93,9 @@ def row_iterator_attach(it, A, desc=None): def col_iterator_attach(it, A, desc=None): """Attach an iterator to a matrix for column-wise iteration. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, and raises on errors: ``NotImplementedException`` + if the matrix is held by row. The iterator is not at any column yet: move it + to one with :func:`col_iterator_seek_col` or :func:`col_iterator_kseek`. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -116,7 +120,8 @@ def col_iterator_attach(it, A, desc=None): def vector_iterator_attach(it, v, desc=None): """Attach an iterator to a vector. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, and raises on errors. The iterator is not at + any entry yet: move it to one with :func:`vector_iterator_seek`. >>> from suitesparse_graphblas import vector >>> v = vector.vector_new(lib.GrB_INT64, 3) @@ -145,7 +150,9 @@ def vector_iterator_attach(it, v, desc=None): def matrix_iterator_seek(it, p): """Seek the matrix entry iterator to position p. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, or ``lib.GxB_EXHAUSTED`` if ``p >= pmax``. For a + bitmap matrix, the iterator moves to the first entry at or after ``p``, and is + exhausted if there is none. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -219,12 +226,20 @@ def matrix_iterator_get_index(it): def matrix_iterator_getp(it): - """Get the current position of the matrix entry iterator.""" + """Get the current position of the matrix entry iterator. + + See :func:`matrix_iterator_getpmax`. + """ return lib.GxB_Matrix_Iterator_getp(it[0]) def matrix_iterator_getpmax(it): - """Get the maximum position of the matrix entry iterator.""" + """Get the end of the matrix entry iterator's positions. + + Positions run from 0 to ``pmax - 1``. ``pmax`` is the number of entries, + except for a bitmap matrix, where it is ``nrows * ncols`` (or 0 if it has no + entries) and a position may have no entry. + """ return lib.GxB_Matrix_Iterator_getpmax(it[0]) @@ -234,9 +249,12 @@ def matrix_iterator_getpmax(it): def row_iterator_seek_row(it, row): - """Seek the row iterator to a specific row. + """Seek the row iterator to a specific row, or the next row it holds. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS`` at the row's first entry, ``lib.GrB_NO_VALUE`` + if the row has no entries, or ``lib.GxB_EXHAUSTED`` if ``row >= nrows``. For + a hypersparse matrix, a row it doesn't hold is skipped for the next one it + does (see :func:`row_iterator_get_row_index`). >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -258,9 +276,9 @@ def row_iterator_seek_row(it, row): def row_iterator_next_row(it): - """Advance the row iterator to the next non-empty row. + """Advance the row iterator to the next row (which may skip empty rows). - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns as :func:`row_iterator_seek_row` does. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -271,12 +289,16 @@ def row_iterator_next_row(it): >>> it = iterator_new() >>> row_iterator_attach(it, A) == lib.GrB_SUCCESS True + >>> row_iterator_seek_row(it, 0) == lib.GrB_SUCCESS + True >>> row_iterator_get_row_index(it) 0 >>> row_iterator_next_row(it) == lib.GrB_SUCCESS True >>> row_iterator_get_row_index(it) 1 + >>> row_iterator_next_row(it) == lib.GxB_EXHAUSTED + True """ info = lib.GxB_rowIterator_nextRow(it[0]) @@ -286,7 +308,8 @@ def row_iterator_next_row(it): def row_iterator_next_col(it): """Advance the row iterator to the next entry in the current row. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, or ``lib.GrB_NO_VALUE`` if the row has no more + entries. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -297,13 +320,18 @@ def row_iterator_next_col(it): >>> it = iterator_new() >>> row_iterator_attach(it, A) == lib.GrB_SUCCESS True + >>> row_iterator_seek_row(it, 0) == lib.GrB_SUCCESS + True >>> iterator_get_int64(it) 10 - >>> _ = row_iterator_next_col(it) + >>> row_iterator_next_col(it) == lib.GrB_SUCCESS + True >>> iterator_get_int64(it) 20 >>> row_iterator_get_col_index(it) 1 + >>> row_iterator_next_col(it) == lib.GrB_NO_VALUE + True """ info = lib.GxB_rowIterator_nextCol(it[0]) @@ -311,26 +339,31 @@ def row_iterator_next_col(it): def row_iterator_kseek(it, k): - """Seek the row iterator to the k-th entry in the current row. + """Seek the row iterator to the k-th row it holds, for ``0 <= k < kount``. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + That is row ``k``, unless the matrix is hypersparse (see + :func:`row_iterator_kount`). Returns as :func:`row_iterator_seek_row` does. """ info = lib.GxB_rowIterator_kseek(it[0], k) return _check_info(info) def row_iterator_get_row_index(it): - """Get the current row index of the row iterator.""" + """Get the current row index of the row iterator (``nrows`` once exhausted).""" return lib.GxB_rowIterator_getRowIndex(it[0]) def row_iterator_get_col_index(it): - """Get the current column index of the row iterator.""" + """Get the column index of the row iterator's current entry.""" return lib.GxB_rowIterator_getColIndex(it[0]) def row_iterator_kount(it): - """Get the number of entries in the current row.""" + """Get the number of rows the row iterator holds, for :func:`row_iterator_kseek`. + + This is ``nrows``, unless the matrix is hypersparse; then it is the number of + rows in its hyperlist, which bounds the number of non-empty rows. + """ return lib.GxB_rowIterator_kount(it[0]) @@ -340,9 +373,12 @@ def row_iterator_kount(it): def col_iterator_seek_col(it, col): - """Seek the column iterator to a specific column. + """Seek the column iterator to a specific column, or the next column it holds. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS`` at the column's first entry, ``lib.GrB_NO_VALUE`` + if the column has no entries, or ``lib.GxB_EXHAUSTED`` if ``col >= ncols``. + For a hypersparse matrix, a column it doesn't hold is skipped for the next + one it does (see :func:`col_iterator_get_col_index`). >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -365,9 +401,9 @@ def col_iterator_seek_col(it, col): def col_iterator_next_col(it): - """Advance the column iterator to the next non-empty column. + """Advance the column iterator to the next column (which may skip empty columns). - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns as :func:`col_iterator_seek_col` does. >>> from suitesparse_graphblas import matrix >>> A = matrix.matrix_new(lib.GrB_INT64, 2, 2) @@ -379,12 +415,16 @@ def col_iterator_next_col(it): >>> it = iterator_new() >>> col_iterator_attach(it, A) == lib.GrB_SUCCESS True + >>> col_iterator_seek_col(it, 0) == lib.GrB_SUCCESS + True >>> col_iterator_get_col_index(it) 0 >>> col_iterator_next_col(it) == lib.GrB_SUCCESS True >>> col_iterator_get_col_index(it) 1 + >>> col_iterator_next_col(it) == lib.GxB_EXHAUSTED + True """ info = lib.GxB_colIterator_nextCol(it[0]) @@ -394,33 +434,39 @@ def col_iterator_next_col(it): def col_iterator_next_row(it): """Advance the column iterator to the next entry in the current column. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, or ``lib.GrB_NO_VALUE`` if the column has no + more entries. """ info = lib.GxB_colIterator_nextRow(it[0]) return _check_info(info) def col_iterator_kseek(it, k): - """Seek the column iterator to the k-th entry in the current column. + """Seek the column iterator to the k-th column it holds, for ``0 <= k < kount``. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + That is column ``k``, unless the matrix is hypersparse (see + :func:`col_iterator_kount`). Returns as :func:`col_iterator_seek_col` does. """ info = lib.GxB_colIterator_kseek(it[0], k) return _check_info(info) def col_iterator_get_col_index(it): - """Get the current column index of the column iterator.""" + """Get the current column index of the column iterator (``ncols`` once exhausted).""" return lib.GxB_colIterator_getColIndex(it[0]) def col_iterator_get_row_index(it): - """Get the current row index of the column iterator.""" + """Get the row index of the column iterator's current entry.""" return lib.GxB_colIterator_getRowIndex(it[0]) def col_iterator_kount(it): - """Get the number of entries in the current column.""" + """Get the number of columns the column iterator holds, for :func:`col_iterator_kseek`. + + This is ``ncols``, unless the matrix is hypersparse; then it is the number of + columns in its hyperlist, which bounds the number of non-empty columns. + """ return lib.GxB_colIterator_kount(it[0]) @@ -432,7 +478,9 @@ def col_iterator_kount(it): def vector_iterator_seek(it, p): """Seek the vector iterator to position p. - Returns ``lib.GrB_SUCCESS`` or ``lib.GxB_EXHAUSTED``. + Returns ``lib.GrB_SUCCESS``, or ``lib.GxB_EXHAUSTED`` if ``p >= pmax``. For a + bitmap vector, the iterator moves to the first entry at or after ``p``, and is + exhausted if there is none. >>> from suitesparse_graphblas import vector >>> v = vector.vector_new(lib.GrB_INT64, 3) @@ -491,12 +539,20 @@ def vector_iterator_get_index(it): def vector_iterator_getp(it): - """Get the current position of the vector iterator.""" + """Get the current position of the vector iterator. + + See :func:`vector_iterator_getpmax`. + """ return lib.GxB_Vector_Iterator_getp(it[0]) def vector_iterator_getpmax(it): - """Get the maximum position of the vector iterator.""" + """Get the end of the vector iterator's positions. + + Positions run from 0 to ``pmax - 1``. ``pmax`` is the number of entries, + except for a bitmap vector, where it is its size (or 0 if it has no entries) + and a position may have no entry. + """ return lib.GxB_Vector_Iterator_getpmax(it[0]) From 9cb73141c52713f332286212a8305b0dc70518f3 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:38:53 -0600 Subject: [PATCH 16/47] Test the iterator API Iterate over matrices of each sparsity with the entry, row and column iterators (as GraphBLAS's documentation does), and over vectors, and compare with the entries. Test kount and kseek, including on hypersparse matrices, seeking empty rows and columns, positions in bitmap matrices and vectors, the formats the row and column iterators need, iterator_new's `free` argument, and each type's value getter at the limits of its type. --- suitesparse_graphblas/tests/test_iterator.py | 328 +++++++++++++++++++ 1 file changed, 328 insertions(+) create mode 100644 suitesparse_graphblas/tests/test_iterator.py diff --git a/suitesparse_graphblas/tests/test_iterator.py b/suitesparse_graphblas/tests/test_iterator.py new file mode 100644 index 0000000..af2fe4e --- /dev/null +++ b/suitesparse_graphblas/tests/test_iterator.py @@ -0,0 +1,328 @@ +import pytest + +from suitesparse_graphblas import ( + bool_types, + complex_types, + exceptions, + ffi, + grb_types, + lib, + matrix, + real_types, + signed_integer_types, + supports_complex, + vector, +) +from suitesparse_graphblas.api import iterator + +SUCCESS = lib.GrB_SUCCESS +NO_VALUE = lib.GrB_NO_VALUE +EXHAUSTED = lib.GxB_EXHAUSTED + +_sparsities = { + lib.GxB_HYPERSPARSE: "hypersparse", + lib.GxB_SPARSE: "sparse", + lib.GxB_BITMAP: "bitmap", + lib.GxB_FULL: "full", +} + +# 5x4, with rows 1 and 3 and column 1 empty +_shape = (5, 4) +_entries = {(0, 2): 10, (2, 3): 20, (2, 0): 30, (4, 2): 40, (0, 0): 50} + + +def _matrix(format, sparsity): + """An INT64 matrix with `_entries`, or with every entry (i * 10 + j) if `sparsity` is full.""" + A = matrix.matrix_new(lib.GrB_INT64, *_shape) + if sparsity == lib.GxB_FULL: + entries = {(i, j): i * 10 + j for i in range(_shape[0]) for j in range(_shape[1])} + else: + entries = _entries + for (i, j), value in entries.items(): + matrix.set_int64(A, value, i, j) + matrix.matrix_set_format(A, format) + matrix.matrix_set_sparsity_control(A, sparsity) + matrix.matrix_wait(A, lib.GrB_MATERIALIZE) + assert matrix.matrix_sparsity_status(A) == sparsity + return A, sorted((i, j, value) for (i, j), value in entries.items()) + + +def test_check_info(): + for info in [SUCCESS, NO_VALUE, EXHAUSTED]: + assert iterator._check_info(info) == info + with pytest.raises(exceptions.InvalidIndex): + iterator._check_info(lib.GrB_INVALID_INDEX) + with pytest.raises(RuntimeError, match="info=-12345"): + iterator._check_info(-12345) + + +def test_iterator_new_free(): + it = iterator.iterator_new(free=None) + assert it[0] != ffi.NULL + iterator.iterator_free(it) + assert it[0] == ffi.NULL + + freed = [] + + def free(it): + freed.append(it) + iterator.iterator_free(it) + + it = iterator.iterator_new(free=free) + assert freed == [] + ffi.release(it) + assert len(freed) == 1 + assert freed[0][0] == ffi.NULL + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +@pytest.mark.parametrize("format", [lib.GxB_BY_ROW, lib.GxB_BY_COL], ids=["by_row", "by_col"]) +def test_matrix_iterator(format, sparsity): + A, expected = _matrix(format, sparsity) + it = iterator.iterator_new() + assert iterator.matrix_iterator_attach(it, A) == SUCCESS + pmax = iterator.matrix_iterator_getpmax(it) + if sparsity == lib.GxB_BITMAP: + assert pmax == _shape[0] * _shape[1] + else: + assert pmax == len(expected) + entries = [] + info = iterator.matrix_iterator_seek(it, 0) + while info != EXHAUSTED: + assert info == SUCCESS + p = iterator.matrix_iterator_getp(it) + assert 0 <= p < pmax + i, j = iterator.matrix_iterator_get_index(it) + entries.append((i, j, iterator.iterator_get_int64(it))) + info = iterator.matrix_iterator_next(it) + assert sorted(entries) == expected + # Held by row, the entries come by row; held by column, by column + if format == lib.GxB_BY_ROW: + assert entries == expected + else: + assert entries == sorted(expected, key=lambda e: (e[1], e[0])) + + # Seeking a position goes to the entry there, or (for bitmap) the next one + for p in range(pmax): + assert iterator.matrix_iterator_seek(it, p) == SUCCESS or sparsity == lib.GxB_BITMAP + if sparsity != lib.GxB_BITMAP: + assert iterator.matrix_iterator_getp(it) == p + assert iterator.matrix_iterator_seek(it, pmax) == EXHAUSTED + + +def _row_iterate(it, seek, next_vector, next_entry, get_vector_index, get_entry_index): + """Iterate over the entries of A as GraphBLAS's documentation does.""" + entries = [] + info = seek(it, 0) + while info != EXHAUSTED: + k = get_vector_index(it) + while info == SUCCESS: + entries.append((k, get_entry_index(it), iterator.iterator_get_int64(it))) + info = next_entry(it) + assert info == NO_VALUE + info = next_vector(it) + return entries + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_row_iterator(sparsity): + A, expected = _matrix(lib.GxB_BY_ROW, sparsity) + nrows = _shape[0] + it = iterator.iterator_new() + assert iterator.row_iterator_attach(it, A) == SUCCESS + entries = _row_iterate( + it, + iterator.row_iterator_seek_row, + iterator.row_iterator_next_row, + iterator.row_iterator_next_col, + iterator.row_iterator_get_row_index, + iterator.row_iterator_get_col_index, + ) + assert entries == expected + assert iterator.row_iterator_get_row_index(it) == nrows # exhausted + + rows = sorted({i for i, _, _ in expected}) + kount = iterator.row_iterator_kount(it) + if sparsity == lib.GxB_HYPERSPARSE: + assert len(rows) <= kount <= nrows + else: + assert kount == nrows + visited = [] + for k in range(kount): + info = iterator.row_iterator_kseek(it, k) + i = iterator.row_iterator_get_row_index(it) + if sparsity != lib.GxB_HYPERSPARSE: + assert i == k + assert info == (SUCCESS if i in rows else NO_VALUE) + visited.append(i) + assert set(rows) <= set(visited) + assert iterator.row_iterator_kseek(it, kount) == EXHAUSTED + + # Seeking an empty row: it has no entries, or (if hypersparse) the next row is found + info = iterator.row_iterator_seek_row(it, 1) + if sparsity == lib.GxB_HYPERSPARSE: + assert info == SUCCESS + assert iterator.row_iterator_get_row_index(it) == 2 + else: + assert info == (SUCCESS if sparsity == lib.GxB_FULL else NO_VALUE) + assert iterator.row_iterator_get_row_index(it) == 1 + assert iterator.row_iterator_seek_row(it, nrows) == EXHAUSTED + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_col_iterator(sparsity): + A, expected = _matrix(lib.GxB_BY_COL, sparsity) + expected = sorted((j, i, value) for i, j, value in expected) + ncols = _shape[1] + it = iterator.iterator_new() + assert iterator.col_iterator_attach(it, A) == SUCCESS + entries = _row_iterate( + it, + iterator.col_iterator_seek_col, + iterator.col_iterator_next_col, + iterator.col_iterator_next_row, + iterator.col_iterator_get_col_index, + iterator.col_iterator_get_row_index, + ) + assert entries == expected + assert iterator.col_iterator_get_col_index(it) == ncols # exhausted + + cols = sorted({j for j, _, _ in expected}) + kount = iterator.col_iterator_kount(it) + if sparsity == lib.GxB_HYPERSPARSE: + assert len(cols) <= kount <= ncols + else: + assert kount == ncols + visited = [] + for k in range(kount): + info = iterator.col_iterator_kseek(it, k) + j = iterator.col_iterator_get_col_index(it) + if sparsity != lib.GxB_HYPERSPARSE: + assert j == k + assert info == (SUCCESS if j in cols else NO_VALUE) + visited.append(j) + assert set(cols) <= set(visited) + assert iterator.col_iterator_kseek(it, kount) == EXHAUSTED + + # Seeking an empty column: it has no entries, or (if hypersparse) the next column is found + info = iterator.col_iterator_seek_col(it, 1) + if sparsity == lib.GxB_HYPERSPARSE: + assert info == SUCCESS + assert iterator.col_iterator_get_col_index(it) == 2 + else: + assert info == (SUCCESS if sparsity == lib.GxB_FULL else NO_VALUE) + assert iterator.col_iterator_get_col_index(it) == 1 + assert iterator.col_iterator_seek_col(it, ncols) == EXHAUSTED + + +def test_row_and_col_iterators_need_their_format(): + it = iterator.iterator_new() + by_col, _ = _matrix(lib.GxB_BY_COL, lib.GxB_SPARSE) + with pytest.raises(exceptions.NotImplementedException): + iterator.row_iterator_attach(it, by_col) + by_row, _ = _matrix(lib.GxB_BY_ROW, lib.GxB_SPARSE) + with pytest.raises(exceptions.NotImplementedException): + iterator.col_iterator_attach(it, by_row) + # The entry iterator takes either + assert iterator.matrix_iterator_attach(it, by_col) == SUCCESS + assert iterator.matrix_iterator_attach(it, by_row) == SUCCESS + + +@pytest.mark.parametrize("sparsity", _sparsities, ids=_sparsities.get) +def test_vector_iterator(sparsity): + size = 6 + v = vector.vector_new(lib.GrB_FP64, size) + if sparsity == lib.GxB_FULL: + expected = [(i, i + 0.5) for i in range(size)] + else: + expected = [(1, 1.5), (4, -2.5), (5, 0.25)] + for i, value in expected: + vector.set_fp64(v, value, i) + check = lib.GxB_Vector_Option_set_INT32(v[0], lib.GxB_SPARSITY_CONTROL, sparsity) + assert check == SUCCESS + vector.vector_wait(v, lib.GrB_MATERIALIZE) + + it = iterator.iterator_new() + assert iterator.vector_iterator_attach(it, v) == SUCCESS + pmax = iterator.vector_iterator_getpmax(it) + assert pmax == (size if sparsity == lib.GxB_BITMAP else len(expected)) + entries = [] + info = iterator.vector_iterator_seek(it, 0) + while info != EXHAUSTED: + assert info == SUCCESS + assert 0 <= iterator.vector_iterator_getp(it) < pmax + entries.append((iterator.vector_iterator_get_index(it), iterator.iterator_get_fp64(it))) + info = iterator.vector_iterator_next(it) + assert entries == expected + if sparsity == lib.GxB_BITMAP: + # Position 2 has no entry, so seeking it finds the one at 4 + assert iterator.vector_iterator_seek(it, 2) == SUCCESS + assert iterator.vector_iterator_getp(it) == 4 + assert iterator.vector_iterator_get_index(it) == 4 + else: + assert iterator.vector_iterator_seek(it, 1) == SUCCESS + assert iterator.vector_iterator_getp(it) == 1 + assert iterator.vector_iterator_seek(it, pmax) == EXHAUSTED + + +def test_vector_iterator_empty(): + v = vector.vector_new(lib.GrB_INT64, 3) + it = iterator.iterator_new() + assert iterator.vector_iterator_attach(it, v) == SUCCESS + assert iterator.vector_iterator_getpmax(it) == 0 + assert iterator.vector_iterator_seek(it, 0) == EXHAUSTED + + +_type_names = { + lib.GrB_BOOL: "bool", + lib.GrB_INT8: "int8", + lib.GrB_INT16: "int16", + lib.GrB_INT32: "int32", + lib.GrB_INT64: "int64", + lib.GrB_UINT8: "uint8", + lib.GrB_UINT16: "uint16", + lib.GrB_UINT32: "uint32", + lib.GrB_UINT64: "uint64", + lib.GrB_FP32: "fp32", + lib.GrB_FP64: "fp64", +} +if supports_complex(): + _type_names[lib.GxB_FC32] = "fc32" + _type_names[lib.GxB_FC64] = "fc64" + + +def _extreme_values(T): + """Values of type T, including its limits, that its C type holds exactly.""" + name = _type_names[T] + if T in bool_types: + return [True, False] + if T in signed_integer_types: + bits = int(name[3:]) + return [-(2 ** (bits - 1)), -1, 2 ** (bits - 1) - 1] + if T in real_types: + return [-0.5, 2.0**100, 2.0**-20] + if T in complex_types: + return [complex(-0.5, 2.0), complex(2.0**100, -1.0), 2.0j] + bits = int(name[4:]) + return [0, 1, 2**bits - 1] + + +@pytest.mark.parametrize("T", sorted(grb_types, key=_type_names.get), ids=_type_names.get) +def test_iterator_get(T): + name = _type_names[T] + values = _extreme_values(T) + v = vector.vector_new(T, len(values)) + setter = getattr(vector, f"set_{name}") + for i, value in enumerate(values): + setter(v, value, i) + vector.vector_wait(v, lib.GrB_MATERIALIZE) + get = getattr(iterator, f"iterator_get_{name}") + it = iterator.iterator_new() + iterator.vector_iterator_attach(it, v) + got = [] + info = iterator.vector_iterator_seek(it, 0) + while info == SUCCESS: + got.append(get(it)) + info = iterator.vector_iterator_next(it) + assert got == values + assert all(type(x) is type(y) for x, y in zip(got, values, strict=True)) From df5b39a960f39109d790589f9c5a6e908fc6df35 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:39:31 -0600 Subject: [PATCH 17/47] Test the scalar getters and setters of every type Set and get each type's limits, check that a getter returns None for a scalar with no value, that the value has the right Python type, that scalar_dup copies it and scalar_clear removes it, and that getters of other types cast. Test the `free` argument of scalar_new and scalar_dup. --- suitesparse_graphblas/tests/test_scalar.py | 95 +++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_scalar.py b/suitesparse_graphblas/tests/test_scalar.py index d413c29..f313dcb 100644 --- a/suitesparse_graphblas/tests/test_scalar.py +++ b/suitesparse_graphblas/tests/test_scalar.py @@ -1,6 +1,6 @@ import pytest -from suitesparse_graphblas import ffi, lib, supports_complex # noqa: F401 +from suitesparse_graphblas import ffi, lib, scalar, supports_complex @pytest.mark.skipif("not supports_complex()") @@ -10,3 +10,96 @@ def test_complex(): assert lib.GrB_Scalar_new(s, lib.GxB_FC64) == success assert lib.GxB_Scalar_setElement_FC64(s[0], 1j) == success assert lib.GrB_Scalar_free(s) == success + + +_type_names = { + lib.GrB_BOOL: "bool", + lib.GrB_INT8: "int8", + lib.GrB_INT16: "int16", + lib.GrB_INT32: "int32", + lib.GrB_INT64: "int64", + lib.GrB_UINT8: "uint8", + lib.GrB_UINT16: "uint16", + lib.GrB_UINT32: "uint32", + lib.GrB_UINT64: "uint64", + lib.GrB_FP32: "fp32", + lib.GrB_FP64: "fp64", +} +if supports_complex(): + _type_names[lib.GxB_FC32] = "fc32" + _type_names[lib.GxB_FC64] = "fc64" + + +def _values(name): + """Values for a scalar of type `name`, including its limits, that it holds exactly.""" + if name == "bool": + return [True, False] + if name.startswith("int"): + bits = int(name[3:]) + return [-(2 ** (bits - 1)), -1, 2 ** (bits - 1) - 1] + if name.startswith("uint"): + bits = int(name[4:]) + return [0, 1, 2**bits - 1] + if name.startswith("fp"): + return [-0.5, 2.0**100, 2.0**-20] + return [complex(-0.5, 2.0), complex(2.0**100, -1.0), 2.0j] + + +@pytest.mark.parametrize("T", sorted(_type_names, key=_type_names.get), ids=_type_names.get) +def test_set_get(T): + name = _type_names[T] + set_value = getattr(scalar, f"set_{name}") + get_value = getattr(scalar, f"get_{name}") + s = scalar.scalar_new(T) + assert scalar.scalar_type(s) == T + assert get_value(s) is None # no value yet + for value in _values(name): + set_value(s, value) + got = get_value(s) + assert got == value + assert type(got) is type(value) + + t = scalar.scalar_dup(s) + assert scalar.scalar_type(t) == T + scalar.scalar_clear(s) + assert get_value(s) is None + assert get_value(t) == value # the duplicate has its own value + + +def test_free(): + # With free=None, the caller frees the scalar + s = scalar.scalar_new(lib.GrB_INT64, free=None) + scalar.set_int64(s, 3) + t = scalar.scalar_dup(s, free=None) + assert scalar.get_int64(t) == 3 + scalar.scalar_free(s) + scalar.scalar_free(t) + assert s[0] == ffi.NULL + assert t[0] == ffi.NULL + + # Otherwise `free` is called with it once it is released + freed = [] + + def free(s): + freed.append(scalar.get_int64(s)) + scalar.scalar_free(s) + + s = scalar.scalar_new(lib.GrB_INT64, free=free) + scalar.set_int64(s, 4) + t = scalar.scalar_dup(s, free=free) + scalar.set_int64(t, 5) + assert freed == [] + ffi.release(s) + ffi.release(t) + assert freed == [4, 5] + + +def test_get_casts(): + # A getter of another type casts the value, as C does + s = scalar.scalar_new(lib.GrB_INT32) + scalar.set_int32(s, -7) + assert scalar.get_fp64(s) == -7.0 + assert scalar.get_int8(s) == -7 + assert scalar.get_bool(s) is True + scalar.set_fp64(s, 2.75) + assert scalar.get_int32(s) == 2 From ba87f6831d19adb3019c7588327a8f5256003259 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:32:12 -0600 Subject: [PATCH 18/47] check_status: raise GraphBLASException for codes it has no class for check_status picked the exception class with _error_code_lookup[code], which has no entry for GrB_ALREADY_SET, GxB_GPU_ERROR or GxB_OUTPUT_IS_READONLY. GraphBLAS returns GrB_ALREADY_SET when an object's name is set a second time, so calling grb_type_set_string(T, lib.GrB_NAME, ...) twice raised KeyError: -9 instead of a GraphBLAS error. Fall back to the base class, exceptions.GraphBLASException. Giving these codes classes of their own would add public names, so this change doesn't. The new tests pass every GrB_Info code in the header to check_status and set a type's name twice. Before the fix they failed with KeyError -9, -7002 and -7003. --- suitesparse_graphblas/__init__.py | 4 +- .../tests/test_exceptions.py | 44 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 48eac6c..3ea8723 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -238,7 +238,9 @@ def check_status(obj, response_code): string = ffi.new("char**") error_func(string, obj) text = ffi.string(string[0]).decode() - raise _error_code_lookup[response_code](text) + # Codes without a class of their own (GrB_ALREADY_SET, GxB_OUTPUT_IS_READONLY, + # GxB_GPU_ERROR, or any new one) raise the base class + raise _error_code_lookup.get(response_code, ex.GraphBLASException)(text) class burble: diff --git a/suitesparse_graphblas/tests/test_exceptions.py b/suitesparse_graphblas/tests/test_exceptions.py index 26b7861..05c27bd 100644 --- a/suitesparse_graphblas/tests/test_exceptions.py +++ b/suitesparse_graphblas/tests/test_exceptions.py @@ -1,6 +1,7 @@ import pytest from suitesparse_graphblas import check_status, exceptions, ffi, lib +from suitesparse_graphblas.api import grb_type def test_check_status(): @@ -10,3 +11,46 @@ def test_check_status(): check_status(A, lib.GrB_PANIC) with pytest.raises(exceptions.Panic): check_status(A[0], lib.GrB_PANIC) + + +def test_check_status_success_and_no_value(): + A = ffi.new("GrB_Matrix*") + check_status(A, lib.GrB_Matrix_new(A, lib.GrB_BOOL, 2, 2)) + assert check_status(A, lib.GrB_SUCCESS) is None + # GrB_NO_VALUE is not an error: the exception class is returned, not raised + assert check_status(A, lib.GrB_NO_VALUE) is exceptions.NoValue + + +_error_names = sorted( + name + for name, info in ffi.typeof("GrB_Info").relements.items() + if info not in {lib.GrB_SUCCESS, lib.GrB_NO_VALUE} +) + + +@pytest.mark.parametrize("name", _error_names) +def test_check_status_raises_for_every_error_code(name): + # Every GrB_Info that GraphBLAS can return, so a code added by a new + # GraphBLAS can't escape as a KeyError + info = getattr(lib, name) + A = ffi.new("GrB_Matrix*") + check_status(A, lib.GrB_Matrix_new(A, lib.GrB_BOOL, 2, 2)) + expected = StopIteration if info == lib.GxB_EXHAUSTED else exceptions.GraphBLASException + with pytest.raises(expected): + check_status(A, info) + + +def test_check_status_already_set(): + # GraphBLAS returns GrB_ALREADY_SET when the name of an object is set twice + T = grb_type.grb_type_new(8) + grb_type.grb_type_set_string(T, lib.GrB_NAME, "first_name") + with pytest.raises(exceptions.GraphBLASException): + grb_type.grb_type_set_string(T, lib.GrB_NAME, "second_name") + assert grb_type.grb_type_get_string(T, lib.GrB_NAME) == "first_name" + + +def test_check_status_unknown_object(): + # The error string is looked up by the type of the object, so an object + # that isn't a GraphBLAS handle is a TypeError, not a crash + with pytest.raises(TypeError, match="Unknown cname int \\*"): + check_status(ffi.new("int*"), lib.GrB_INVALID_VALUE) From b5f6adbf091db1a39cbae14ebf1b7e7c5dd2fe42 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:34:19 -0600 Subject: [PATCH 19/47] Size string buffers from get_SIZE in global_get_string, grb_type_get_string Both read the string into ffi.new("char[256]"), but GrB_Global_get_String and GrB_Type_get_String strcpy the whole string into the caller's buffer. Any longer string overran the buffer and came back cut at 256 characters. Several global strings are always longer: GxB_LIBRARY_LICENSE (614 characters), GxB_API_ABOUT (346). JIT settings can be longer too (GxB_JIT_C_COMPILER_FLAGS can be 900+), and so can a type's GxB_JIT_C_DEFINITION. Ask GraphBLAS for the size with *_get_SIZE first and allocate that much. The new tests read the two long global strings, set and read back a 1000-character GxB_JIT_C_PREFACE, and read back a type definition longer than 256 characters. Before the fix, each returned only the first 256 characters. --- suitesparse_graphblas/api/global_options.py | 8 +++-- suitesparse_graphblas/api/grb_type.py | 5 ++- .../tests/test_api_objects.py | 12 +++++++ .../tests/test_global_options.py | 34 +++++++++++++++++++ 4 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 suitesparse_graphblas/tests/test_api_objects.py create mode 100644 suitesparse_graphblas/tests/test_global_options.py diff --git a/suitesparse_graphblas/api/global_options.py b/suitesparse_graphblas/api/global_options.py index 85224e4..03ddf15 100644 --- a/suitesparse_graphblas/api/global_options.py +++ b/suitesparse_graphblas/api/global_options.py @@ -129,8 +129,12 @@ def global_get_string(field): True """ - val = ffi.new("char[256]") - info = lib.GrB_Global_get_String(lib.GrB_GLOBAL, val, field) + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + info = lib.GrB_Global_get_SIZE(lib.GrB_GLOBAL, size, field) + if info == lib.GrB_SUCCESS: + val = ffi.new("char[]", size[0]) + info = lib.GrB_Global_get_String(lib.GrB_GLOBAL, val, field) if info != lib.GrB_SUCCESS: raise _error_code_lookup.get(info, RuntimeError)( f"GrB_Global_get_String failed with info={info}" diff --git a/suitesparse_graphblas/api/grb_type.py b/suitesparse_graphblas/api/grb_type.py index 1c01fc3..5552de0 100644 --- a/suitesparse_graphblas/api/grb_type.py +++ b/suitesparse_graphblas/api/grb_type.py @@ -155,7 +155,10 @@ def grb_type_get_string(T, field): 'GrB_INT64' """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(T, lib.GrB_Type_get_SIZE(T[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(T, lib.GrB_Type_get_String(T[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/tests/test_api_objects.py b/suitesparse_graphblas/tests/test_api_objects.py new file mode 100644 index 0000000..bb47eab --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_objects.py @@ -0,0 +1,12 @@ +from suitesparse_graphblas import lib +from suitesparse_graphblas.api import grb_type + + +def test_grb_type_definition_longer_than_256(): + fields = "; ".join(f"double x{i}" for i in range(40)) + defn = f"typedef struct {{ {fields}; }} wide_type ;" + assert len(defn) > 256 + T = grb_type.grb_type_new_named(40 * 8, "wide_type", defn) + assert grb_type.grb_type_get_string(T, lib.GxB_JIT_C_DEFINITION) == defn + assert grb_type.grb_type_get_size(T, lib.GxB_JIT_C_DEFINITION) == len(defn) + 1 + assert grb_type.grb_type_get_string(T, lib.GxB_JIT_C_NAME) == "wide_type" diff --git a/suitesparse_graphblas/tests/test_global_options.py b/suitesparse_graphblas/tests/test_global_options.py new file mode 100644 index 0000000..1a6237c --- /dev/null +++ b/suitesparse_graphblas/tests/test_global_options.py @@ -0,0 +1,34 @@ +import pytest + +from suitesparse_graphblas import lib +from suitesparse_graphblas.api import global_options as go + + +@pytest.mark.parametrize("field", ["GxB_API_ABOUT", "GxB_LIBRARY_LICENSE"]) +def test_global_get_string_longer_than_256(field): + # Both are longer than 256 characters in every build + field = getattr(lib, field) + value = go.global_get_string(field) + assert value == go.global_option_get_char(field) + assert len(value) > 256 + assert go.global_get_size(field) == len(value.encode()) + 1 + + +def test_global_get_string_and_size(): + assert go.global_get_string(lib.GrB_NAME) == "SuiteSparse:GraphBLAS" + assert go.global_get_size(lib.GrB_NAME) == len("SuiteSparse:GraphBLAS") + 1 + + +@pytest.mark.thread_unsafe(reason="sets a global option") +def test_global_set_string(): + # The C preface goes at the top of each JIT kernel; setting it compiles nothing + old = go.global_get_string(lib.GxB_JIT_C_PREFACE) + new = "/* " + "x" * 1000 + " */" + go.global_set_string(lib.GxB_JIT_C_PREFACE, new) + try: + assert go.global_get_string(lib.GxB_JIT_C_PREFACE) == new + assert go.global_option_get_char(lib.GxB_JIT_C_PREFACE) == new + assert go.global_get_size(lib.GxB_JIT_C_PREFACE) == len(new) + 1 + finally: + go.global_set_string(lib.GxB_JIT_C_PREFACE, old) + assert go.global_get_string(lib.GxB_JIT_C_PREFACE) == old From 99f49b939b37ab360e255e1bd8d09b514c53c2f4 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:36:00 -0600 Subject: [PATCH 20/47] burble.is_enabled: return a bool, as documented The docstring shows burble.is_enabled as False and True, and it returned a bool until the update to SuiteSparse:GraphBLAS 7.4.0. That update moved it from GxB_Global_Option_get with a bool* to GxB_Global_Option_get_INT32, which returns the int32 0 or 1. The repr changed with it, to . Convert the value to a bool. The new test checks is_enabled with `is`, and checks the repr, before and after enable(). Before the fix it failed with `assert 0 is False`. --- suitesparse_graphblas/__init__.py | 2 +- suitesparse_graphblas/tests/test_burble.py | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 suitesparse_graphblas/tests/test_burble.py diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 3ea8723..7028120 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -287,7 +287,7 @@ def is_enabled(self): raise _error_code_lookup[info]( "Failed to get burble status (has GraphBLAS been initialized?" ) - return val_ptr[0] + return bool(val_ptr[0]) def enable(self): """Enable diagnostic output""" diff --git a/suitesparse_graphblas/tests/test_burble.py b/suitesparse_graphblas/tests/test_burble.py new file mode 100644 index 0000000..065b845 --- /dev/null +++ b/suitesparse_graphblas/tests/test_burble.py @@ -0,0 +1,16 @@ +import pytest + +from suitesparse_graphblas import burble + + +@pytest.mark.thread_unsafe(reason="burble is a global option") +def test_is_enabled(): + assert burble.is_enabled is False + burble.enable() + try: + assert burble.is_enabled is True + assert repr(burble) == "" + finally: + burble.disable() + assert burble.is_enabled is False + assert repr(burble) == "" From c8568d881e9c236bae8f2b312639697ddfa1d0ac Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:36:17 -0600 Subject: [PATCH 21/47] burble: fix the context-manager example and close the error messages The docstring said to write `with burble():`. burble is an instance, not the class, so that raises "TypeError: 'burble' object is not callable". `with burble:` is the form that works. The example's second line also began with ">>>" where a continuation line takes "...". Also close the parenthesis in the three "(has GraphBLAS been initialized?" error messages. --- suitesparse_graphblas/__init__.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 7028120..7bfead0 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -268,8 +268,8 @@ class burble: Example as a context manager: - >>> with burble(): - >>> n = matrix.matrix_nvals(A) + >>> with burble: + ... n = matrix.matrix_nvals(A) [ GrB_Matrix_nvals 1.91e-06 sec ] @@ -285,7 +285,7 @@ def is_enabled(self): info = lib.GxB_Global_Option_get_INT32(lib.GxB_BURBLE, val_ptr) if info != lib.GrB_SUCCESS: raise _error_code_lookup[info]( - "Failed to get burble status (has GraphBLAS been initialized?" + "Failed to get burble status (has GraphBLAS been initialized?)" ) return bool(val_ptr[0]) @@ -294,7 +294,7 @@ def enable(self): info = lib.GxB_Global_Option_set_INT32(lib.GxB_BURBLE, ffi.cast("int32_t", 1)) if info != lib.GrB_SUCCESS: raise _error_code_lookup[info]( - "Failed to enable burble (has GraphBLAS been initialized?" + "Failed to enable burble (has GraphBLAS been initialized?)" ) def disable(self): @@ -302,7 +302,7 @@ def disable(self): info = lib.GxB_Global_Option_set_INT32(lib.GxB_BURBLE, ffi.cast("int32_t", 0)) if info != lib.GrB_SUCCESS: raise _error_code_lookup[info]( - "Failed to disable burble (has GraphBLAS been initialized?" + "Failed to disable burble (has GraphBLAS been initialized?)" ) def __enter__(self): From 15092a5427244b6bb5786c5d1c2a0d619f6c6f5e Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:36:32 -0600 Subject: [PATCH 22/47] Test the global option getters and setters Each one now has a test for its error path (an invalid field raises InvalidValue). Each setter is also checked by setting a new value, reading it back through both the GxB_Global_Option and GrB_Global interfaces, and restoring the old value. GxB_HYPER_SWITCH is also checked as the default that new matrices take. Tests that change a global option are marked thread_unsafe. --- .../tests/test_global_options.py | 64 ++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_global_options.py b/suitesparse_graphblas/tests/test_global_options.py index 1a6237c..bd70f7a 100644 --- a/suitesparse_graphblas/tests/test_global_options.py +++ b/suitesparse_graphblas/tests/test_global_options.py @@ -1,8 +1,30 @@ import pytest -from suitesparse_graphblas import lib +from suitesparse_graphblas import exceptions, lib, matrix from suitesparse_graphblas.api import global_options as go +INVALID_FIELD = 999999 + + +@pytest.mark.parametrize( + "func, args", + [ + (go.global_option_get_int32, ()), + (go.global_option_set_int32, (1,)), + (go.global_option_get_fp64, ()), + (go.global_option_set_fp64, (1.0,)), + (go.global_option_get_char, ()), + (go.global_get_int32, ()), + (go.global_set_int32, (1,)), + (go.global_get_size, ()), + (go.global_get_string, ()), + (go.global_set_string, ("x",)), + ], +) +def test_invalid_field(func, args): + with pytest.raises(exceptions.InvalidValue, match="failed with info=-3"): + func(INVALID_FIELD, *args) + @pytest.mark.parametrize("field", ["GxB_API_ABOUT", "GxB_LIBRARY_LICENSE"]) def test_global_get_string_longer_than_256(field): @@ -32,3 +54,43 @@ def test_global_set_string(): finally: go.global_set_string(lib.GxB_JIT_C_PREFACE, old) assert go.global_get_string(lib.GxB_JIT_C_PREFACE) == old + + +@pytest.mark.thread_unsafe(reason="sets a global option") +def test_global_option_int32(): + old = go.global_option_get_int32(lib.GxB_PRINT_1BASED) + try: + for value in (1, 0): + go.global_option_set_int32(lib.GxB_PRINT_1BASED, value) + assert go.global_option_get_int32(lib.GxB_PRINT_1BASED) == value + # The GxB_Global_Option and GrB_Global interfaces share the setting + assert go.global_get_int32(lib.GxB_PRINT_1BASED) == value + finally: + go.global_option_set_int32(lib.GxB_PRINT_1BASED, old) + + +@pytest.mark.thread_unsafe(reason="sets a global option") +def test_global_set_int32(): + old = go.global_get_int32(lib.GxB_PRINT_1BASED) + try: + for value in (1, 0): + go.global_set_int32(lib.GxB_PRINT_1BASED, value) + assert go.global_get_int32(lib.GxB_PRINT_1BASED) == value + assert go.global_option_get_int32(lib.GxB_PRINT_1BASED) == value + finally: + go.global_set_int32(lib.GxB_PRINT_1BASED, old) + + +@pytest.mark.thread_unsafe(reason="sets a global option") +def test_global_option_fp64(): + old = go.global_option_get_fp64(lib.GxB_HYPER_SWITCH) + new = 0.25 if old != 0.25 else 0.125 + go.global_option_set_fp64(lib.GxB_HYPER_SWITCH, new) + try: + assert go.global_option_get_fp64(lib.GxB_HYPER_SWITCH) == new + # The global setting is the default for new matrices + A = matrix.matrix_new(lib.GrB_BOOL, 3, 3) + assert matrix.matrix_hyper_switch(A) == new + finally: + go.global_option_set_fp64(lib.GxB_HYPER_SWITCH, old) + assert go.global_option_get_fp64(lib.GxB_HYPER_SWITCH) == old From 642ddc335fa8ff9eeee3a96d5fd38103f3e79be8 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:38:54 -0600 Subject: [PATCH 23/47] Test libget, vararg, the type sets and the burble context manager - libget: a GrB_ name, one that falls back to GxB_, and one that exists as neither (the AttributeError names what was asked for). - vararg: values pass through variadic GxB_Matrix_Option_set/get and come back right, as a double, an int32 and pointers. On osx-arm64 this goes through the char * cast; elsewhere vararg returns its argument. - The type sets: each holds the GraphBLAS types it should, by name. - burble as a context manager: it prints diagnostics only while enabled, restores the previous state when nested, when already enabled, and when the block raises, and it unpickles as itself. Two branches in __init__.py are marked "no cover": complex_types for a build without complex types (every build uses suitesparse_graphblas.h, which has them), and the failure path of GrB_init/GxB_init, which fail only when GraphBLAS is already initialized (checked just before), on bad arguments, or out of memory. --- suitesparse_graphblas/__init__.py | 5 +- suitesparse_graphblas/tests/test_burble.py | 48 ++++++++++++- suitesparse_graphblas/tests/test_package.py | 76 ++++++++++++++++++++- 3 files changed, 125 insertions(+), 4 deletions(-) diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 7bfead0..07b317b 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -103,7 +103,8 @@ def initialize(*, blocking=False, memory_manager="numpy"): info = lib.GrB_init(blocking) else: raise ValueError(f'memory_manager argument must be "numpy" or "c"; got: {memory_manager!r}') - if info != lib.GrB_SUCCESS: + # Fails only if already initialized (checked above), on bad arguments, or out of memory + if info != lib.GrB_SUCCESS: # pragma: no cover (defensive) raise _error_code_lookup.get(info, RuntimeError)( f"Failed to initialize GraphBLAS (info={info})" ) @@ -161,7 +162,7 @@ def libget(name): lib.GxB_FC64, ) ) -else: +else: # pragma: no cover (every build uses suitesparse_graphblas.h, which has complex) complex_types = frozenset() diff --git a/suitesparse_graphblas/tests/test_burble.py b/suitesparse_graphblas/tests/test_burble.py index 065b845..d9c6b2b 100644 --- a/suitesparse_graphblas/tests/test_burble.py +++ b/suitesparse_graphblas/tests/test_burble.py @@ -1,6 +1,9 @@ +import pickle + import pytest -from suitesparse_graphblas import burble +from suitesparse_graphblas import burble, lib, matrix +from suitesparse_graphblas.api.utils import _capture_c_output @pytest.mark.thread_unsafe(reason="burble is a global option") @@ -14,3 +17,46 @@ def test_is_enabled(): burble.disable() assert burble.is_enabled is False assert repr(burble) == "" + + +@pytest.mark.thread_unsafe(reason="burble is a global option, and this captures stdout") +def test_context_manager_prints_diagnostics(): + A = matrix.matrix_new(lib.GrB_BOOL, 3, 3) + # A pending tuple, so that matrix_nvals has work to do and report + matrix.set_bool(A, True, 0, 1) + with burble as b: + assert b is burble + assert burble.is_enabled is True + out = _capture_c_output(matrix.matrix_nvals, A) + assert burble.is_enabled is False + assert "GrB_Matrix_nvals" in out + matrix.set_bool(A, True, 1, 2) + assert _capture_c_output(matrix.matrix_nvals, A) == "" + + +@pytest.mark.thread_unsafe(reason="burble is a global option") +def test_context_manager_restores_the_previous_state(): + with burble: + with burble: + assert burble.is_enabled is True + # The inner block found burble enabled, so it leaves it enabled + assert burble.is_enabled is True + assert burble.is_enabled is False + + burble.enable() + try: + with burble: + pass + assert burble.is_enabled is True + finally: + burble.disable() + + with pytest.raises(ZeroDivisionError): + with burble: + 1 / 0 + assert burble.is_enabled is False + + +def test_pickle(): + # burble is a singleton, and unpickles as itself + assert pickle.loads(pickle.dumps(burble)) is burble diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index 4fe0bb7..c997521 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -3,7 +3,23 @@ import pytest import suitesparse_graphblas -from suitesparse_graphblas import ffi, lib +from suitesparse_graphblas import ( + bool_types, + check_status, + complex_types, + ffi, + grb_types, + integer_types, + lib, + libget, + matrix, + real_types, + signed_integer_types, + supports_complex, + unsigned_integer_types, + vararg, +) +from suitesparse_graphblas.api import grb_type def test_matrix_existence(): @@ -71,3 +87,61 @@ def test_version_tracks_libgraphblas(): pytest.skip(f"development build between releases: {version}") parts = tuple(int(x) for x in version.split(".")[:3]) assert parts == suitesparse_graphblas.libgraphblas_version + + +def test_libget(): + assert libget("GrB_INP0") == lib.GrB_INP0 + assert libget("GrB_FP64") == lib.GrB_FP64 + # A GrB_ name that GraphBLAS has only as GxB_ falls back to it + assert not hasattr(lib, "GrB_HYPER_SWITCH") + assert libget("GrB_HYPER_SWITCH") == lib.GxB_HYPER_SWITCH + assert not hasattr(lib, "GrB_FC64") + assert libget("GrB_FC64") == lib.GxB_FC64 + # If neither exists, the error names what was asked for + with pytest.raises(AttributeError, match="GrB_NO_SUCH_NAME"): + libget("GrB_NO_SUCH_NAME") + + +def _type_names(types): + return {grb_type.grb_type_get_string(ffi.new("GrB_Type*", T), lib.GrB_NAME) for T in types} + + +def test_type_sets(): + assert _type_names(bool_types) == {"GrB_BOOL"} + assert _type_names(signed_integer_types) == {"GrB_INT8", "GrB_INT16", "GrB_INT32", "GrB_INT64"} + assert _type_names(unsigned_integer_types) == { + "GrB_UINT8", + "GrB_UINT16", + "GrB_UINT32", + "GrB_UINT64", + } + assert integer_types == signed_integer_types | unsigned_integer_types + assert _type_names(real_types) == {"GrB_FP32", "GrB_FP64"} + expected_complex = {"GxB_FC32", "GxB_FC64"} if supports_complex() else set() + assert _type_names(complex_types) == expected_complex + assert grb_types == bool_types | integer_types | real_types | complex_types + assert len(grb_types) == 11 + len(complex_types) + + +def test_vararg(): + # vararg makes a value safe to pass to a variadic GraphBLAS function on every + # platform: double, int32, and pointer (for the getters) + A = matrix.matrix_new(lib.GrB_FP64, 3, 3) + check_status( + A, + lib.GxB_Matrix_Option_set(A[0], lib.GxB_HYPER_SWITCH, vararg(ffi.cast("double", 0.375))), + ) + assert matrix.matrix_hyper_switch(A) == 0.375 + check_status( + A, + lib.GxB_Matrix_Option_set( + A[0], lib.GxB_SPARSITY_CONTROL, vararg(ffi.cast("int32_t", lib.GxB_BITMAP)) + ), + ) + assert matrix.matrix_sparsity_control(A) == lib.GxB_BITMAP + hyper_switch = ffi.new("double*") + check_status(A, lib.GxB_Matrix_Option_get(A[0], lib.GxB_HYPER_SWITCH, vararg(hyper_switch))) + assert hyper_switch[0] == 0.375 + sparsity = ffi.new("int32_t*") + check_status(A, lib.GxB_Matrix_Option_get(A[0], lib.GxB_SPARSITY_CONTROL, vararg(sparsity))) + assert sparsity[0] == lib.GxB_BITMAP From a17227786bb8218283028b5f0d20c1eda74c3f8a Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:39:07 -0600 Subject: [PATCH 24/47] test_initialize: check calls before initialize, and the "c" allocator The script runs in a fresh process, so it can check what happens before GraphBLAS is initialized. burble and the global option getters raise Panic, and so does container_new. An unknown memory_manager raises ValueError and leaves GraphBLAS uninitialized. It now initializes with memory_manager="C", since every pytest session already initializes with the default, "numpy". This also checks that case doesn't matter, and that NumPy's memory is then not handed to GraphBLAS without a copy. --- .../tests/test_initialize.py | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_initialize.py b/suitesparse_graphblas/tests/test_initialize.py index fbd4db7..0c8775c 100644 --- a/suitesparse_graphblas/tests/test_initialize.py +++ b/suitesparse_graphblas/tests/test_initialize.py @@ -1,10 +1,34 @@ if __name__ == "__main__": + import numpy as np import pytest import suitesparse_graphblas as ssgb + from suitesparse_graphblas import burble, exceptions, lib, utils + from suitesparse_graphblas.api import container, global_options assert ssgb.is_initialized() is False - ssgb.initialize() + + # Before initialize, GraphBLAS calls fail with GrB_PANIC + for func in (lambda: burble.is_enabled, burble.enable, burble.disable): + with pytest.raises(exceptions.Panic, match="has GraphBLAS been initialized"): + func() + with pytest.raises(exceptions.Panic, match="info=-101"): + global_options.global_option_get_int32(lib.GxB_BURBLE) + with pytest.raises(exceptions.Panic, match="info=-101"): + container.container_new() + + # An unknown memory manager is an error, and leaves GraphBLAS uninitialized + with pytest.raises(ValueError, match='"numpy" or "c"'): + ssgb.initialize(memory_manager="malloc") + assert ssgb.is_initialized() is False + + # Every pytest session initializes with the default, "numpy" (see conftest.py), so + # use the C library's allocator here, spelled in another case + ssgb.initialize(memory_manager="C") assert ssgb.is_initialized() is True + # NumPy's memory can't be handed to GraphBLAS without a copy, since GraphBLAS frees it + # with libc free + assert utils.can_unclaim_buffer(np.empty(3)) is False with pytest.raises(RuntimeError, match="GraphBLAS is already initialized"): ssgb.initialize() + assert burble.is_enabled is False From 29bada9371698e07c974e68f130b5ff9fc701d54 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:40:48 -0600 Subject: [PATCH 25/47] Test contexts, containers, descriptors, types and semirings - free=None: the handle isn't freed on collection, works until freed by hand, and is NULL afterwards. Using a freed context raises NullPointer. - Descriptors: a new descriptor's fields and name can be set and read back. A built-in descriptor's fields and name are read-only. - Types and semirings: setting and reading a name, and the errors for a number property read as a string, setting a semiring's type codes, and renaming a built-in semiring. - Contexts: an invalid field raises InvalidValue. container_free's error path is marked "no cover", since GxB_Container_free always returns GrB_SUCCESS. --- suitesparse_graphblas/api/container.py | 2 +- .../tests/test_api_objects.py | 115 +++++++++++++++++- 2 files changed, 114 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/api/container.py b/suitesparse_graphblas/api/container.py index 2418f0a..fd323b6 100644 --- a/suitesparse_graphblas/api/container.py +++ b/suitesparse_graphblas/api/container.py @@ -9,7 +9,7 @@ def container_free(c): """ info = lib.GxB_Container_free(c) - if info != lib.GrB_SUCCESS: + if info != lib.GrB_SUCCESS: # pragma: no cover (GxB_Container_free always succeeds) raise _error_code_lookup.get(info, RuntimeError)( f"GxB_Container_free failed with info={info}" ) diff --git a/suitesparse_graphblas/tests/test_api_objects.py b/suitesparse_graphblas/tests/test_api_objects.py index bb47eab..3c74fa6 100644 --- a/suitesparse_graphblas/tests/test_api_objects.py +++ b/suitesparse_graphblas/tests/test_api_objects.py @@ -1,5 +1,7 @@ -from suitesparse_graphblas import lib -from suitesparse_graphblas.api import grb_type +import pytest + +from suitesparse_graphblas import exceptions, ffi, lib +from suitesparse_graphblas.api import container, context, descriptor, grb_type, semiring def test_grb_type_definition_longer_than_256(): @@ -10,3 +12,112 @@ def test_grb_type_definition_longer_than_256(): assert grb_type.grb_type_get_string(T, lib.GxB_JIT_C_DEFINITION) == defn assert grb_type.grb_type_get_size(T, lib.GxB_JIT_C_DEFINITION) == len(defn) + 1 assert grb_type.grb_type_get_string(T, lib.GxB_JIT_C_NAME) == "wide_type" + + +# `free=None` returns a handle that isn't freed when it is garbage collected, so the caller +# frees it. Freeing sets the handle to NULL. + + +def test_context_free_none(): + ctx = context.context_new(free=None) + assert ctx[0] != ffi.NULL + context.context_set_nthreads(ctx, 3) + assert context.context_get_nthreads(ctx) == 3 + context.context_free(ctx) + assert ctx[0] == ffi.NULL + # A freed context is an error to use, not a crash + with pytest.raises(exceptions.NullPointer): + context.context_get_nthreads(ctx) + + +def test_container_free_none(): + c = container.container_new(free=None) + assert c[0] != ffi.NULL + container.container_free(c) + assert c[0] == ffi.NULL + + +def test_grb_type_free_none(): + T = grb_type.grb_type_new(16, free=None) + assert grb_type.grb_type_size(T) == 16 + grb_type.grb_type_free(T) + assert T[0] == ffi.NULL + + defn = "typedef struct { double a ; double b ; } pair_type ;" + T = grb_type.grb_type_new_named(16, "pair_type", defn, free=None) + assert grb_type.grb_type_size(T) == 16 + assert grb_type.grb_type_name(T) == "pair_type" + assert grb_type.grb_type_get_string(T, lib.GxB_JIT_C_DEFINITION) == defn + grb_type.grb_type_free(T) + assert T[0] == ffi.NULL + + +def test_semiring_free_none(): + s = semiring.semiring_new(lib.GrB_MAX_MONOID_FP64, lib.GrB_PLUS_FP64, free=None) + assert semiring.semiring_add(s) == lib.GrB_MAX_MONOID_FP64 + assert semiring.semiring_multiply(s) == lib.GrB_PLUS_FP64 + semiring.semiring_free(s) + assert s[0] == ffi.NULL + + +def test_context_invalid_field(): + ctx = context.context_new() + with pytest.raises(exceptions.InvalidValue): + context.context_set_int32(ctx, 999999, 1) + with pytest.raises(exceptions.InvalidValue): + context.context_get_fp64(ctx, 999999) + + +def test_descriptor_set_get(): + # Not a fixture: pytest-run-parallel would share it between threads + D = ffi.new("GrB_Descriptor*") + assert lib.GrB_Descriptor_new(D) == lib.GrB_SUCCESS + D = ffi.gc(D, lib.GrB_Descriptor_free) + desc = D[0] + assert descriptor.descriptor_get_int32(desc, lib.GrB_OUTP_FIELD) == lib.GrB_DEFAULT + descriptor.descriptor_set_int32(desc, lib.GrB_OUTP_FIELD, lib.GrB_REPLACE) + assert descriptor.descriptor_get_int32(desc, lib.GrB_OUTP_FIELD) == lib.GrB_REPLACE + descriptor.descriptor_set_int32(desc, lib.GrB_MASK_FIELD, lib.GrB_STRUCTURE) + assert descriptor.descriptor_get_int32(desc, lib.GrB_MASK_FIELD) == lib.GrB_STRUCTURE + + descriptor.descriptor_set_string(desc, lib.GrB_NAME, "my_descriptor") + assert descriptor.descriptor_get_string(desc, lib.GrB_NAME) == "my_descriptor" + assert descriptor.descriptor_get_size(desc, lib.GrB_NAME) == len("my_descriptor") + 1 + descriptor.descriptor_wait(desc) + + +def test_builtin_descriptor_is_read_only(): + with pytest.raises(exceptions.InvalidValue): + descriptor.descriptor_set_int32(lib.GrB_DESC_S, lib.GrB_OUTP_FIELD, lib.GrB_REPLACE) + with pytest.raises(exceptions.InvalidValue): + descriptor.descriptor_set_string(lib.GrB_DESC_S, lib.GrB_NAME, "renamed") + assert descriptor.descriptor_get_int32(lib.GrB_DESC_S, lib.GrB_OUTP_FIELD) == lib.GrB_DEFAULT + assert descriptor.descriptor_get_string(lib.GrB_DESC_S, lib.GrB_NAME) == "GrB_DESC_S" + + +def test_grb_type_name(): + T = grb_type.grb_type_new(8) + # A new type has no name until it is given one + assert grb_type.grb_type_get_string(T, lib.GrB_NAME) == "" + grb_type.grb_type_set_string(T, lib.GrB_NAME, "my_type") + assert grb_type.grb_type_get_string(T, lib.GrB_NAME) == "my_type" + assert grb_type.grb_type_get_size(T, lib.GrB_NAME) == len("my_type") + 1 + # GrB_SIZE is a number, not a string + with pytest.raises(exceptions.InvalidValue): + grb_type.grb_type_get_string(T, lib.GrB_SIZE) + + +def test_semiring_set(): + s = semiring.semiring_new(lib.GrB_MAX_MONOID_FP64, lib.GrB_PLUS_FP64) + semiring.semiring_set_string(s, lib.GrB_NAME, "max_plus") + assert semiring.semiring_get_string(s, lib.GrB_NAME) == "max_plus" + # A semiring's integer properties (its types) are read-only + code = semiring.semiring_get_int32(s, lib.GrB_INP0_TYPE_CODE) + assert code == lib.GrB_FP64_CODE + with pytest.raises(exceptions.InvalidValue): + semiring.semiring_set_int32(s, lib.GrB_INP0_TYPE_CODE, lib.GrB_INT64_CODE) + assert semiring.semiring_get_int32(s, lib.GrB_INP0_TYPE_CODE) == code + # Built-in semirings can't be renamed + builtin = ffi.new("GrB_Semiring*", lib.GrB_PLUS_TIMES_SEMIRING_INT64) + with pytest.raises(exceptions.InvalidValue): + semiring.semiring_set_string(builtin, lib.GrB_NAME, "renamed") From 5bd9a467132e08752b873c7431e9889852bb26e6 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:42:07 -0600 Subject: [PATCH 26/47] Test the BFS example against a reference BFS The doctest covered one path graph in the default mode. The new tests compare levels and parents with a plain-Python BFS on a random directed graph, from two sources, with a bool and an FP64 adjacency matrix, in all three modes (level and parent, level only, parent only). They also check that the parent is the lowest-numbered one, an isolated source, and the error when neither output is asked for. The script's __main__ block is run with runpy, with initialize stubbed out since the session has already initialized GraphBLAS, and its table is checked. --- suitesparse_graphblas/tests/test_bfs.py | 119 ++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 suitesparse_graphblas/tests/test_bfs.py diff --git a/suitesparse_graphblas/tests/test_bfs.py b/suitesparse_graphblas/tests/test_bfs.py new file mode 100644 index 0000000..93738aa --- /dev/null +++ b/suitesparse_graphblas/tests/test_bfs.py @@ -0,0 +1,119 @@ +import random +import runpy + +import pytest + +import suitesparse_graphblas +from suitesparse_graphblas import lib, matrix, vector +from suitesparse_graphblas.api.examples import bfs as bfs_module +from suitesparse_graphblas.api.examples.bfs import bfs + + +def _reference_bfs(n, edges, src): + """BFS levels, and parents chosen as bfs() does: the lowest-numbered one.""" + out = [[] for _ in range(n)] + for i, j in edges: + out[i].append(j) + level = {src: 0} + parent = {src: src} + frontier = [src] + while frontier: + reached = {} + for i in frontier: + for j in out[i]: + if j not in level: + reached[j] = min(reached.get(j, i), i) + for j, p in reached.items(): + level[j] = level[p] + 1 + parent[j] = p + frontier = list(reached) + return level, parent + + +def _to_dict(v): + indices, values = vector.vector_extract_tuples_int64(v) + return {int(i): int(x) for i, x in zip(indices, values)} + + +def _random_graph(n, nedges, T=lib.GrB_BOOL): + # Directed, with cycles, self-loops, and nodes that can't be reached from 0 + rng = random.Random(12345) + edges = {(rng.randrange(n), rng.randrange(n)) for _ in range(nedges)} + A = matrix.matrix_new(T, n, n) + for i, j in edges: + if T == lib.GrB_BOOL: + matrix.set_bool(A, True, i, j) + else: + matrix.set_fp64(A, 0.5, i, j) + return A, edges + + +@pytest.mark.parametrize("T", [lib.GrB_BOOL, lib.GrB_FP64]) +@pytest.mark.parametrize("src", [0, 45]) +def test_bfs_matches_reference(T, src): + n = 60 + A, edges = _random_graph(n, 90, T) + expected_level, expected_parent = _reference_bfs(n, edges, src) + assert 1 < len(expected_level) < n # the graph is neither trivial nor all reachable + + level, parent = bfs(A, src) + assert _to_dict(level) == expected_level + assert _to_dict(parent) == expected_parent + + level, parent = bfs(A, src, compute_parent=False) + assert parent is None + assert _to_dict(level) == expected_level + + level, parent = bfs(A, src, compute_level=False) + assert level is None + assert _to_dict(parent) == expected_parent + + +def test_bfs_lowest_parent(): + # 3 can be reached from 1 or 2; MIN_FIRST picks 1 + A = matrix.matrix_new(lib.GrB_BOOL, 4, 4) + for i, j in [(0, 2), (0, 1), (2, 3), (1, 3)]: + matrix.set_bool(A, True, i, j) + level, parent = bfs(A, 0) + assert _to_dict(level) == {0: 0, 1: 1, 2: 1, 3: 2} + assert _to_dict(parent) == {0: 0, 1: 0, 2: 0, 3: 1} + + +def test_bfs_isolated_source(): + A = matrix.matrix_new(lib.GrB_BOOL, 3, 3) + matrix.set_bool(A, True, 1, 2) + level, parent = bfs(A, 0) + assert _to_dict(level) == {0: 0} + assert _to_dict(parent) == {0: 0} + assert vector.vector_size(level) == vector.vector_size(parent) == 3 + + +def test_bfs_needs_an_output(): + A = matrix.matrix_new(lib.GrB_BOOL, 3, 3) + with pytest.raises(ValueError, match="at least one"): + bfs(A, 0, compute_level=False, compute_parent=False) + + +@pytest.mark.thread_unsafe(reason="patches suitesparse_graphblas.initialize and captures stdout") +def test_bfs_script(monkeypatch, capsys): + # The script initializes GraphBLAS, which this session already did + monkeypatch.setattr(suitesparse_graphblas, "initialize", lambda: None) + runpy.run_path(bfs_module.__file__, run_name="__main__") + lines = capsys.readouterr().out.splitlines() + assert lines[0] == "BFS from node 0:" + assert lines[1].split() == ["node", "level", "parent"] + rows = [tuple(int(x) for x in line.split()) for line in lines[2:]] + # 0 --- 1 --- 2 + # | | + # 3 4 --- 5 + # | + # 6 + assert rows == [ + (0, 0, 0), + (1, 1, 0), + (2, 2, 1), + (3, 1, 0), + (4, 2, 1), + (5, 3, 4), + (6, 3, 4), + ] From 2b0cf6cc084ba6a35204628eb8f334c98111697e Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:43:08 -0600 Subject: [PATCH 27/47] test_io: really write and read full matrices in the binfile test The test meant to fill every entry when it asks for GxB_FULL, but it compared the type with the sparsity constant (`T is not lib.GxB_FULL`), which is always true. So every matrix got the same single entry, and GraphBLAS can't make a 2x2 matrix with one entry full: binwrite never wrote FULLR or FULLC, and binread never read them. The branch it skipped called lib.GrB_assign, which cffi doesn't have, since GrB_assign is a C _Generic macro. Test the sparsity, and fill every entry with the type's element setter. Also check that A has the requested format before writing it, and that B has it after reading it back, so that a test that writes the wrong format can't pass again. --- suitesparse_graphblas/tests/test_io.py | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 65ebe25..1922321 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -152,28 +152,18 @@ def test_matrix_binfile_read_write(tmp_path): for sparsity in (lib.GxB_HYPERSPARSE, lib.GxB_SPARSE, lib.GxB_BITMAP, lib.GxB_FULL): A = matrix.matrix_new(T, 2, 2) - if T is not lib.GxB_FULL: + if sparsity == lib.GxB_FULL: + # A matrix can only be full if it has a value everywhere + values = _test_elements(T)[0] + for k, (i, j) in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]): + check_status(A, _element_setters[T](A[0], values[k % 2], i, j)) + else: for args in zip(*_test_elements(T)): f = _element_setters[T] check_status(A, f(A[0], *args)) - else: - Tone = _test_elements(T)[0][0] - check_status( - A[0], - lib.GrB_assign( - A, - NULL, - NULL, - Tone, - lib.GrB_ALL, - 0, - lib.GrB_ALL, - 0, - NULL, - ), - ) matrix.matrix_set_sparsity_control(A, sparsity) matrix.matrix_set_format(A, format) + assert matrix.matrix_sparsity_status(A) == sparsity binfilef = tmp_path / "binfilewrite_test.binfile" binary.binwrite(A, binfilef, opener=opener) @@ -185,6 +175,8 @@ def test_matrix_binfile_read_write(tmp_path): assert matrix.matrix_hyper_switch(A) == matrix.matrix_hyper_switch(B) assert matrix.matrix_bitmap_switch(A) == matrix.matrix_bitmap_switch(B) # assert matrix.matrix_sparsity_control(A) == matrix.matrix_sparsity_control(B) + assert matrix.matrix_sparsity_status(B) == sparsity + assert matrix.matrix_format(B) == format C = matrix.matrix_new(lib.GrB_BOOL, 2, 2) From 1e130df79bff072c281afc7b8a6bd745fe6cf904 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:48:44 -0600 Subject: [PATCH 28/47] _capture_c_output: restore stdout if the call raises, and close fds The doctest helper never closed its duplicate of fd 1, so it leaked one file descriptor per call. If the call raised, fd 1 stayed pointed at the pipe for the rest of the process, so later output went into a pipe that nothing read, and the process would block once the pipe filled. A failing print doctest would then hide its own failure, and could hang the test run. Restore fd 1 and close every descriptor in finally blocks. The new tests capture a context's print three times and print a freed context (which raises NullPointer), and check that fd 1 is the same file afterwards and that the next free descriptors haven't changed. Before the fix the first test failed with [11, 12, 16, ...] == [11, 12, 13, ...], and the second found fd 1 still pointing at the pipe. --- suitesparse_graphblas/api/utils.py | 18 +++++--- suitesparse_graphblas/tests/test_api_utils.py | 45 +++++++++++++++++++ 2 files changed, 56 insertions(+), 7 deletions(-) create mode 100644 suitesparse_graphblas/tests/test_api_utils.py diff --git a/suitesparse_graphblas/api/utils.py b/suitesparse_graphblas/api/utils.py index df5d3eb..1d50911 100644 --- a/suitesparse_graphblas/api/utils.py +++ b/suitesparse_graphblas/api/utils.py @@ -7,10 +7,14 @@ def _capture_c_output(fn, *args): sys.stdout.flush() r, w = os.pipe() old = os.dup(1) - os.dup2(w, 1) - fn(*args) - os.dup2(old, 1) - os.close(w) - out = os.read(r, 100000).decode() - os.close(r) - return out + try: + os.dup2(w, 1) + try: + fn(*args) + finally: + os.dup2(old, 1) + os.close(w) + return os.read(r, 100000).decode() + finally: + os.close(old) + os.close(r) diff --git a/suitesparse_graphblas/tests/test_api_utils.py b/suitesparse_graphblas/tests/test_api_utils.py new file mode 100644 index 0000000..10c89d7 --- /dev/null +++ b/suitesparse_graphblas/tests/test_api_utils.py @@ -0,0 +1,45 @@ +import os + +import pytest + +from suitesparse_graphblas import exceptions, ffi, lib +from suitesparse_graphblas.api import context +from suitesparse_graphblas.api.utils import _capture_c_output + + +def _free_fds(): + # New file descriptors take the lowest free numbers, so these change if one leaks + fds = [os.dup(1) for _ in range(8)] + for fd in fds: + os.close(fd) + return fds + + +def _stdout_id(): + st = os.fstat(1) + return st.st_dev, st.st_ino + + +@pytest.mark.thread_unsafe(reason="redirects file descriptor 1") +def test_capture_c_output(): + ctx = context.context_new() + fds = _free_fds() + stdout = _stdout_id() + for _ in range(3): + out = _capture_c_output(context.context_print, ctx, "my_ctx", lib.GxB_SHORT) + assert "my_ctx" in out + assert _stdout_id() == stdout + assert _free_fds() == fds + + +@pytest.mark.thread_unsafe(reason="redirects file descriptor 1") +def test_capture_c_output_restores_stdout_on_error(): + ctx = context.context_new(free=None) + context.context_free(ctx) + fds = _free_fds() + stdout = _stdout_id() + with pytest.raises(exceptions.NullPointer): + _capture_c_output(context.context_print, ctx) + assert ctx[0] == ffi.NULL + assert _stdout_id() == stdout + assert _free_fds() == fds From f334c88c0b28b2d17ea19c5c72d0ef29261a343d Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:52:16 -0600 Subject: [PATCH 29/47] test_io: check the sparsity control again in the binfile round trip The assertion was commented out because binwrite reset the matrix's sparsity control when it packed the matrix back. binwrite now restores it, so the round trip keeps it. --- suitesparse_graphblas/tests/test_io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 1922321..b6bd660 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -174,7 +174,7 @@ def test_matrix_binfile_read_write(tmp_path): assert matrix.matrix_ncols(A) == matrix.matrix_ncols(B) assert matrix.matrix_hyper_switch(A) == matrix.matrix_hyper_switch(B) assert matrix.matrix_bitmap_switch(A) == matrix.matrix_bitmap_switch(B) - # assert matrix.matrix_sparsity_control(A) == matrix.matrix_sparsity_control(B) + assert matrix.matrix_sparsity_control(A) == matrix.matrix_sparsity_control(B) assert matrix.matrix_sparsity_status(B) == sparsity assert matrix.matrix_format(B) == format From a50ada24749f9e4d0c111b14e1ce109bb62c5772 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:53:31 -0600 Subject: [PATCH 30/47] Size string buffers from get_SIZE in descriptor and semiring get_string descriptor_get_string and semiring_get_string read into ffi.new("char[256]"), but GrB_Descriptor_get_String and GrB_Semiring_get_String strcpy the whole string into the caller's buffer. A name set with GrB_NAME has no length limit (GB_user_name_set allocates strlen + 1; GxB_MAX_NAME_LEN bounds only the JIT C name), so a name longer than 255 characters overran the buffer and came back cut at 256 characters. Ask GraphBLAS for the size first, as global_get_string and grb_type_get_string now do. The new tests set a 1000-character name on a descriptor and on a semiring and read it back. Before the fix both came back as the first 256 characters. One change follows from GraphBLAS itself: GrB_Descriptor_get_String returns the name whatever the field, but GrB_Descriptor_get_SIZE accepts only GrB_NAME. So descriptor_get_string now raises InvalidValue for any other field, as the other string getters do, instead of returning the name. --- suitesparse_graphblas/api/descriptor.py | 5 +++- suitesparse_graphblas/api/semiring.py | 5 +++- .../tests/test_api_objects.py | 25 +++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/suitesparse_graphblas/api/descriptor.py b/suitesparse_graphblas/api/descriptor.py index 308a071..9b57de8 100644 --- a/suitesparse_graphblas/api/descriptor.py +++ b/suitesparse_graphblas/api/descriptor.py @@ -111,7 +111,10 @@ def descriptor_get_string(desc, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(desc, lib.GrB_Descriptor_get_SIZE(desc, size, field)) + val = ffi.new("char[]", size[0]) check_status(desc, lib.GrB_Descriptor_get_String(desc, val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/api/semiring.py b/suitesparse_graphblas/api/semiring.py index e942c3c..328e342 100644 --- a/suitesparse_graphblas/api/semiring.py +++ b/suitesparse_graphblas/api/semiring.py @@ -147,7 +147,10 @@ def semiring_get_string(s, field): True """ - val = ffi.new("char[256]") + # GraphBLAS copies the whole string, so make room for all of it + size = ffi.new("size_t*") + check_status(s, lib.GrB_Semiring_get_SIZE(s[0], size, field)) + val = ffi.new("char[]", size[0]) check_status(s, lib.GrB_Semiring_get_String(s[0], val, field)) return ffi.string(val).decode() diff --git a/suitesparse_graphblas/tests/test_api_objects.py b/suitesparse_graphblas/tests/test_api_objects.py index 3c74fa6..3aec30d 100644 --- a/suitesparse_graphblas/tests/test_api_objects.py +++ b/suitesparse_graphblas/tests/test_api_objects.py @@ -121,3 +121,28 @@ def test_semiring_set(): builtin = ffi.new("GrB_Semiring*", lib.GrB_PLUS_TIMES_SEMIRING_INT64) with pytest.raises(exceptions.InvalidValue): semiring.semiring_set_string(builtin, lib.GrB_NAME, "renamed") + + +# GraphBLAS doesn't limit the length of a name set with GrB_NAME + + +def test_descriptor_name_longer_than_256(): + D = ffi.new("GrB_Descriptor*") + assert lib.GrB_Descriptor_new(D) == lib.GrB_SUCCESS + D = ffi.gc(D, lib.GrB_Descriptor_free) + name = "d" * 1000 + descriptor.descriptor_set_string(D[0], lib.GrB_NAME, name) + assert descriptor.descriptor_get_string(D[0], lib.GrB_NAME) == name + assert descriptor.descriptor_get_size(D[0], lib.GrB_NAME) == len(name) + 1 + # GrB_NAME is a descriptor's only string. (GrB_Descriptor_get_String itself returns the + # name for any field, but GrB_Descriptor_get_SIZE rejects the others.) + with pytest.raises(exceptions.InvalidValue): + descriptor.descriptor_get_string(D[0], lib.GrB_OUTP_FIELD) + + +def test_semiring_name_longer_than_256(): + s = semiring.semiring_new(lib.GrB_MAX_MONOID_FP64, lib.GrB_PLUS_FP64) + name = "s" * 1000 + semiring.semiring_set_string(s, lib.GrB_NAME, name) + assert semiring.semiring_get_string(s, lib.GrB_NAME) == name + assert semiring.semiring_get_size(s, lib.GrB_NAME) == len(name) + 1 From fdacccf800997ada3c17870ad5a38eb165bc32e7 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 13:56:49 -0600 Subject: [PATCH 31/47] _capture_c_output: return "" for no output on Pyodide Emscripten's pipes don't report end-of-file. Once the write end is closed, reading an empty pipe raises BlockingIOError (EAGAIN) instead of returning b"", even though the read end is blocking. So on Pyodide, _capture_c_output raised whenever the call printed nothing. The existing doctests always print something, so none of them hit it. Treat BlockingIOError from the read as no output. The new test captures a call that prints nothing. On Pyodide 314.0.7 it failed with "BlockingIOError: [Errno 6] Resource temporarily unavailable" before the fix, and so did the burble test that checks that nothing is printed while burble is off. Elsewhere the read returns b"" as before, so the new branch is marked "no cover". --- suitesparse_graphblas/api/utils.py | 5 ++++- suitesparse_graphblas/tests/test_api_utils.py | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/api/utils.py b/suitesparse_graphblas/api/utils.py index 1d50911..d23ae3a 100644 --- a/suitesparse_graphblas/api/utils.py +++ b/suitesparse_graphblas/api/utils.py @@ -14,7 +14,10 @@ def _capture_c_output(fn, *args): finally: os.dup2(old, 1) os.close(w) - return os.read(r, 100000).decode() + try: + return os.read(r, 100000).decode() + except BlockingIOError: # pragma: no cover (Emscripten: an empty pipe has no EOF) + return "" finally: os.close(old) os.close(r) diff --git a/suitesparse_graphblas/tests/test_api_utils.py b/suitesparse_graphblas/tests/test_api_utils.py index 10c89d7..cb23d91 100644 --- a/suitesparse_graphblas/tests/test_api_utils.py +++ b/suitesparse_graphblas/tests/test_api_utils.py @@ -43,3 +43,10 @@ def test_capture_c_output_restores_stdout_on_error(): assert ctx[0] == ffi.NULL assert _stdout_id() == stdout assert _free_fds() == fds + + +@pytest.mark.thread_unsafe(reason="redirects file descriptor 1") +def test_capture_c_output_of_nothing(): + fds = _free_fds() + assert _capture_c_output(lambda: None) == "" + assert _free_fds() == fds From 317dc0214187551e77b811cd66d5c328bfb23735 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 14:00:28 -0600 Subject: [PATCH 32/47] _capture_c_output: close the pipe if redirecting stdout fails If os.dup2(w, 1) raised, the write end of the pipe was never closed: only the inner finally closed it, and that runs only once the redirect has worked. --- suitesparse_graphblas/api/utils.py | 8 +++++--- suitesparse_graphblas/tests/test_api_utils.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/api/utils.py b/suitesparse_graphblas/api/utils.py index d23ae3a..cbcaaeb 100644 --- a/suitesparse_graphblas/api/utils.py +++ b/suitesparse_graphblas/api/utils.py @@ -8,11 +8,13 @@ def _capture_c_output(fn, *args): r, w = os.pipe() old = os.dup(1) try: - os.dup2(w, 1) try: - fn(*args) + os.dup2(w, 1) + try: + fn(*args) + finally: + os.dup2(old, 1) finally: - os.dup2(old, 1) os.close(w) try: return os.read(r, 100000).decode() diff --git a/suitesparse_graphblas/tests/test_api_utils.py b/suitesparse_graphblas/tests/test_api_utils.py index cb23d91..81c6d7d 100644 --- a/suitesparse_graphblas/tests/test_api_utils.py +++ b/suitesparse_graphblas/tests/test_api_utils.py @@ -50,3 +50,18 @@ def test_capture_c_output_of_nothing(): fds = _free_fds() assert _capture_c_output(lambda: None) == "" assert _free_fds() == fds + + +@pytest.mark.thread_unsafe(reason="patches os.dup2") +def test_capture_c_output_closes_fds_when_redirecting_fails(monkeypatch): + def failing_dup2(fd, fd2): + raise OSError("dup2 failed") + + fds = _free_fds() + stdout = _stdout_id() + monkeypatch.setattr(os, "dup2", failing_dup2) + with pytest.raises(OSError, match="dup2 failed"): + _capture_c_output(lambda: None) + monkeypatch.undo() + assert _stdout_id() == stdout + assert _free_fds() == fds From 07b86144456c4c45ba23465e2fc5d0b98214fc37 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 14:00:31 -0600 Subject: [PATCH 33/47] global_get_string: name the call that failed The size is asked for first now, so an invalid field fails in GrB_Global_get_SIZE, but the message still said GrB_Global_get_String. --- suitesparse_graphblas/api/global_options.py | 6 +++--- suitesparse_graphblas/tests/test_global_options.py | 6 ++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/api/global_options.py b/suitesparse_graphblas/api/global_options.py index 03ddf15..ab0998b 100644 --- a/suitesparse_graphblas/api/global_options.py +++ b/suitesparse_graphblas/api/global_options.py @@ -131,14 +131,14 @@ def global_get_string(field): """ # GraphBLAS copies the whole string, so make room for all of it size = ffi.new("size_t*") + call = "GrB_Global_get_SIZE" info = lib.GrB_Global_get_SIZE(lib.GrB_GLOBAL, size, field) if info == lib.GrB_SUCCESS: val = ffi.new("char[]", size[0]) + call = "GrB_Global_get_String" info = lib.GrB_Global_get_String(lib.GrB_GLOBAL, val, field) if info != lib.GrB_SUCCESS: - raise _error_code_lookup.get(info, RuntimeError)( - f"GrB_Global_get_String failed with info={info}" - ) + raise _error_code_lookup.get(info, RuntimeError)(f"{call} failed with info={info}") return ffi.string(val).decode() diff --git a/suitesparse_graphblas/tests/test_global_options.py b/suitesparse_graphblas/tests/test_global_options.py index bd70f7a..04b3507 100644 --- a/suitesparse_graphblas/tests/test_global_options.py +++ b/suitesparse_graphblas/tests/test_global_options.py @@ -26,6 +26,12 @@ def test_invalid_field(func, args): func(INVALID_FIELD, *args) +def test_global_get_string_names_the_call_that_failed(): + # The size is asked for first, so an invalid field fails there + with pytest.raises(exceptions.InvalidValue, match="^GrB_Global_get_SIZE failed with"): + go.global_get_string(INVALID_FIELD) + + @pytest.mark.parametrize("field", ["GxB_API_ABOUT", "GxB_LIBRARY_LICENSE"]) def test_global_get_string_longer_than_256(field): # Both are longer than 256 characters in every build From b026b0aadd16a671a5a9e984c45f11b1829a553d Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 14:00:35 -0600 Subject: [PATCH 34/47] burble: raise GraphBLASException for codes it has no class for check_status already falls back to GraphBLASException. The three burble methods still indexed _error_code_lookup directly, so a code with no class raised KeyError. --- suitesparse_graphblas/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 07b317b..9a64557 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -285,7 +285,7 @@ def is_enabled(self): val_ptr = ffi.new("int32_t*") info = lib.GxB_Global_Option_get_INT32(lib.GxB_BURBLE, val_ptr) if info != lib.GrB_SUCCESS: - raise _error_code_lookup[info]( + raise _error_code_lookup.get(info, ex.GraphBLASException)( "Failed to get burble status (has GraphBLAS been initialized?)" ) return bool(val_ptr[0]) @@ -294,7 +294,7 @@ def enable(self): """Enable diagnostic output""" info = lib.GxB_Global_Option_set_INT32(lib.GxB_BURBLE, ffi.cast("int32_t", 1)) if info != lib.GrB_SUCCESS: - raise _error_code_lookup[info]( + raise _error_code_lookup.get(info, ex.GraphBLASException)( "Failed to enable burble (has GraphBLAS been initialized?)" ) @@ -302,7 +302,7 @@ def disable(self): """Disable diagnostic output""" info = lib.GxB_Global_Option_set_INT32(lib.GxB_BURBLE, ffi.cast("int32_t", 0)) if info != lib.GrB_SUCCESS: - raise _error_code_lookup[info]( + raise _error_code_lookup.get(info, ex.GraphBLASException)( "Failed to disable burble (has GraphBLAS been initialized?)" ) From c4f61510c2e25988ac464eeb3315041414474294 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 14:01:17 -0600 Subject: [PATCH 35/47] test_api_objects: say what GrB_Descriptor_get_String returns for other fields It ignores the field and returns the name, which is "" when none is set, not the name in every case. --- suitesparse_graphblas/tests/test_api_objects.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/suitesparse_graphblas/tests/test_api_objects.py b/suitesparse_graphblas/tests/test_api_objects.py index 3aec30d..4316ecc 100644 --- a/suitesparse_graphblas/tests/test_api_objects.py +++ b/suitesparse_graphblas/tests/test_api_objects.py @@ -134,8 +134,9 @@ def test_descriptor_name_longer_than_256(): descriptor.descriptor_set_string(D[0], lib.GrB_NAME, name) assert descriptor.descriptor_get_string(D[0], lib.GrB_NAME) == name assert descriptor.descriptor_get_size(D[0], lib.GrB_NAME) == len(name) + 1 - # GrB_NAME is a descriptor's only string. (GrB_Descriptor_get_String itself returns the - # name for any field, but GrB_Descriptor_get_SIZE rejects the others.) + # GrB_NAME is a descriptor's only string. (GrB_Descriptor_get_String itself ignores the + # field and returns the name, or "" when none is set, but GrB_Descriptor_get_SIZE rejects + # every field but GrB_NAME.) with pytest.raises(exceptions.InvalidValue): descriptor.descriptor_get_string(D[0], lib.GrB_OUTP_FIELD) From 28564de66e8800ee98f9213c7cb226fb507def11 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 14:23:34 -0600 Subject: [PATCH 36/47] test_vararg: expect failure with conda-forge's cffi on macOS arm64 CI's macOS jobs (conda-forge, arm64) failed it: the double set through vararg read back as 0.0. conda-forge's cffi links conda's libffi, and through it a variadic call on macOS arm64 loses its variadic arguments, with or without vararg: an int32 setting doesn't change either (reproduced with cffi 2.0.0 and libffi 3.5.2). PyPI's cffi links the system libffi, and the test passes with it (cffi 2.0.0 and 2.1.1), so the wheel jobs still run it for real. --- suitesparse_graphblas/tests/test_package.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index c997521..2b0ee63 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -1,3 +1,4 @@ +import os import sys import pytest @@ -123,6 +124,20 @@ def test_type_sets(): assert len(grb_types) == 11 + len(complex_types) +# conda-forge's cffi links conda's libffi, and through it a variadic call on macOS arm64 loses +# its variadic arguments, with or without vararg: a double arrives as 0.0 and an int32 setting +# doesn't change (cffi 2.0.0, libffi 3.5.2). PyPI's cffi links the system libffi and works. +_conda_on_osx_arm64 = ( + sys.platform == "darwin" + and suitesparse_graphblas._is_osx_arm64 + and os.path.isdir(os.path.join(sys.prefix, "conda-meta")) +) + + +@pytest.mark.xfail( + _conda_on_osx_arm64, + reason="variadic calls lose their arguments with conda-forge's cffi on macOS arm64", +) def test_vararg(): # vararg makes a value safe to pass to a variadic GraphBLAS function on every # platform: double, int32, and pointer (for the getters) From 0c560f00f1f6d9a18bf1f40dee63dfe9ef0ec7d0 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 14:45:38 -0600 Subject: [PATCH 37/47] Mark the complex-type checks in scalar and iterator as no branch As in matrix, vector and monoid: the build always declares the complex types, so supports_complex() is never false and its false branch only shows as a partial. --- suitesparse_graphblas/api/iterator.py | 2 +- suitesparse_graphblas/api/scalar.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/suitesparse_graphblas/api/iterator.py b/suitesparse_graphblas/api/iterator.py index 9382707..7ccfd74 100644 --- a/suitesparse_graphblas/api/iterator.py +++ b/suitesparse_graphblas/api/iterator.py @@ -616,7 +616,7 @@ def iterator_get_fp64(it): return lib.GxB_Iterator_get_FP64(it[0]) -if supports_complex(): +if supports_complex(): # pragma: no branch (the build always declares complex types) def iterator_get_fc32(it): """Get the current fc32 value from the iterator.""" diff --git a/suitesparse_graphblas/api/scalar.py b/suitesparse_graphblas/api/scalar.py index f4537a3..3e66f33 100644 --- a/suitesparse_graphblas/api/scalar.py +++ b/suitesparse_graphblas/api/scalar.py @@ -449,7 +449,7 @@ def get_fp64(s): return value[0] -if supports_complex(): +if supports_complex(): # pragma: no branch (the build always declares complex types) def set_fc32(s, value): """Set an fc32 value to the scalar. From db43846a2e5f6470285f86fa103f7167ee34d9b1 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:00:02 -0600 Subject: [PATCH 38/47] Add AlreadySet, GpuError and OutputIsReadonly exceptions check_status had no class for GrB_ALREADY_SET, GxB_GPU_ERROR or GxB_OUTPUT_IS_READONLY, so they raised the GraphBLASException base class. Give each its own subclass, as for every other GrB_Info code: - GrB_ALREADY_SET: GrB_NAME of a type, operator, monoid or semiring, or a JIT C name or definition, set a second time. - GxB_OUTPUT_IS_READONLY: writing to an object whose memory is read-only, such as a vector loaded with GxB_IS_READONLY. - GxB_GPU_ERROR: CUDA builds. A code a newer GraphBLAS adds still falls back to GraphBLASException, and the test of every GrB_Info code now fails until such a code has a class. --- suitesparse_graphblas/__init__.py | 3 ++ suitesparse_graphblas/exceptions.py | 12 +++++ .../tests/test_exceptions.py | 47 +++++++++++++++++-- 3 files changed, 57 insertions(+), 5 deletions(-) diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 9a64557..668635d 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -188,9 +188,12 @@ def libget(name): lib.GrB_INDEX_OUT_OF_BOUNDS: ex.IndexOutOfBound, lib.GrB_PANIC: ex.Panic, lib.GrB_NOT_IMPLEMENTED: ex.NotImplementedException, + lib.GrB_ALREADY_SET: ex.AlreadySet, # GxB Errors lib.GxB_EXHAUSTED: StopIteration, lib.GxB_JIT_ERROR: ex.JitError, + lib.GxB_GPU_ERROR: ex.GpuError, + lib.GxB_OUTPUT_IS_READONLY: ex.OutputIsReadonly, } GrB_SUCCESS = lib.GrB_SUCCESS GrB_NO_VALUE = lib.GrB_NO_VALUE diff --git a/suitesparse_graphblas/exceptions.py b/suitesparse_graphblas/exceptions.py index 3761228..a4d69cb 100644 --- a/suitesparse_graphblas/exceptions.py +++ b/suitesparse_graphblas/exceptions.py @@ -64,3 +64,15 @@ class NotImplementedException(GraphBLASException): class JitError(GraphBLASException): pass + + +class AlreadySet(GraphBLASException): + pass + + +class GpuError(GraphBLASException): + pass + + +class OutputIsReadonly(GraphBLASException): + pass diff --git a/suitesparse_graphblas/tests/test_exceptions.py b/suitesparse_graphblas/tests/test_exceptions.py index 05c27bd..fb33a9e 100644 --- a/suitesparse_graphblas/tests/test_exceptions.py +++ b/suitesparse_graphblas/tests/test_exceptions.py @@ -1,6 +1,6 @@ import pytest -from suitesparse_graphblas import check_status, exceptions, ffi, lib +from suitesparse_graphblas import _error_code_lookup, check_status, exceptions, ffi, lib from suitesparse_graphblas.api import grb_type @@ -30,25 +30,62 @@ def test_check_status_success_and_no_value(): @pytest.mark.parametrize("name", _error_names) def test_check_status_raises_for_every_error_code(name): - # Every GrB_Info that GraphBLAS can return, so a code added by a new - # GraphBLAS can't escape as a KeyError + # Every GrB_Info that GraphBLAS can return has its own exception class. + # This fails when a new GraphBLAS adds a code, as a reminder to add one. info = getattr(lib, name) + assert info in _error_code_lookup + expected = _error_code_lookup[info] + assert expected is StopIteration or ( + issubclass(expected, exceptions.GraphBLASException) + and expected is not exceptions.GraphBLASException + ) A = ffi.new("GrB_Matrix*") check_status(A, lib.GrB_Matrix_new(A, lib.GrB_BOOL, 2, 2)) - expected = StopIteration if info == lib.GxB_EXHAUSTED else exceptions.GraphBLASException with pytest.raises(expected): check_status(A, info) +def test_check_status_unknown_code(): + # A code that this build doesn't know raises the base class, not KeyError + A = ffi.new("GrB_Matrix*") + check_status(A, lib.GrB_Matrix_new(A, lib.GrB_BOOL, 2, 2)) + unknown = -12345 + assert unknown not in _error_code_lookup + with pytest.raises(exceptions.GraphBLASException) as excinfo: + check_status(A, unknown) + assert type(excinfo.value) is exceptions.GraphBLASException + + def test_check_status_already_set(): # GraphBLAS returns GrB_ALREADY_SET when the name of an object is set twice T = grb_type.grb_type_new(8) grb_type.grb_type_set_string(T, lib.GrB_NAME, "first_name") - with pytest.raises(exceptions.GraphBLASException): + with pytest.raises(exceptions.AlreadySet): grb_type.grb_type_set_string(T, lib.GrB_NAME, "second_name") assert grb_type.grb_type_get_string(T, lib.GrB_NAME) == "first_name" +def test_check_status_output_is_readonly(): + # A vector loaded with GxB_IS_READONLY borrows the buffer, so GraphBLAS + # refuses to write to it with GxB_OUTPUT_IS_READONLY + v = ffi.new("GrB_Vector*") + check_status(v, lib.GrB_Vector_new(v, lib.GrB_INT64, 0)) + buf = ffi.new("int64_t[4]", [1, 2, 3, 4]) + X = ffi.new("void**", buf) + try: + check_status( + v, + lib.GxB_Vector_load( + v[0], X, lib.GrB_INT64, 4, ffi.sizeof(buf), lib.GxB_IS_READONLY, ffi.NULL + ), + ) + with pytest.raises(exceptions.OutputIsReadonly): + check_status(v, lib.GrB_Vector_setElement_INT64(v[0], 9, 0)) + assert list(buf) == [1, 2, 3, 4] + finally: + check_status(v, lib.GrB_Vector_free(v)) + + def test_check_status_unknown_object(): # The error string is looked up by the type of the object, so an object # that isn't a GraphBLAS handle is a TypeError, not a crash From a9bec7e657a81f98b5299ab0561661d34bf783ae Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:05:33 -0600 Subject: [PATCH 39/47] Test that every object type with an error function is in check_status's table check_status looks up the object's *_error function by its C type to get GraphBLAS's error string. An object type missing from _error_func_lookup raises TypeError instead of the GraphBLAS exception. Derive the expected types from the signatures of every *_error function the build declares, so a new object type in a newer GraphBLAS fails the test. --- .../tests/test_exceptions.py | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_exceptions.py b/suitesparse_graphblas/tests/test_exceptions.py index fb33a9e..477ac39 100644 --- a/suitesparse_graphblas/tests/test_exceptions.py +++ b/suitesparse_graphblas/tests/test_exceptions.py @@ -1,6 +1,13 @@ import pytest -from suitesparse_graphblas import _error_code_lookup, check_status, exceptions, ffi, lib +from suitesparse_graphblas import ( + _error_code_lookup, + _error_func_lookup, + check_status, + exceptions, + ffi, + lib, +) from suitesparse_graphblas.api import grb_type @@ -86,6 +93,17 @@ def test_check_status_output_is_readonly(): check_status(v, lib.GrB_Vector_free(v)) +def test_error_func_lookup_has_every_object_type(): + # check_status gets the error string with the object's *_error function. + # Every *_error function's object type must be in the table, or a new + # GraphBLAS object type would raise TypeError instead of its error. + error_funcs = [name for name in dir(lib) if name.endswith("_error")] + assert error_funcs + for name in error_funcs: + cname = ffi.typeof(getattr(lib, name)).args[1].cname + assert cname in _error_func_lookup, name + + def test_check_status_unknown_object(): # The error string is looked up by the type of the object, so an object # that isn't a GraphBLAS handle is a TypeError, not a crash From 748fd38a9878b9045cec191ec042cd49462d5a29 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:01:21 -0600 Subject: [PATCH 40/47] Add SUITESPARSE_GRAPHBLAS_NO_COMPLEX to build without complex types The package has code for builds without complex types (supports_complex() and its `if supports_complex():` blocks), but nothing has built that way since the MSVC build switched to _Fcomplex and _Dcomplex, so none of it is tested. SuiteSparse:GraphBLAS can't be built without complex types: its CMake stops if the compiler has neither C99 nor MSVC complex numbers, and GraphBLAS.h has an #error for that case (GxB_NO_FC32 and GxB_NO_FC64 only drop factory kernels). So leave them out on this side instead: with the variable set, cffi declares suitesparse_graphblas_no_complex.h, which create_headers.py keeps current, instead of suitesparse_graphblas.h, and links the same library. --- build_graphblas_cffi.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/build_graphblas_cffi.py b/build_graphblas_cffi.py index 94594e6..8c45d9c 100644 --- a/build_graphblas_cffi.py +++ b/build_graphblas_cffi.py @@ -49,7 +49,12 @@ library_dirs=library_dirs, ) -ffibuilder.cdef((ss_g / "suitesparse_graphblas.h").read_text()) +# SUITESPARSE_GRAPHBLAS_NO_COMPLEX=1 leaves out the complex types and functions, so that CI +# can test the package without them. +header = "suitesparse_graphblas.h" +if os.environ.get("SUITESPARSE_GRAPHBLAS_NO_COMPLEX"): + header = "suitesparse_graphblas_no_complex.h" +ffibuilder.cdef((ss_g / header).read_text()) def get_extension(apply_msvc_patch: bool = None, extra_compile_args=()): From 25790e996f5e5dd39e98a87234fbc4559cec5bc2 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:01:24 -0600 Subject: [PATCH 41/47] binary: import without complex types _ss_typecodes and _ss_typenames used lib.GxB_FC32 and lib.GxB_FC64 unconditionally, so in a build without complex types, importing suitesparse_graphblas.io raised AttributeError. Built with SUITESPARSE_GRAPHBLAS_NO_COMPLEX=1, pytest failed to collect test_io.py, io/__init__.py and binary.py: AttributeError: cffi library 'suitesparse_graphblas._graphblas' has no function, constant or global variable named 'GxB_FC32' Add the complex entries only if supports_complex(), as the rest of the package does. test_io.py now runs in that build, including the binwrite/binread round trip of every type in grb_types. --- suitesparse_graphblas/api/io/binary.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 71291e8..8ffe9cb 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -3,7 +3,7 @@ import numpy as np -from suitesparse_graphblas import __version__, check_status, ffi, lib +from suitesparse_graphblas import __version__, check_status, ffi, lib, supports_complex from suitesparse_graphblas.api import matrix from suitesparse_graphblas.utils import empty, give_buffer @@ -42,8 +42,6 @@ lib.GrB_UINT64: 8, lib.GrB_FP32: 9, lib.GrB_FP64: 10, - lib.GxB_FC32: 11, - lib.GxB_FC64: 12, } _ss_typenames = { @@ -58,10 +56,14 @@ lib.GrB_UINT64: "GrB_UINT64", lib.GrB_FP32: "GrB_FP32", lib.GrB_FP64: "GrB_FP64", - lib.GxB_FC32: "GxB_FC32", - lib.GxB_FC64: "GxB_FC64", } +if supports_complex(): + _ss_typecodes[lib.GxB_FC32] = 11 + _ss_typecodes[lib.GxB_FC64] = 12 + _ss_typenames[lib.GxB_FC32] = "GxB_FC32" + _ss_typenames[lib.GxB_FC64] = "GxB_FC64" + _ss_codetypes = {v: k for k, v in _ss_typecodes.items()} From b47edf3fa6cf004077a19f2c2445dd9c25eea0f7 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:01:37 -0600 Subject: [PATCH 42/47] test_libget: check the GrB_FC64 fallback only with complex types Without complex types neither GrB_FC64 nor GxB_FC64 exists, so libget("GrB_FC64") raises AttributeError. GrB_HYPER_SWITCH still checks the fallback to GxB_ in every build. --- suitesparse_graphblas/tests/test_package.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index 2b0ee63..0b49a70 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -97,7 +97,8 @@ def test_libget(): assert not hasattr(lib, "GrB_HYPER_SWITCH") assert libget("GrB_HYPER_SWITCH") == lib.GxB_HYPER_SWITCH assert not hasattr(lib, "GrB_FC64") - assert libget("GrB_FC64") == lib.GxB_FC64 + if supports_complex(): + assert libget("GrB_FC64") == lib.GxB_FC64 # If neither exists, the error names what was asked for with pytest.raises(AttributeError, match="GrB_NO_SUCH_NAME"): libget("GrB_NO_SUCH_NAME") From c7f66a643b26a0eb0717acc59a7f198648b3f084 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:01:46 -0600 Subject: [PATCH 43/47] Test that the complex functions exist only with complex types matrix, vector, scalar, monoid and iterator define their fc32 and fc64 functions under `if supports_complex():`. Check the names in both kinds of build: all of them with complex types, and none without, rather than functions that would fail on a missing lib attribute. --- suitesparse_graphblas/tests/test_package.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/suitesparse_graphblas/tests/test_package.py b/suitesparse_graphblas/tests/test_package.py index 0b49a70..8d513aa 100644 --- a/suitesparse_graphblas/tests/test_package.py +++ b/suitesparse_graphblas/tests/test_package.py @@ -1,3 +1,4 @@ +import importlib import os import sys @@ -125,6 +126,24 @@ def test_type_sets(): assert len(grb_types) == 11 + len(complex_types) +_complex_functions = { + "matrix": ["set", "get", "matrix_build", "matrix_extract_tuples"], + "vector": ["set", "get", "vector_build", "vector_extract_tuples"], + "scalar": ["set", "get"], + "monoid": ["monoid_new", "monoid_terminal_new"], + "iterator": ["iterator_get"], +} + + +@pytest.mark.parametrize("module", _complex_functions) +def test_complex_functions(module): + # The functional API has its fc32 and fc64 functions only when the build has complex types + mod = importlib.import_module(f"suitesparse_graphblas.api.{module}") + names = {name for name in vars(mod) if name.endswith(("_fc32", "_fc64"))} + expected = {f"{prefix}_{t}" for prefix in _complex_functions[module] for t in ["fc32", "fc64"]} + assert names == (expected if supports_complex() else set()) + + # conda-forge's cffi links conda's libffi, and through it a variadic call on macOS arm64 loses # its variadic arguments, with or without vararg: a double arrives as 0.0 and an int32 setting # doesn't change (cffi 2.0.0, libffi 3.5.2). PyPI's cffi links the system libffi and works. From 8c6bcc400aeed21470e285945f0f49519ae097a6 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:01:49 -0600 Subject: [PATCH 44/47] CI: test a build without complex types Add one job that builds with SUITESPARSE_GRAPHBLAS_NO_COMPLEX=1 and runs the same tests, coverage and upload as the others. It is ubuntu-latest with Python 3.15: Linux is the quickest runner, a GIL build skips the free-threaded jobs' threaded run, and the code it tests (the other side of each `if supports_complex():`) is Python that depends on neither the OS nor the Python version. The job is an `include:` entry with a new `source` value, because an entry that only added a key would merge into the existing ubuntu-latest 3.15 job. "Build" checks that supports_complex() is false, so the job can't pass by testing the usual build, and the job uploads to Codecov under its own name. --- .github/workflows/test.yml | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4f70c9e..1b13a0a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -33,6 +33,12 @@ jobs: # source: ["source"] # A trailing "t" means the free-threaded (no-GIL) build of that version. python-version: ["3.11", "3.12", "3.13", "3.14", "3.14t", "3.15", "3.15t"] + include: + # Also build psg without complex types (GraphBLAS always has them) and test that. + # GraphBLAS is from conda-forge; "-no-complex" sets the switch in "Build". + - os: ubuntu-latest + source: conda-forge-no-complex + python-version: "3.15" steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -100,8 +106,13 @@ jobs: # make install # popd - name: Build + env: + SUITESPARSE_GRAPHBLAS_NO_COMPLEX: ${{ contains(matrix.source, 'no-complex') && '1' || '' }} run: | pip install -e . --no-deps + if [[ -n $SUITESPARSE_GRAPHBLAS_NO_COMPLEX ]]; then + python -c 'import suitesparse_graphblas as ssgb; assert not ssgb.supports_complex()' + fi - name: Test env: PYVER: ${{ matrix.python-version }} @@ -134,7 +145,7 @@ jobs: # The "Coverage report" step wrote coverage.xml, so skip the uploader's own search for # gcov, Xcode, Swift and coverage.py data (it only logs a warning for each). plugins: noop - name: ${{ matrix.os }} ${{ matrix.python-version }} + name: ${{ matrix.os }} ${{ matrix.python-version }}${{ contains(matrix.source, 'no-complex') && ' no-complex' || '' }} # PRs from forks upload without a token. Pushes to main need the repository # secret CODECOV_TOKEN. An upload that fails doesn't fail the job. token: ${{ secrets.CODECOV_TOKEN }} From b9c8d23594eae8f988ff35b82730f80aa7dc3ea7 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:02:11 -0600 Subject: [PATCH 45/47] Measure both branches of the complex-type checks The `# pragma: no branch` on the `if supports_complex():` in api/matrix, vector, scalar, monoid and iterator, and the `# pragma: no cover` on the `else:` in __init__.py, said that every build declares complex types. The no-complex CI job now takes the other branch, so let coverage measure it: in the report Codecov merges from all jobs, both branches of each check are covered. Each job's own report shows one partial branch per check, as it already did for the tests' own checks. --- suitesparse_graphblas/__init__.py | 2 +- suitesparse_graphblas/api/iterator.py | 2 +- suitesparse_graphblas/api/matrix.py | 2 +- suitesparse_graphblas/api/monoid.py | 2 +- suitesparse_graphblas/api/scalar.py | 2 +- suitesparse_graphblas/api/vector.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 668635d..58a0ef7 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -162,7 +162,7 @@ def libget(name): lib.GxB_FC64, ) ) -else: # pragma: no cover (every build uses suitesparse_graphblas.h, which has complex) +else: complex_types = frozenset() diff --git a/suitesparse_graphblas/api/iterator.py b/suitesparse_graphblas/api/iterator.py index 7ccfd74..9382707 100644 --- a/suitesparse_graphblas/api/iterator.py +++ b/suitesparse_graphblas/api/iterator.py @@ -616,7 +616,7 @@ def iterator_get_fp64(it): return lib.GxB_Iterator_get_FP64(it[0]) -if supports_complex(): # pragma: no branch (the build always declares complex types) +if supports_complex(): def iterator_get_fc32(it): """Get the current fc32 value from the iterator.""" diff --git a/suitesparse_graphblas/api/matrix.py b/suitesparse_graphblas/api/matrix.py index b6166e5..157d733 100644 --- a/suitesparse_graphblas/api/matrix.py +++ b/suitesparse_graphblas/api/matrix.py @@ -1873,7 +1873,7 @@ def get_fp64(A, i, j): return value[0] -if supports_complex(): # pragma: no branch (the build always declares complex types) +if supports_complex(): def set_fc32(A, value, i, j): """Set an fc32 value to the matrix at row `i` column `j`. diff --git a/suitesparse_graphblas/api/monoid.py b/suitesparse_graphblas/api/monoid.py index d2e3cce..1f55125 100644 --- a/suitesparse_graphblas/api/monoid.py +++ b/suitesparse_graphblas/api/monoid.py @@ -379,7 +379,7 @@ def monoid_terminal_new_udt(op, identity, terminal, *, free=monoid_free): return m -if supports_complex(): # pragma: no branch (the build always declares complex types) +if supports_complex(): def monoid_new_fc32(op, identity, *, free=monoid_free): """Create a new GrB_Monoid with an fc32 identity. diff --git a/suitesparse_graphblas/api/scalar.py b/suitesparse_graphblas/api/scalar.py index 3e66f33..f4537a3 100644 --- a/suitesparse_graphblas/api/scalar.py +++ b/suitesparse_graphblas/api/scalar.py @@ -449,7 +449,7 @@ def get_fp64(s): return value[0] -if supports_complex(): # pragma: no branch (the build always declares complex types) +if supports_complex(): def set_fc32(s, value): """Set an fc32 value to the scalar. diff --git a/suitesparse_graphblas/api/vector.py b/suitesparse_graphblas/api/vector.py index 5438941..f123028 100644 --- a/suitesparse_graphblas/api/vector.py +++ b/suitesparse_graphblas/api/vector.py @@ -1560,7 +1560,7 @@ def get_fp64(v, i): return value[0] -if supports_complex(): # pragma: no branch (the build always declares complex types) +if supports_complex(): def set_fc32(v, value, i): """Set an fc32 value to the vector at position `i`. From 73575d3643fd392e4dfef55df759f948afc5e8ff Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:11:13 -0600 Subject: [PATCH 46/47] Add completeness guards derived from GraphBLAS's own declarations New tests/test_completeness.py fails when a newer GraphBLAS declares something the package does not cover, instead of relying on hand lists that can go stale. Each expected set comes from cffi's lib and ffi, so the tests also adapt to a build without complex types. - Built-in types: the GrB_/GxB_ names matching BOOL, INT, UINT, FP and FC are checked to be exactly the GrB_Type constants, then compared with grb_types. The bool/signed/unsigned/real/complex partition is derived from each type's GrB_EL_TYPE_CODE against GrB_Type_Code. - Binary file tables: _ss_typecodes, _ss_typenames and grb_types must have the same keys, and each name must equal the type's GrB_NAME. - Compression: the GxB_COMPRESSION_* codecs must be exactly the five known ones, so a new codec prompts a decision about its level, and each must appear in test_io's _serialize_options. - Wrapper families: get_*/set_* (matrix, vector, scalar), *_build_*, *_extract_tuples_*, iterator_get_*, monoid_new_* and monoid_terminal_new_* must cover every built-in type (and udt for the monoid ones). - Sparsity: the GxB_HYPERSPARSE/SPARSE/BITMAP/FULL constants must match the _sparsities tables in test_io and test_iterator. --- .../tests/test_completeness.py | 167 ++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 suitesparse_graphblas/tests/test_completeness.py diff --git a/suitesparse_graphblas/tests/test_completeness.py b/suitesparse_graphblas/tests/test_completeness.py new file mode 100644 index 0000000..477d3d8 --- /dev/null +++ b/suitesparse_graphblas/tests/test_completeness.py @@ -0,0 +1,167 @@ +"""Guards that the package covers everything the GraphBLAS it is built against declares. + +Each expected set is derived from GraphBLAS itself (the cffi `lib` and `ffi`), never from a hand +list, so a GraphBLAS that adds a type, a compression codec or a sparsity format fails a test here +and prompts a decision, instead of the package quietly falling behind. +""" + +import importlib +import re + +import pytest + +import suitesparse_graphblas as sg +from suitesparse_graphblas import ffi, lib +from suitesparse_graphblas.api.io import binary + +_TYPE_NAME = re.compile(r"G[rx]B_(BOOL|U?INT\d+|FP\d+|FC\d+)") + +_GrB_Type = ffi.typeof("GrB_Type") + +# The complex types are present exactly when the GraphBLAS was built with them +_builtin_names = sorted(n for n in dir(lib) if _TYPE_NAME.fullmatch(n)) +_builtin_types = {n: getattr(lib, n) for n in _builtin_names} + + +def _type_code(T): + value = ffi.new("int32_t*") + assert lib.GrB_Type_get_INT32(T, value, lib.GrB_EL_TYPE_CODE) == lib.GrB_SUCCESS + return value[0] + + +def _type_name(T): + size = ffi.new("size_t*") + assert lib.GrB_Type_get_SIZE(T, size, lib.GrB_NAME) == lib.GrB_SUCCESS + buf = ffi.new("char[]", size[0]) + assert lib.GrB_Type_get_String(T, buf, lib.GrB_NAME) == lib.GrB_SUCCESS + return ffi.string(buf).decode() + + +def test_builtin_type_names_are_all_types(): + # The pattern that finds the built-in types must not pick up anything else + for name in _builtin_names: + assert ffi.typeof(getattr(lib, name)) is _GrB_Type, name + assert len(_builtin_names) == (13 if sg.supports_complex() else 11) + # ... and must miss none: every GrB_Type constant is a built-in type + all_types = { + n + for n in dir(lib) + if n.startswith(("GrB_", "GxB_")) + and isinstance(getattr(lib, n), ffi.CData) + and ffi.typeof(getattr(lib, n)) is _GrB_Type + } + assert all_types == set(_builtin_names) + + +def test_grb_types_has_every_builtin_type(): + assert sg.grb_types == frozenset(_builtin_types.values()) + + +def test_type_families_partition_by_type_code(): + codes = ffi.typeof("GrB_Type_Code").relements + families = { + "BOOL": sg.bool_types, + "INT": sg.signed_integer_types, + "UINT": sg.unsigned_integer_types, + "FP": sg.real_types, + "FC": sg.complex_types, + } + expected = {name: set() for name in families} + for name, T in _builtin_types.items(): + code = _type_code(T) + (code_name,) = (n for n, v in codes.items() if v == code) + assert code_name == f"{name}_CODE" + family = re.fullmatch(r"G[rx]B_(BOOL|U?INT|FP|FC)\d*", name).group(1) + expected[family].add(T) + for family, types in families.items(): + assert types == expected[family], family + assert sg.integer_types == sg.signed_integer_types | sg.unsigned_integer_types + # The type codes are the built-in types plus the user-defined one + assert set(codes) == {f"{n}_CODE" for n in _builtin_names} | {"GrB_UDT_CODE"} + + +def test_binary_type_tables_cover_every_type(): + assert set(binary._ss_typecodes) == set(binary._ss_typenames) == set(sg.grb_types) + # The on-disk ordinals are unique, and decode back to the type + assert len(set(binary._ss_typecodes.values())) == len(binary._ss_typecodes) + assert {binary._ss_codetypes[c] for c in binary._ss_typecodes.values()} == set(sg.grb_types) + + +@pytest.mark.parametrize("name", _builtin_names) +def test_binary_type_name_matches_graphblas(name): + T = _builtin_types[name] + assert binary._ss_typenames[T] == _type_name(T) + + +_compression_names = sorted( + n for n in dir(lib) if n.startswith("GxB_COMPRESSION_") and not callable(getattr(lib, n)) +) + + +def test_compression_codecs_are_known(): + # A new codec needs a decision: whether it takes a level, as LZ4HC and ZSTD do (see + # `serialize.get_serialize_desc`), and a case in the `_serialize_options` tests in test_io.py + assert _compression_names == [ + "GxB_COMPRESSION_DEFAULT", + "GxB_COMPRESSION_LZ4", + "GxB_COMPRESSION_LZ4HC", + "GxB_COMPRESSION_NONE", + "GxB_COMPRESSION_ZSTD", + ] + + +@pytest.mark.parametrize("name", _compression_names) +def test_every_compression_codec_is_tested(name): + from suitesparse_graphblas.tests.test_io import _serialize_options + + assert getattr(lib, name) in {compression for compression, _ in _serialize_options.values()} + + +_ALL_TYPES = [n[4:].lower() for n in _builtin_names] + +# (module, family prefix, whether there is also a user-defined-type variant) +_families = [ + ("matrix", "get", False), + ("matrix", "set", False), + ("matrix", "matrix_build", False), + ("matrix", "matrix_extract_tuples", False), + ("vector", "get", False), + ("vector", "set", False), + ("vector", "vector_build", False), + ("vector", "vector_extract_tuples", False), + ("scalar", "get", False), + ("scalar", "set", False), + ("iterator", "iterator_get", False), + ("monoid", "monoid_new", True), + ("monoid", "monoid_terminal_new", True), +] + + +@pytest.mark.parametrize("module, prefix, udt", _families) +def test_wrapper_family_covers_every_type(module, prefix, udt): + mod = importlib.import_module(f"suitesparse_graphblas.api.{module}") + suffixes = _ALL_TYPES + (["udt"] if udt else []) + # Functions named `_` (functions of other families, such as + # `matrix_option_get_int32`, are named differently) + found = { + name[len(prefix) + 1 :] + for name in vars(mod) + if name.startswith(prefix + "_") + and callable(getattr(mod, name)) + and re.fullmatch(r"(bool|u?int\d+|fp\d+|fc\d+|udt)", name[len(prefix) + 1 :]) + } + assert found == set(suffixes) + + +def test_sparsity_formats_are_known(): + from suitesparse_graphblas.tests.test_io import _sparsities + + found = { + getattr(lib, n) + for n in dir(lib) + if re.fullmatch(r"GxB_(HYPERSPARSE|SPARSE|BITMAP|FULL)", n) + } + assert found == set(_sparsities) + from suitesparse_graphblas.tests import test_iterator + + assert set(test_iterator._sparsities) == found From cc4854cbe20d0b89fc1ea3b51bafeda11c4bf0aa Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:31:22 -0600 Subject: [PATCH 47/47] binwrite: refuse comments that make the header too long binread skips a text header of exactly GRB_HEADER_LEN (512) bytes, but binwrite wrote a longer header when the comments didn't fit (over about 330 characters), so binread misread the file. Raise ValueError instead, before the file is opened, so nothing is written and the matrix is restored as on any other error. The strict xfail test now checks that the longest comment that fits round-trips, and that one character more is refused and writes no file. --- suitesparse_graphblas/api/io/binary.py | 8 ++++++++ suitesparse_graphblas/tests/test_io.py | 25 +++++++++++++++---------- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 8ffe9cb..5265d21 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -73,6 +73,9 @@ def binwrite(A, filename, comments=None, opener=Path.open): ``opener`` opens the file for writing (e.g. ``gzip.open`` to compress it). To avoid a copy, ``A`` is unpacked while it is written and packed again afterwards (even if writing fails), so other threads must not use ``A`` meanwhile. + + ``comments`` must be ASCII, and short enough that the text header fits in + ``GRB_HEADER_LEN`` (512) bytes; otherwise this raises ValueError and writes nothing. """ if isinstance(filename, str): filename = Path(filename) @@ -245,6 +248,11 @@ def binwrite(A, filename, comments=None, opener=Path.open): ) header_content = header_template.format(**vars) header = f"{header_content: <{GRB_HEADER_LEN}}".encode("ascii") + if len(header) > GRB_HEADER_LEN: + raise ValueError( + f"comments are too long: the header would be {len(header)} bytes, " + f"and binread reads only the first {GRB_HEADER_LEN}" + ) with opener(filename, "wb") as f: fwrite = f.write diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index b6bd660..00507ce 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -422,20 +422,25 @@ def test_binread_unknown_field(tmp_path, offset, value, message): binary.binread(path) -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="binwrite lets comments make the header longer than the 512 bytes binread skips", -) def test_binwrite_long_comments(tmp_path): + # binread skips a header of exactly GRB_HEADER_LEN bytes, so binwrite refuses + # comments that would make it longer, before it opens the file A = _make_matrix(lib.GrB_INT64, "sparse") path = tmp_path / "matrix.binfile" - try: + binary.binwrite(A, path, comments="") + used = len(path.read_bytes()[: binary.GRB_HEADER_LEN].rstrip(b" ")) + room = binary.GRB_HEADER_LEN - used + # The longest comment that fits round-trips + binary.binwrite(A, path, comments="x" * room) + _assert_matrices_equal(A, binary.binread(path)) + # One more character is refused, and nothing is written + path.unlink() + with pytest.raises(ValueError, match="comments are too long"): + binary.binwrite(A, path, comments="x" * (room + 1)) + assert not path.exists() + with pytest.raises(ValueError, match="comments are too long"): binary.binwrite(A, path, comments="x" * binary.GRB_HEADER_LEN) - except ValueError: # refusing such comments would do as well as shortening them - assert not path.exists() - else: - _assert_matrices_equal(A, binary.binread(path)) + assert not path.exists() _assert_matrices_equal(A, _make_matrix(lib.GrB_INT64, "sparse"))