From cb20e2cdcc543b290e9844a22f90b6176635b05d Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 21:55:21 -0600 Subject: [PATCH 01/17] Raise OverflowError for int32 settings that don't fit, not wrap around The functions that set an int32 option or property (context_set_int32 and context_set_nthreads, matrix_set_format, matrix_set_sparsity_control, the *_option_set_int32 and *_set_int32 of each object, and the global ones) passed the value through ffi.cast("int32_t", value), which wraps around silently: context_set_nthreads(ctx, 2**32 + 3) set 3 threads, and matrix_set_format(A, 2**32 + 1) made A held by column. Each of the GraphBLAS functions they call takes an int32_t (none is variadic), so pass the value as it is, as the element setters do: cffi checks the range and raises OverflowError. Integers in range, including NumPy integers and integer cdata, are converted as before. A float or a str is now a TypeError. The cast truncated a float (4.7 set 4) and took a one-character str as its character code ("3" set 51 threads), which the docstrings ("from an int32") never promised. test_set_int32_rejects_non_int32 tries values just out of range, a float and a str with each of these functions. Before, each call set the wrapped, truncated or character-code value (or GraphBLAS rejected it, for the read-only properties of types, semirings, monoids and operators) instead of raising OverflowError or TypeError. --- suitesparse_graphblas/api/binaryop.py | 2 +- suitesparse_graphblas/api/context.py | 2 +- suitesparse_graphblas/api/descriptor.py | 2 +- suitesparse_graphblas/api/global_options.py | 4 +- suitesparse_graphblas/api/grb_type.py | 2 +- suitesparse_graphblas/api/indexbinaryop.py | 2 +- suitesparse_graphblas/api/indexunaryop.py | 2 +- suitesparse_graphblas/api/matrix.py | 10 +- suitesparse_graphblas/api/monoid.py | 2 +- suitesparse_graphblas/api/semiring.py | 2 +- suitesparse_graphblas/api/unaryop.py | 2 +- suitesparse_graphblas/api/vector.py | 2 +- .../tests/test_api_objects.py | 132 +++++++++++++++++- suitesparse_graphblas/tests/test_api_ops.py | 18 +++ 14 files changed, 164 insertions(+), 20 deletions(-) diff --git a/suitesparse_graphblas/api/binaryop.py b/suitesparse_graphblas/api/binaryop.py index 7faa009..ead5c26 100644 --- a/suitesparse_graphblas/api/binaryop.py +++ b/suitesparse_graphblas/api/binaryop.py @@ -158,7 +158,7 @@ def binaryop_get_int32(op, field): def binaryop_set_int32(op, field, value): """Set an operator option from an int32.""" - check_status(op, lib.GrB_BinaryOp_set_INT32(op[0], ffi.cast("int32_t", value), field)) + check_status(op, lib.GrB_BinaryOp_set_INT32(op[0], value, field)) def binaryop_get_size(op, field): diff --git a/suitesparse_graphblas/api/context.py b/suitesparse_graphblas/api/context.py index 5549bd5..07237d8 100644 --- a/suitesparse_graphblas/api/context.py +++ b/suitesparse_graphblas/api/context.py @@ -102,7 +102,7 @@ def context_set_int32(ctx, field, value): 2 """ - check_status(ctx, lib.GxB_Context_set_INT32(ctx[0], field, ffi.cast("int32_t", value))) + check_status(ctx, lib.GxB_Context_set_INT32(ctx[0], field, value)) def context_get_fp64(ctx, field): diff --git a/suitesparse_graphblas/api/descriptor.py b/suitesparse_graphblas/api/descriptor.py index 9b57de8..7d21c56 100644 --- a/suitesparse_graphblas/api/descriptor.py +++ b/suitesparse_graphblas/api/descriptor.py @@ -86,7 +86,7 @@ def descriptor_set_int32(desc, field, value): desc, lib.GrB_Descriptor_set_INT32( desc, - ffi.cast("int32_t", value), + value, field, ), ) diff --git a/suitesparse_graphblas/api/global_options.py b/suitesparse_graphblas/api/global_options.py index ab0998b..85ec02b 100644 --- a/suitesparse_graphblas/api/global_options.py +++ b/suitesparse_graphblas/api/global_options.py @@ -23,7 +23,7 @@ def global_option_set_int32(field, value): >>> global_option_set_int32(lib.GxB_BURBLE, 0) """ - info = lib.GxB_Global_Option_set_INT32(field, ffi.cast("int32_t", value)) + info = lib.GxB_Global_Option_set_INT32(field, value) if info != lib.GrB_SUCCESS: raise _error_code_lookup.get(info, RuntimeError)( f"GxB_Global_Option_set_INT32 failed with info={info}" @@ -99,7 +99,7 @@ def global_set_int32(field, value): >>> global_set_int32(lib.GxB_NTHREADS, nthreads) """ - info = lib.GrB_Global_set_INT32(lib.GrB_GLOBAL, ffi.cast("int32_t", value), field) + info = lib.GrB_Global_set_INT32(lib.GrB_GLOBAL, value, field) if info != lib.GrB_SUCCESS: raise _error_code_lookup.get(info, RuntimeError)( f"GrB_Global_set_INT32 failed with info={info}" diff --git a/suitesparse_graphblas/api/grb_type.py b/suitesparse_graphblas/api/grb_type.py index 5552de0..5ce067c 100644 --- a/suitesparse_graphblas/api/grb_type.py +++ b/suitesparse_graphblas/api/grb_type.py @@ -131,7 +131,7 @@ def grb_type_set_int32(T, field, value): suitesparse_graphblas.exceptions.InvalidValue """ - check_status(T, lib.GrB_Type_set_INT32(T[0], ffi.cast("int32_t", value), field)) + check_status(T, lib.GrB_Type_set_INT32(T[0], value, field)) def grb_type_get_size(T, field): diff --git a/suitesparse_graphblas/api/indexbinaryop.py b/suitesparse_graphblas/api/indexbinaryop.py index 4ababdb..eb3acbb 100644 --- a/suitesparse_graphblas/api/indexbinaryop.py +++ b/suitesparse_graphblas/api/indexbinaryop.py @@ -108,7 +108,7 @@ def indexbinaryop_get_int32(op, field): def indexbinaryop_set_int32(op, field, value): """Set an operator option from an int32.""" - check_status(op, lib.GxB_IndexBinaryOp_set_INT32(op[0], ffi.cast("int32_t", value), field)) + check_status(op, lib.GxB_IndexBinaryOp_set_INT32(op[0], value, field)) def indexbinaryop_get_size(op, field): diff --git a/suitesparse_graphblas/api/indexunaryop.py b/suitesparse_graphblas/api/indexunaryop.py index f2414c6..7bfb513 100644 --- a/suitesparse_graphblas/api/indexunaryop.py +++ b/suitesparse_graphblas/api/indexunaryop.py @@ -143,7 +143,7 @@ def indexunaryop_get_int32(op, field): def indexunaryop_set_int32(op, field, value): """Set an operator option from an int32.""" - check_status(op, lib.GrB_IndexUnaryOp_set_INT32(op[0], ffi.cast("int32_t", value), field)) + check_status(op, lib.GrB_IndexUnaryOp_set_INT32(op[0], value, field)) def indexunaryop_get_size(op, field): diff --git a/suitesparse_graphblas/api/matrix.py b/suitesparse_graphblas/api/matrix.py index 157d733..d2f577e 100644 --- a/suitesparse_graphblas/api/matrix.py +++ b/suitesparse_graphblas/api/matrix.py @@ -127,8 +127,7 @@ def matrix_set_format(A, format): True """ - format_val = ffi.cast("int32_t", format) - check_status(A, lib.GxB_Matrix_Option_set_INT32(A[0], lib.GxB_FORMAT, format_val)) + check_status(A, lib.GxB_Matrix_Option_set_INT32(A[0], lib.GxB_FORMAT, format)) def matrix_sparsity_status(A): @@ -149,10 +148,7 @@ def matrix_sparsity_control(A): def matrix_set_sparsity_control(A, sparsity): """Set the sparsity control of the matrix.""" - sparsity_control = ffi.cast("int32_t", sparsity) - check_status( - A, lib.GxB_Matrix_Option_set_INT32(A[0], lib.GxB_SPARSITY_CONTROL, sparsity_control) - ) + check_status(A, lib.GxB_Matrix_Option_set_INT32(A[0], lib.GxB_SPARSITY_CONTROL, sparsity)) def matrix_hyper_switch(A): @@ -208,7 +204,7 @@ def matrix_option_set_int32(A, field, value): lib.GxB_Matrix_Option_set_INT32( A[0], field, - ffi.cast("int32_t", value), + value, ), ) diff --git a/suitesparse_graphblas/api/monoid.py b/suitesparse_graphblas/api/monoid.py index 1f55125..fe02dd3 100644 --- a/suitesparse_graphblas/api/monoid.py +++ b/suitesparse_graphblas/api/monoid.py @@ -525,7 +525,7 @@ def monoid_get_int32(m, field): def monoid_set_int32(m, field, value): """Set a monoid option from an int32.""" - check_status(m, lib.GrB_Monoid_set_INT32(m[0], ffi.cast("int32_t", value), field)) + check_status(m, lib.GrB_Monoid_set_INT32(m[0], value, field)) def monoid_get_size(m, field): diff --git a/suitesparse_graphblas/api/semiring.py b/suitesparse_graphblas/api/semiring.py index 328e342..ee8722a 100644 --- a/suitesparse_graphblas/api/semiring.py +++ b/suitesparse_graphblas/api/semiring.py @@ -123,7 +123,7 @@ def semiring_get_int32(s, field): def semiring_set_int32(s, field, value): """Set a semiring option from an int32.""" - check_status(s, lib.GrB_Semiring_set_INT32(s[0], ffi.cast("int32_t", value), field)) + check_status(s, lib.GrB_Semiring_set_INT32(s[0], value, field)) def semiring_get_size(s, field): diff --git a/suitesparse_graphblas/api/unaryop.py b/suitesparse_graphblas/api/unaryop.py index f26b9eb..d71b818 100644 --- a/suitesparse_graphblas/api/unaryop.py +++ b/suitesparse_graphblas/api/unaryop.py @@ -142,7 +142,7 @@ def unaryop_get_int32(op, field): def unaryop_set_int32(op, field, value): """Set an operator option from an int32.""" - check_status(op, lib.GrB_UnaryOp_set_INT32(op[0], ffi.cast("int32_t", value), field)) + check_status(op, lib.GrB_UnaryOp_set_INT32(op[0], value, field)) def unaryop_get_size(op, field): diff --git a/suitesparse_graphblas/api/vector.py b/suitesparse_graphblas/api/vector.py index f123028..1340f8a 100644 --- a/suitesparse_graphblas/api/vector.py +++ b/suitesparse_graphblas/api/vector.py @@ -109,7 +109,7 @@ def vector_option_set_int32(v, field, value): lib.GxB_Vector_Option_set_INT32( v[0], field, - ffi.cast("int32_t", value), + value, ), ) diff --git a/suitesparse_graphblas/tests/test_api_objects.py b/suitesparse_graphblas/tests/test_api_objects.py index 4316ecc..d592fe7 100644 --- a/suitesparse_graphblas/tests/test_api_objects.py +++ b/suitesparse_graphblas/tests/test_api_objects.py @@ -1,7 +1,16 @@ import pytest from suitesparse_graphblas import exceptions, ffi, lib -from suitesparse_graphblas.api import container, context, descriptor, grb_type, semiring +from suitesparse_graphblas.api import ( + container, + context, + descriptor, + global_options, + grb_type, + matrix, + semiring, + vector, +) def test_grb_type_definition_longer_than_256(): @@ -147,3 +156,124 @@ def test_semiring_name_longer_than_256(): 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 + + +def _matrix_setting(set_, get, value): + A = matrix.matrix_new(lib.GrB_INT64, 2, 2) + return value, lambda v: set_(A, v), lambda: get(A) + + +def _descriptor_setting(field, value): + D = ffi.new("GrB_Descriptor*") + assert lib.GrB_Descriptor_new(D) == lib.GrB_SUCCESS + D = ffi.gc(D, lib.GrB_Descriptor_free) + return ( + value, + lambda v: descriptor.descriptor_set_int32(D[0], field, v), + lambda: descriptor.descriptor_get_int32(D[0], field), + ) + + +def _setting(new, set_, get, field, value): + obj = new() + return value, lambda v: set_(obj, field, v), lambda: get(obj, field) + + +def _global_setting(set_, get, field): + return 1 - get(field), lambda v: set_(field, v), lambda: get(field) + + +# Each function that sets an int32 option or property: `(value, set, get)` for that setting of +# a new object, where `value` is in range and accepted (or rejected by GraphBLAS anyway, for the +# read-only properties of a type or a semiring) +_int32_settings = { + "context_set_int32": lambda: _setting( + context.context_new, + context.context_set_int32, + context.context_get_int32, + lib.GxB_CONTEXT_NTHREADS, + 3, + ), + "context_set_nthreads": lambda: _setting( + context.context_new, + lambda ctx, _, v: context.context_set_nthreads(ctx, v), + lambda ctx, _: context.context_get_nthreads(ctx), + None, + 3, + ), + "matrix_set_format": lambda: _matrix_setting( + matrix.matrix_set_format, matrix.matrix_format, lib.GxB_BY_COL + ), + "matrix_set_sparsity_control": lambda: _matrix_setting( + matrix.matrix_set_sparsity_control, matrix.matrix_sparsity_control, lib.GxB_SPARSE + ), + "matrix_option_set_int32": lambda: _setting( + lambda: matrix.matrix_new(lib.GrB_INT64, 2, 2), + matrix.matrix_option_set_int32, + matrix.matrix_option_get_int32, + lib.GxB_FORMAT, + lib.GxB_BY_COL, + ), + "vector_option_set_int32": lambda: _setting( + lambda: vector.vector_new(lib.GrB_INT64, 2), + vector.vector_option_set_int32, + vector.vector_option_get_int32, + lib.GxB_SPARSITY_CONTROL, + lib.GxB_SPARSE, + ), + "descriptor_set_int32": lambda: _descriptor_setting(lib.GrB_OUTP_FIELD, lib.GrB_REPLACE), + "grb_type_set_int32": lambda: _setting( + lambda: grb_type.grb_type_new(8), + grb_type.grb_type_set_int32, + grb_type.grb_type_get_int32, + lib.GrB_EL_TYPE_CODE, + lib.GrB_INT64_CODE, + ), + "semiring_set_int32": lambda: _setting( + lambda: semiring.semiring_new(lib.GrB_MAX_MONOID_FP64, lib.GrB_PLUS_FP64), + semiring.semiring_set_int32, + semiring.semiring_get_int32, + lib.GrB_INP0_TYPE_CODE, + lib.GrB_INT64_CODE, + ), + "global_option_set_int32": lambda: _global_setting( + global_options.global_option_set_int32, + global_options.global_option_get_int32, + lib.GxB_PRINT_1BASED, + ), + "global_set_int32": lambda: _global_setting( + global_options.global_set_int32, global_options.global_get_int32, lib.GxB_PRINT_1BASED + ), +} + +_global_unsafe = pytest.mark.thread_unsafe( + reason="a value that wrapped around would set a global option" +) + + +@pytest.mark.parametrize( + "name", + [ + pytest.param(name, marks=_global_unsafe if name.startswith("global") else ()) + for name in _int32_settings + ], +) +def test_set_int32_rejects_non_int32(name): + # A value that doesn't fit in an int32 is an error, rather than wrapping around to one that + # does (2**32 + 3 would set 3) + value, set_, get = _int32_settings[name]() + old = get() + try: + for wrapped in (value + 2**32, value - 2**32, 2**31, -(2**31) - 1): + with pytest.raises(OverflowError): + set_(wrapped) + assert get() == old + # So is a float or a str, rather than truncated (4.7 would set 4) or taken as a + # character code ("3" would set 51) + for wrong in (value + 0.7, "3"): + with pytest.raises(TypeError): + set_(wrong) + assert get() == old + finally: + if get() != old: # put a global option back + set_(old) diff --git a/suitesparse_graphblas/tests/test_api_ops.py b/suitesparse_graphblas/tests/test_api_ops.py index 790b9ff..140d4c4 100644 --- a/suitesparse_graphblas/tests/test_api_ops.py +++ b/suitesparse_graphblas/tests/test_api_ops.py @@ -309,6 +309,24 @@ def test_set_int32_not_allowed(kind): assert get_int32(obj, lib.GrB_OUTP_TYPE_CODE) == code +@pytest.mark.parametrize("kind", list(MODULES)) +def test_set_int32_rejects_non_int32(kind): + # A value that doesn't fit in an int32 is an error, rather than wrapping around to one that + # does (and that GraphBLAS then rejects, here). So is a float or a str, rather than + # truncated or taken as a character code. + get_int32 = _func(kind, "get_int32") + set_int32 = _func(kind, "set_int32") + obj = _user_defined(kind) + code = get_int32(obj, lib.GrB_OUTP_TYPE_CODE) + for value in (lib.GrB_BOOL_CODE + 2**32, 2**31, -(2**31) - 1): + with pytest.raises(OverflowError): + set_int32(obj, lib.GrB_OUTP_TYPE_CODE, value) + for value in (lib.GrB_BOOL_CODE + 0.7, "3"): + with pytest.raises(TypeError): + set_int32(obj, lib.GrB_OUTP_TYPE_CODE, value) + assert get_int32(obj, lib.GrB_OUTP_TYPE_CODE) == code + + @pytest.mark.parametrize( ("kind", "name"), [ From 45b2eec376134b196ccdba23bb7422b3fb851c15 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 21:56:22 -0600 Subject: [PATCH 02/17] binread: check the file's GraphBLAS version with a ValueError, not assert binread checked that a file is from this version of SuiteSparse:GraphBLAS with an assert, so `python -O` skipped the check (and read the file anyway), and otherwise the error was a bare AssertionError. Raise ValueError instead, saying what the version is and what it should be. test_binread_other_version changes the version in a file: binread raised AssertionError, and read the file under `python -O`. --- suitesparse_graphblas/api/io/binary.py | 12 +++++++++--- suitesparse_graphblas/tests/test_io.py | 12 ++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 5265d21..a54aca7 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -400,7 +400,8 @@ def binwrite(A, filename, comments=None, opener=Path.open): def binread(filename, opener=Path.open): """Read a Matrix from ``filename``, written by ``binwrite``. - ``opener`` opens the file for reading (e.g. ``gzip.open``). + ``opener`` opens the file for reading (e.g. ``gzip.open``). The file must be from this + version of SuiteSparse:GraphBLAS, else this raises ValueError. """ if isinstance(filename, str): filename = Path(filename) @@ -416,8 +417,13 @@ def fread(nbytes): fread(GRB_HEADER_LEN) impl = frombuff("uint64_t*", fread(sizeof("uint64_t"))) - - assert impl[0] == lib.GxB_IMPLEMENTATION + if impl[0] != lib.GxB_IMPLEMENTATION: + raise ValueError( + f"{filename} is not from binwrite with SuiteSparse:GraphBLAS " + f"v{lib.GxB_IMPLEMENTATION_MAJOR}.{lib.GxB_IMPLEMENTATION_MINOR}." + f"{lib.GxB_IMPLEMENTATION_SUB}: its version is {impl[0]}, not " + f"{lib.GxB_IMPLEMENTATION}" + ) format = frombuff("GxB_Format_Value*", fread(sizeof("GxB_Format_Value"))) sparsity_status = frombuff("int32_t*", fread(sizeof("int32_t"))) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index c5b3de9..7713619 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -428,6 +428,18 @@ def test_binread_unknown_field(tmp_path, offset, value, message): binary.binread(path) +def test_binread_other_version(tmp_path): + # binread reads files from this version of GraphBLAS only, and checks even under + # `python -O`, which skips asserts + path = tmp_path / "matrix.binfile" + binary.binwrite(_make_matrix(lib.GrB_INT64, "sparse"), path) + data = bytearray(path.read_bytes()) + struct.pack_into("=Q", data, binary.GRB_HEADER_LEN, lib.GxB_IMPLEMENTATION + 1) + path.write_bytes(data) + with pytest.raises(ValueError, match=f"its version is {lib.GxB_IMPLEMENTATION + 1}, not"): + binary.binread(path) + + 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 From 0dd132c4efdff6a298c29b69167f8dc64e8013de Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:01:23 -0600 Subject: [PATCH 03/17] binread: have GraphBLAS check the matrix in the file binread packs the arrays it reads into a matrix with GxB_Matrix_pack_*, which by default trusts them: GraphBLAS checks their sizes, but not their content. So a corrupt file made an invalid matrix. For example, binread returned a 3x4 matrix with an entry in column 1000, which GxB_Matrix_fprint called GrB_INVALID_OBJECT, and which later operations would index out of bounds with. Pack with a descriptor whose GxB_IMPORT is GxB_SECURE_IMPORT: GraphBLAS then checks the matrix as it does for GxB_Matrix_fprint. It checks the indices (in range, sorted, no duplicates), the row or column pointers, the hypersparse list, and the bitmap, and binread raises InvalidObject or IndexOutOfBound. The check fails after GraphBLAS has taken the arrays, so the matrix frees them. 2000 failed reads of a 1.6 MB file left the maximum RSS where it was. The check is a single pass over the matrix in one thread. Reading a 10M x 10M FP64 matrix from the page cache took 0.016 s before and 0.10 s after, with 10M entries (a 240 MB file), and 0.045 s before and 0.20 s after, with 50M entries (880 MB). Reading the file from disk, or decompressing it, costs more than that. Checking the same things in NumPy was faster for CSR (0.03-0.04 s), but it would repeat GraphBLAS's rules for each format in this module. test_binread_invalid_matrix changes the arrays of a file in eight ways (column out of range, out of order, or repeated; decreasing row pointers; hypersparse rows out of range or out of order; a bitmap holding 2, or more entries than nvals). binread returned a matrix for each one. --- suitesparse_graphblas/api/io/binary.py | 24 ++++++++-- suitesparse_graphblas/tests/test_io.py | 64 ++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 3 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index a54aca7..3e12d05 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -67,6 +67,19 @@ _ss_codetypes = {v: k for k, v in _ss_typecodes.items()} +def _secure_import_desc(): + """A new descriptor for ``GxB_Matrix_pack_*`` to check the arrays it is given. + + By default, packing trusts them, and arrays that aren't a valid matrix (from a corrupt + file, say) make an invalid one. The check takes O(nvals) time. + """ + desc = ffi.new("GrB_Descriptor*") + check_status(desc, lib.GrB_Descriptor_new(desc)) + desc = ffi.gc(desc, lib.GrB_Descriptor_free) + check_status(desc, lib.GrB_Descriptor_set_INT32(desc[0], lib.GxB_SECURE_IMPORT, lib.GxB_IMPORT)) + return desc + + def binwrite(A, filename, comments=None, opener=Path.open): """Write Matrix ``A`` to ``filename`` in SuiteSparse:GraphBLAS's binary format. @@ -401,7 +414,9 @@ def binread(filename, opener=Path.open): """Read a Matrix from ``filename``, written by ``binwrite``. ``opener`` opens the file for reading (e.g. ``gzip.open``). The file must be from this - version of SuiteSparse:GraphBLAS, else this raises ValueError. + version of SuiteSparse:GraphBLAS, else this raises ValueError. GraphBLAS checks the + matrix it holds (in O(nvals) time), so a corrupt file raises an error, such as + ``InvalidObject``, rather than making an invalid matrix. """ if isinstance(filename, str): filename = Path(filename) @@ -492,15 +507,18 @@ def read(nbytes, ctype): # An iso matrix stores a single value, and GraphBLAS must be told its true size read(typesize[0] if is_iso[0] else nx * typesize[0], "void*") # Ax + desc = _secure_import_desc() with ExitStack() as stack: - # The buffers become GraphBLAS's only if the pack succeeds + # The buffers become GraphBLAS's once the pack takes them. It checks their sizes + # first, and their content (sorted indices in range, ...) after: if that fails, `A` + # holds them, and frees them when it is freed given = [ stack.enter_context(give_buffer(array, ctype, copy=False, arena=arena)) for array, ctype in buffers ] ptrs = [ptr for ptr, _, _ in given] sizes = [nbytes for _, nbytes, _ in given] - check_status(A, pack(A[0], *ptrs, *sizes, is_iso[0], *args, NULL)) + check_status(A, pack(A[0], *ptrs, *sizes, is_iso[0], *args, desc[0])) matrix.matrix_set_sparsity_control(A, sparsity_control[0]) matrix.matrix_set_hyper_switch(A, hyper_switch[0]) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 7713619..d3ce4cf 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -14,6 +14,7 @@ bool_types, check_status, complex_types, + exceptions, ffi, grb_types, lib, @@ -428,6 +429,69 @@ def test_binread_unknown_field(tmp_path, offset, value, message): binary.binread(path) +# Where the arrays start: after the sparsity status and control (int32 each), the hyper and +# bitmap switches, nrows, ncols, nvec, nvals, the type code (int32), the type size, and iso +_arrays_offset = ( + _sparsity_offset + + 2 * ffi.sizeof("int32_t") + + 2 * ffi.sizeof("double") + + 4 * ffi.sizeof("GrB_Index") + + ffi.sizeof("int32_t") + + ffi.sizeof("size_t") + + ffi.sizeof("bool") +) + + +def _binfile_arrays(data, sparsity): + """The index arrays of `_make_matrix(lib.GrB_INT64, "sparse")` (3x4, by row) in `data`, a + bytearray of the file binwrite wrote for it, as writable views of `data`.""" + sizes = { + lib.GxB_SPARSE: [("Ap", np.uint64, 4), ("Ai", np.uint64, 3)], + lib.GxB_HYPERSPARSE: [("Ap", np.uint64, 3), ("Ah", np.uint64, 2), ("Ai", np.uint64, 3)], + lib.GxB_BITMAP: [("Ab", np.int8, 12)], + }[sparsity] + arrays = {} + offset = _arrays_offset + for name, dtype, size in sizes: + arrays[name] = np.frombuffer(data, dtype, size, offset) + offset += arrays[name].nbytes + return arrays + + +# Ways a file can hold an invalid matrix, each as (sparsity, name of an array, the array as +# binwrite wrote it, what to change it to, what binread raises: GraphBLAS calls indices out of +# order or repeated "out of bounds", and anything else an invalid object) +_bitmap = [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1] +_out_of_bounds = exceptions.IndexOutOfBound +_invalid_arrays = { + "column out of range": (lib.GxB_SPARSE, "Ai", [1, 0, 3], [1, 0, 4], InvalidObject), + "columns out of order": (lib.GxB_SPARSE, "Ai", [1, 0, 3], [1, 3, 0], _out_of_bounds), + "duplicate column": (lib.GxB_SPARSE, "Ai", [1, 0, 3], [1, 0, 0], _out_of_bounds), + "row pointers decrease": (lib.GxB_SPARSE, "Ap", [0, 1, 1, 3], [0, 2, 1, 3], InvalidObject), + "row out of range": (lib.GxB_HYPERSPARSE, "Ah", [0, 2], [0, 3], InvalidObject), + "rows out of order": (lib.GxB_HYPERSPARSE, "Ah", [0, 2], [2, 0], InvalidObject), + "bitmap not 0 or 1": (lib.GxB_BITMAP, "Ab", _bitmap, [2] * 12, InvalidObject), + "bitmap not nvals": (lib.GxB_BITMAP, "Ab", _bitmap, [1] * 12, InvalidObject), +} + + +@pytest.mark.parametrize("case", _invalid_arrays) +def test_binread_invalid_matrix(tmp_path, case): + # GraphBLAS checks what binread gives it, so a corrupt file can't make an invalid matrix + sparsity, name, written, invalid, exception = _invalid_arrays[case] + A = _make_matrix(lib.GrB_INT64, "sparse") + matrix.matrix_set_sparsity_control(A, sparsity) + path = tmp_path / "matrix.binfile" + binary.binwrite(A, path) + data = bytearray(path.read_bytes()) + array = _binfile_arrays(data, sparsity)[name] + assert array.tolist() == written + array[:] = invalid + path.write_bytes(data) + with pytest.raises(exception): + binary.binread(path) + + def test_binread_other_version(tmp_path): # binread reads files from this version of GraphBLAS only, and checks even under # `python -O`, which skips asserts From 34f4742d2bcd791c143a3a777454b0212ccf4639 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:02:18 -0600 Subject: [PATCH 04/17] initialize: raise GraphBLASException for an unknown failure code When GxB_init or GrB_init fails, initialize raises the exception for the code from _error_code_lookup, as check_status does. For a code that isn't in the table, though, it fell back to RuntimeError, where check_status and burble fall back to GraphBLASException, the base class of the others. Fall back to GraphBLASException here too. Every GrB_Info error code of this GraphBLAS is in the table, so only a code that a newer GraphBLAS adds would reach the fallback. The RuntimeError that the docstring promises, for initializing twice, comes from the is_initialized() check before the call, and is unchanged. test_initialize_fails makes the init call return a code (with is_initialized patched to say GraphBLAS isn't initialized): an unknown one raised RuntimeError. It also covers this branch, so it no longer needs its "no cover" pragma. --- suitesparse_graphblas/__init__.py | 4 ++-- suitesparse_graphblas/tests/test_exceptions.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/suitesparse_graphblas/__init__.py b/suitesparse_graphblas/__init__.py index 58a0ef7..2e5935b 100644 --- a/suitesparse_graphblas/__init__.py +++ b/suitesparse_graphblas/__init__.py @@ -104,8 +104,8 @@ def initialize(*, blocking=False, memory_manager="numpy"): else: raise ValueError(f'memory_manager argument must be "numpy" or "c"; got: {memory_manager!r}') # 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)( + if info != lib.GrB_SUCCESS: + raise _error_code_lookup.get(info, ex.GraphBLASException)( f"Failed to initialize GraphBLAS (info={info})" ) # See: https://github.com/GraphBLAS/python-suitesparse-graphblas/issues/40 diff --git a/suitesparse_graphblas/tests/test_exceptions.py b/suitesparse_graphblas/tests/test_exceptions.py index 477ac39..eaa1755 100644 --- a/suitesparse_graphblas/tests/test_exceptions.py +++ b/suitesparse_graphblas/tests/test_exceptions.py @@ -1,5 +1,6 @@ import pytest +import suitesparse_graphblas from suitesparse_graphblas import ( _error_code_lookup, _error_func_lookup, @@ -63,6 +64,22 @@ def test_check_status_unknown_code(): assert type(excinfo.value) is exceptions.GraphBLASException +@pytest.mark.thread_unsafe(reason="patches the package") +@pytest.mark.parametrize( + "info, exception", + [(lib.GrB_OUT_OF_MEMORY, exceptions.OutOfMemory), (-12345, exceptions.GraphBLASException)], + ids=["out of memory", "unknown"], +) +def test_initialize_fails(monkeypatch, info, exception): + # If GraphBLAS fails to initialize, `initialize` raises the exception for the code, as + # check_status does: the base class for a code that this build doesn't know + monkeypatch.setattr(suitesparse_graphblas, "is_initialized", lambda: False) + monkeypatch.setattr(suitesparse_graphblas.utils, "call_gxb_init", lambda ffi, lib, mode: info) + with pytest.raises(exception, match=f"info={info}") as excinfo: + suitesparse_graphblas.initialize() + assert type(excinfo.value) is exception + + 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) From e3920a41ea3d494052a14e3bdea77f28ff1d29b2 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:03:02 -0600 Subject: [PATCH 05/17] binwrite: leave the comment line empty when there are no comments binwrite formatted `comments` into the text header as they were, so the default, None, wrote a line saying "None". Write an empty line instead, as LAGraph's binwrite does when it has no comments. binread skips the text header, so it still reads the files with "None" in them. test_binwrite_without_comments compares the header binwrite writes without comments to the one with comments="": it had "None" where the other had an empty line. It also reads a file with "None" in it. --- suitesparse_graphblas/api/io/binary.py | 5 +++-- suitesparse_graphblas/tests/test_io.py | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 3e12d05..41bb1a2 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -87,7 +87,8 @@ def binwrite(A, filename, comments=None, opener=Path.open): 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 + ``comments`` go at the end of the text header (None leaves an empty line there, as LAGraph + does). They 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): @@ -257,7 +258,7 @@ def binwrite(A, filename, comments=None, opener=Path.open): size=typesize[0], type=_ss_typenames[matrix_type[0]], iso=int(is_iso[0]), - comments=comments, + comments="" if comments is None else comments, ) header_content = header_template.format(**vars) header = f"{header_content: <{GRB_HEADER_LEN}}".encode("ascii") diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index d3ce4cf..771890e 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -504,6 +504,22 @@ def test_binread_other_version(tmp_path): binary.binread(path) +def test_binwrite_without_comments(tmp_path): + # Without comments, the comment line of the header is empty, as LAGraph writes it + A = _make_matrix(lib.GrB_INT64, "sparse") + path = tmp_path / "matrix.binfile" + binary.binwrite(A, path, comments="") + header = path.read_bytes()[: binary.GRB_HEADER_LEN] + assert header.decode("ascii").split("\n")[9:11] == ["iso: 0", ""] + binary.binwrite(A, path) + assert path.read_bytes()[: binary.GRB_HEADER_LEN] == header + _assert_matrices_equal(A, binary.binread(path)) + # binwrite wrote "None" for no comments before, and binread still reads those files + binary.binwrite(A, path, comments="None") + assert b"\nNone\n" in path.read_bytes()[: binary.GRB_HEADER_LEN] + _assert_matrices_equal(A, binary.binread(path)) + + 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 From d168a52d6a3a74d9f9620abcce3b2091c0ecd2f4 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:04:59 -0600 Subject: [PATCH 06/17] Tests: run test_io.py and binread's memory check on Windows too test_io.py skipped itself on Windows since it was added, in #18 (2021), without saying why. The commits squashed into #18 say: io/binary.py got `malloc` from libc with cffi's `dlopen(None)`, and then from `dlopen(find_library("c"))`, neither of which works on Windows, so importing it failed ("cant call dlopen(None) on windows...", then "no binary file cookies for you windows!", which added the skip). The skip went above the import of binary. binary.py has needed neither since: 0b713dc dlopened ucrtbase on Windows, and #157 dropped libc's malloc for GraphBLAS's own allocator (and doctest-modules has imported binary.py on Windows since). So remove the skip. The tests write and read files in tmp_path, close each file before opening it again, and use fixed-size fields. The allocator check in test_memory.py also skipped binread and binwrite on Windows ("see test_io.py"). Skip only its arena that uses libc's allocator, which does need `dlopen(None)`. --- suitesparse_graphblas/tests/test_io.py | 3 --- suitesparse_graphblas/tests/test_memory.py | 5 ++--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 771890e..a8d0329 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -1,7 +1,6 @@ import bz2 import functools import gzip -import platform import struct import sys from contextlib import contextmanager @@ -31,8 +30,6 @@ except ImportError: # Pyodide before 314 has it as a separate package lzma = None -if platform.system() == "Windows": - pytest.skip("skipping windows-only tests", allow_module_level=True) from suitesparse_graphblas.api import context # isort:skip from suitesparse_graphblas.api.global_options import global_get_int32 # isort:skip diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index 651bd14..9cd2bc8 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -18,7 +18,6 @@ ) # Move memory between GraphBLAS and NumPy every supported way, then free all of it. -# `binary` is not tested on Windows; see test_io.py. SCRIPT = textwrap.dedent(""" import gc import sys @@ -116,8 +115,6 @@ def roundtrips(): for t in threads: t.join() - if sys.platform == "win32": - return from suitesparse_graphblas.io import binary # `binread` hands its buffers to GraphBLAS; an iso matrix stores a single value, and @@ -135,6 +132,8 @@ def roundtrips(): check_status(B, lib.GrB_Matrix_wait(B[0], lib.GrB_MATERIALIZE)) assert matrix.matrix_nvals(B) == 900 + if sys.platform == "win32": # no `dlopen(None)` to get libc's allocator from + return # Another arena, using libc's allocator k = lib.GxB_NARENAS - 1 import cffi From d952f529eb0d2a3c0628f6d567d48c3ad00a24e6 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:15:39 -0600 Subject: [PATCH 07/17] _capture_c_output: capture into a temporary file, not a pipe The test helper pointed stdout at a pipe and read the pipe after the call returned, so a call that printed more than the pipe holds (64 KiB on Linux and macOS) blocked forever, waiting for a reader; and it read only the first 100000 bytes. A temporary file takes any amount of output without a reader, and without a thread, which Pyodide doesn't have. An empty file also reads as "", where Emscripten raised BlockingIOError for an empty pipe. test_capture_c_output_of_more_than_a_pipe_holds prints a vector of 10000 entries (about 200 KB): it hung (and was killed after 30 s) with the pipe. The new helper passes the tests of the old one (no file descriptor leaks, stdout restored after an error) here and on Pyodide. --- suitesparse_graphblas/api/utils.py | 20 ++++++++----------- suitesparse_graphblas/tests/test_api_utils.py | 19 +++++++++++++++++- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/suitesparse_graphblas/api/utils.py b/suitesparse_graphblas/api/utils.py index cbcaaeb..ee052d6 100644 --- a/suitesparse_graphblas/api/utils.py +++ b/suitesparse_graphblas/api/utils.py @@ -1,25 +1,21 @@ import os import sys +import tempfile def _capture_c_output(fn, *args): """Capture C-level stdout output from a function call.""" sys.stdout.flush() - r, w = os.pipe() - old = os.dup(1) - try: + # A file, unlike a pipe, takes any amount of output without a reader, and needs no thread + with tempfile.TemporaryFile() as f: + old = os.dup(1) try: - os.dup2(w, 1) + os.dup2(f.fileno(), 1) try: fn(*args) finally: os.dup2(old, 1) finally: - os.close(w) - 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) + os.close(old) + f.seek(0) + return f.read().decode() diff --git a/suitesparse_graphblas/tests/test_api_utils.py b/suitesparse_graphblas/tests/test_api_utils.py index 81c6d7d..6d587d5 100644 --- a/suitesparse_graphblas/tests/test_api_utils.py +++ b/suitesparse_graphblas/tests/test_api_utils.py @@ -1,9 +1,10 @@ import os +import numpy as np import pytest from suitesparse_graphblas import exceptions, ffi, lib -from suitesparse_graphblas.api import context +from suitesparse_graphblas.api import context, vector from suitesparse_graphblas.api.utils import _capture_c_output @@ -65,3 +66,19 @@ def failing_dup2(fd, fd2): monkeypatch.undo() assert _stdout_id() == stdout assert _free_fds() == fds + + +@pytest.mark.thread_unsafe(reason="redirects file descriptor 1") +def test_capture_c_output_of_more_than_a_pipe_holds(): + # The output used to go to a pipe that was read after the call returned, so printing more + # than the pipe holds (64 KiB on Linux and macOS) waited forever for a reader + n = 10_000 + v = vector.vector_new(lib.GrB_INT64, n) + indices = np.arange(n, dtype=np.uint64) + vector.vector_build_int64(v, indices, indices.astype(np.int64), n, lib.GrB_PLUS_INT64) + fds = _free_fds() + out = _capture_c_output(vector.vector_print, v, "v", lib.GxB_COMPLETE) + assert len(out) > 2**17 + entries = [line for line in out.splitlines() if line.startswith(" (")] + assert entries == [f" ({i},0) {i}" for i in range(n)] + assert _free_fds() == fds From 4e0bd4ab62e0b4f886e2a8cfd4de5c274f662df7 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:41:41 -0600 Subject: [PATCH 08/17] binread: check the matrix after packing it, not with a secure pack 29ac555 packed with GxB_SECURE_IMPORT, so that GraphBLAS would check the matrix. When that check fails, though, GB_import frees the matrix it packed into (GB_FREE_ALL, on the pack's own copy of the handle), header and all. binread's handle was left pointing at freed memory: check_status read the error string from it (always empty), and the handle's ffi.gc freed it again once the exception was gone, by when a new matrix could have been given the same memory, and was destroyed. Pack as before, which checks only the sizes of the arrays, and then check the matrix with GxB_Matrix_fprint(A, "", GxB_SILENT, NULL). That runs the same check (GB_matvec_check) and leaves A a valid header that is freed as usual. It returns GrB_INVALID_OBJECT for anything wrong (also for indices out of order or repeated, which the secure pack reported as GrB_INDEX_OUT_OF_BOUNDS), with no error string, so binread raises InvalidObject with a message of its own, naming the file. test_binread_invalid_matrix_frees_only_its_own keeps the exception of a failed read, makes ten matrices, and drops the exception: after the secure pack, the first new matrix had lost its header (UninitializedObject). test_binread_invalid_matrix now also corrupts files of a matrix held by column, and checks the message. The check costs what the secure pack's did. Reading 10M FP64 entries from the page cache took 0.010 s without it and 0.029 s with it, for a 1M x 1M matrix with 10 entries in each row; 0.015 s and 0.056 s for a 10M x 10M matrix with one in each row; and 0.017 s and 0.105 s for one with 10M entries in random places (the case 29ac555 measured), where GxB_Matrix_fprint alone takes 0.095 s. --- suitesparse_graphblas/api/io/binary.py | 36 +++++------ suitesparse_graphblas/tests/test_io.py | 89 ++++++++++++++++++-------- 2 files changed, 78 insertions(+), 47 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 41bb1a2..eb557f3 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -5,6 +5,7 @@ from suitesparse_graphblas import __version__, check_status, ffi, lib, supports_complex from suitesparse_graphblas.api import matrix +from suitesparse_graphblas.exceptions import InvalidObject from suitesparse_graphblas.utils import empty, give_buffer GRB_HEADER_LEN = 512 @@ -67,19 +68,6 @@ _ss_codetypes = {v: k for k, v in _ss_typecodes.items()} -def _secure_import_desc(): - """A new descriptor for ``GxB_Matrix_pack_*`` to check the arrays it is given. - - By default, packing trusts them, and arrays that aren't a valid matrix (from a corrupt - file, say) make an invalid one. The check takes O(nvals) time. - """ - desc = ffi.new("GrB_Descriptor*") - check_status(desc, lib.GrB_Descriptor_new(desc)) - desc = ffi.gc(desc, lib.GrB_Descriptor_free) - check_status(desc, lib.GrB_Descriptor_set_INT32(desc[0], lib.GxB_SECURE_IMPORT, lib.GxB_IMPORT)) - return desc - - def binwrite(A, filename, comments=None, opener=Path.open): """Write Matrix ``A`` to ``filename`` in SuiteSparse:GraphBLAS's binary format. @@ -416,8 +404,8 @@ def binread(filename, opener=Path.open): ``opener`` opens the file for reading (e.g. ``gzip.open``). The file must be from this version of SuiteSparse:GraphBLAS, else this raises ValueError. GraphBLAS checks the - matrix it holds (in O(nvals) time), so a corrupt file raises an error, such as - ``InvalidObject``, rather than making an invalid matrix. + matrix it holds (in O(nvals) time), so a corrupt file raises InvalidObject rather than + making an invalid matrix. """ if isinstance(filename, str): filename = Path(filename) @@ -508,18 +496,26 @@ def read(nbytes, ctype): # An iso matrix stores a single value, and GraphBLAS must be told its true size read(typesize[0] if is_iso[0] else nx * typesize[0], "void*") # Ax - desc = _secure_import_desc() with ExitStack() as stack: - # The buffers become GraphBLAS's once the pack takes them. It checks their sizes - # first, and their content (sorted indices in range, ...) after: if that fails, `A` - # holds them, and frees them when it is freed + # The buffers become GraphBLAS's only if the pack succeeds, which checks their + # sizes; then `A` holds them, and frees them when it is freed, valid or not given = [ stack.enter_context(give_buffer(array, ctype, copy=False, arena=arena)) for array, ctype in buffers ] ptrs = [ptr for ptr, _, _ in given] sizes = [nbytes for _, nbytes, _ in given] - check_status(A, pack(A[0], *ptrs, *sizes, is_iso[0], *args, desc[0])) + check_status(A, pack(A[0], *ptrs, *sizes, is_iso[0], *args, NULL)) + + # The pack trusts the content of the buffers, so check that they make a valid matrix + # (sorted indices in range, ...). A pack with GxB_SECURE_IMPORT would check it too, but + # when the check fails it frees the matrix, leaving `A` a handle to freed memory. + info = lib.GxB_Matrix_fprint(A[0], b"", lib.GxB_SILENT, NULL) + if info == lib.GrB_INVALID_OBJECT: + raise InvalidObject( + f"{filename} does not hold a valid matrix: GxB_Matrix_fprint rejects it" + ) + check_status(A, info) matrix.matrix_set_sparsity_control(A, sparsity_control[0]) matrix.matrix_set_hyper_switch(A, hyper_switch[0]) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index a8d0329..a4a1f14 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -13,7 +13,6 @@ bool_types, check_status, complex_types, - exceptions, ffi, grb_types, lib, @@ -439,13 +438,24 @@ def test_binread_unknown_field(tmp_path, offset, value, message): ) +def _symmetric_matrix(format, sparsity): + """A 4x4 INT64 matrix whose pattern is its own transpose, so that its arrays are the same + whether it is held by row or by column: entries (0, 0), (0, 2), (2, 0), and (3, 3).""" + A = matrix.matrix_new(lib.GrB_INT64, 4, 4) + for k, (i, j) in enumerate([(0, 0), (0, 2), (2, 0), (3, 3)]): + matrix.set_int64(A, 10 * k, i, j) + matrix.matrix_set_format(A, format) + matrix.matrix_set_sparsity_control(A, sparsity) + return A + + def _binfile_arrays(data, sparsity): - """The index arrays of `_make_matrix(lib.GrB_INT64, "sparse")` (3x4, by row) in `data`, a - bytearray of the file binwrite wrote for it, as writable views of `data`.""" + """The index arrays of `_symmetric_matrix` in `data`, a bytearray of the file binwrite wrote + for it, as writable views of `data`.""" sizes = { - lib.GxB_SPARSE: [("Ap", np.uint64, 4), ("Ai", np.uint64, 3)], - lib.GxB_HYPERSPARSE: [("Ap", np.uint64, 3), ("Ah", np.uint64, 2), ("Ai", np.uint64, 3)], - lib.GxB_BITMAP: [("Ab", np.int8, 12)], + lib.GxB_SPARSE: [("Ap", np.uint64, 5), ("Ai", np.uint64, 4)], + lib.GxB_HYPERSPARSE: [("Ap", np.uint64, 4), ("Ah", np.uint64, 3), ("Ai", np.uint64, 4)], + lib.GxB_BITMAP: [("Ab", np.int8, 16)], }[sparsity] arrays = {} offset = _arrays_offset @@ -456,37 +466,62 @@ def _binfile_arrays(data, sparsity): # Ways a file can hold an invalid matrix, each as (sparsity, name of an array, the array as -# binwrite wrote it, what to change it to, what binread raises: GraphBLAS calls indices out of -# order or repeated "out of bounds", and anything else an invalid object) -_bitmap = [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1] -_out_of_bounds = exceptions.IndexOutOfBound +# binwrite wrote it, what to change it to) +_bitmap = [1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1] _invalid_arrays = { - "column out of range": (lib.GxB_SPARSE, "Ai", [1, 0, 3], [1, 0, 4], InvalidObject), - "columns out of order": (lib.GxB_SPARSE, "Ai", [1, 0, 3], [1, 3, 0], _out_of_bounds), - "duplicate column": (lib.GxB_SPARSE, "Ai", [1, 0, 3], [1, 0, 0], _out_of_bounds), - "row pointers decrease": (lib.GxB_SPARSE, "Ap", [0, 1, 1, 3], [0, 2, 1, 3], InvalidObject), - "row out of range": (lib.GxB_HYPERSPARSE, "Ah", [0, 2], [0, 3], InvalidObject), - "rows out of order": (lib.GxB_HYPERSPARSE, "Ah", [0, 2], [2, 0], InvalidObject), - "bitmap not 0 or 1": (lib.GxB_BITMAP, "Ab", _bitmap, [2] * 12, InvalidObject), - "bitmap not nvals": (lib.GxB_BITMAP, "Ab", _bitmap, [1] * 12, InvalidObject), + "index out of range": (lib.GxB_SPARSE, "Ai", [0, 2, 0, 3], [0, 2, 0, 4]), + "indices out of order": (lib.GxB_SPARSE, "Ai", [0, 2, 0, 3], [2, 0, 0, 3]), + "duplicate index": (lib.GxB_SPARSE, "Ai", [0, 2, 0, 3], [0, 0, 0, 3]), + "pointers decrease": (lib.GxB_SPARSE, "Ap", [0, 2, 2, 3, 4], [0, 2, 1, 3, 4]), + "hypersparse index out of range": (lib.GxB_HYPERSPARSE, "Ah", [0, 2, 3], [0, 2, 4]), + "hypersparse indices out of order": (lib.GxB_HYPERSPARSE, "Ah", [0, 2, 3], [2, 0, 3]), + "bitmap not 0 or 1": (lib.GxB_BITMAP, "Ab", _bitmap, [2] + _bitmap[1:]), + "bitmap not nvals": (lib.GxB_BITMAP, "Ab", _bitmap, [1] * 16), } +_formats = {lib.GxB_BY_ROW: "by row", lib.GxB_BY_COL: "by column"} -@pytest.mark.parametrize("case", _invalid_arrays) -def test_binread_invalid_matrix(tmp_path, case): - # GraphBLAS checks what binread gives it, so a corrupt file can't make an invalid matrix - sparsity, name, written, invalid, exception = _invalid_arrays[case] - A = _make_matrix(lib.GrB_INT64, "sparse") - matrix.matrix_set_sparsity_control(A, sparsity) - path = tmp_path / "matrix.binfile" - binary.binwrite(A, path) +def _invalid_binfile(path, format, case): + """Write a file at `path` that binread reads as an invalid matrix, made as `case` says.""" + sparsity, name, written, invalid = _invalid_arrays[case] + binary.binwrite(_symmetric_matrix(format, sparsity), path) data = bytearray(path.read_bytes()) array = _binfile_arrays(data, sparsity)[name] assert array.tolist() == written array[:] = invalid path.write_bytes(data) - with pytest.raises(exception): + + +@pytest.mark.parametrize("case", _invalid_arrays) +@pytest.mark.parametrize("format", _formats, ids=_formats.get) +def test_binread_invalid_matrix(tmp_path, format, case): + # binread checks the matrix it reads, so a corrupt file can't make an invalid one + path = tmp_path / "matrix.binfile" + sparsity = _invalid_arrays[case][0] + binary.binwrite(_symmetric_matrix(format, sparsity), path) + _assert_matrices_equal(binary.binread(path), _symmetric_matrix(format, sparsity)) + _invalid_binfile(path, format, case) + with pytest.raises(InvalidObject, match="does not hold a valid matrix"): + binary.binread(path) + + +def test_binread_invalid_matrix_frees_only_its_own(tmp_path): + # A matrix binread rejects is freed once, when the exception that holds it goes, and with + # nothing else. (When GraphBLAS checked the matrix as it packed it, a failed check freed + # the matrix itself, and binread's handle to it was left to free whatever matrix came to + # use its memory next.) + import gc + + path = tmp_path / "matrix.binfile" + _invalid_binfile(path, lib.GxB_BY_ROW, "index out of range") + with pytest.raises(InvalidObject) as excinfo: binary.binread(path) + matrices = [_make_matrix(lib.GrB_INT64, "sparse") for _ in range(10)] + del excinfo + gc.collect() + for A in matrices: + assert matrix.matrix_nvals(A) == 3 + assert matrix.get_int64(A, 2, 3) == _values(lib.GrB_INT64)[1] def test_binread_other_version(tmp_path): From 410dc005908ac257eb837f07888110fd31b400c9 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:42:46 -0600 Subject: [PATCH 09/17] binread: name the file's GraphBLAS version as major.minor.sub The ValueError for a file from another version of GraphBLAS gave that version as GraphBLAS encodes it, GxB_VERSION(major, minor, sub): "its version is 10005004, not 10005003". Say "SuiteSparse:GraphBLAS 10.5.3: its version is 10.5.4" instead. test_binread_other_version checks the message for three versions: the next patch release, 11.0.0 and 9.4.12. It got the encoded numbers. --- suitesparse_graphblas/api/io/binary.py | 9 ++++++--- suitesparse_graphblas/tests/test_io.py | 20 ++++++++++++++++---- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index eb557f3..daa8a6f 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -68,6 +68,11 @@ _ss_codetypes = {v: k for k, v in _ss_typecodes.items()} +def _version(code): + """The version that ``code`` (``GxB_VERSION(major, minor, sub)``) stands for, as a str.""" + return f"{code // 1000000}.{code // 1000 % 1000}.{code % 1000}" + + def binwrite(A, filename, comments=None, opener=Path.open): """Write Matrix ``A`` to ``filename`` in SuiteSparse:GraphBLAS's binary format. @@ -424,9 +429,7 @@ def fread(nbytes): if impl[0] != lib.GxB_IMPLEMENTATION: raise ValueError( f"{filename} is not from binwrite with SuiteSparse:GraphBLAS " - f"v{lib.GxB_IMPLEMENTATION_MAJOR}.{lib.GxB_IMPLEMENTATION_MINOR}." - f"{lib.GxB_IMPLEMENTATION_SUB}: its version is {impl[0]}, not " - f"{lib.GxB_IMPLEMENTATION}" + f"{_version(lib.GxB_IMPLEMENTATION)}: its version is {_version(impl[0])}" ) format = frombuff("GxB_Format_Value*", fread(sizeof("GxB_Format_Value"))) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index a4a1f14..0ebd91a 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -530,10 +530,22 @@ def test_binread_other_version(tmp_path): path = tmp_path / "matrix.binfile" binary.binwrite(_make_matrix(lib.GrB_INT64, "sparse"), path) data = bytearray(path.read_bytes()) - struct.pack_into("=Q", data, binary.GRB_HEADER_LEN, lib.GxB_IMPLEMENTATION + 1) - path.write_bytes(data) - with pytest.raises(ValueError, match=f"its version is {lib.GxB_IMPLEMENTATION + 1}, not"): - binary.binread(path) + # GraphBLAS numbers a version as GxB_VERSION(major, minor, sub): 10.5.4 is 10005004 + major, minor, sub = ( + lib.GxB_IMPLEMENTATION_MAJOR, + lib.GxB_IMPLEMENTATION_MINOR, + lib.GxB_IMPLEMENTATION_SUB, + ) + for version, name in [ + (lib.GxB_IMPLEMENTATION + 1, f"{major}.{minor}.{sub + 1}"), + (11_000_000, "11.0.0"), + (9_004_012, "9.4.12"), + ]: + struct.pack_into("=Q", data, binary.GRB_HEADER_LEN, version) + path.write_bytes(data) + message = f"SuiteSparse:GraphBLAS {major}.{minor}.{sub}: its version is {name}$" + with pytest.raises(ValueError, match=message): + binary.binread(path) def test_binwrite_without_comments(tmp_path): From 60c5b770d529ac5389c59a52b03b3447fb34e401 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:43:08 -0600 Subject: [PATCH 10/17] Tests: drop a comment about the pipe _capture_c_output no longer uses test_print captures a silent and then a short fprint in one call because, it said, a capture of no output failed on Emscripten, where reading an empty pipe raised BlockingIOError. _capture_c_output captures into a temporary file now (97541fd), and no output reads as "", so the comment no longer holds. --- suitesparse_graphblas/tests/test_api_ops.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/suitesparse_graphblas/tests/test_api_ops.py b/suitesparse_graphblas/tests/test_api_ops.py index 140d4c4..97233ca 100644 --- a/suitesparse_graphblas/tests/test_api_ops.py +++ b/suitesparse_graphblas/tests/test_api_ops.py @@ -379,8 +379,6 @@ def test_print(kind): 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) From 35091355e5c8dd9c1a4da19e9cf8e69482c605f3 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:41:50 -0600 Subject: [PATCH 11/17] serialize: raise OverflowError for a compression that doesn't fit int32_t get_serialize_desc passed the compression method plus the level through ffi.cast("int32_t", ...), which wraps around silently: serialize_matrix(A, GxB_COMPRESSION_ZSTD, level=2**32 + 1) serialized with ZSTD level 1, and a float level was truncated. GxB_Desc_set_INT32 takes an int32_t, so pass the value as it is, as the other int32 setters now do: cffi checks the range and raises OverflowError, and a float or a str is a TypeError. Integers in range, NumPy's included, are converted as before. test_serialize_compression_out_of_range tries ZSTD and LZ4HC with levels 2**32 + 1 and 1 - 2**32, a method beyond int32_t, and a float level, with a stand-in for the module's `lib` that counts lookups. Each one raises when the descriptor is set, and GraphBLAS's serialize function is never reached. Before this change, each call serialized at the wrapped or truncated level. The other cast left in serialize.py is the deprecated nthreads of get_serialize_desc, where GraphBLAS rejects the field whatever its value. --- suitesparse_graphblas/api/io/serialize.py | 6 +-- suitesparse_graphblas/tests/test_io.py | 45 +++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index 1d9e114..34b2760 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -110,10 +110,8 @@ def get_serialize_desc(compression=lib.GxB_COMPRESSION_DEFAULT, level=None, nthr lib.GxB_COMPRESSION_ZSTD, }: compression += level - check_status( - desc, - lib.GxB_Desc_set_INT32(desc, lib.GxB_COMPRESSION, ffi.cast("int32_t", compression)), - ) + # OverflowError if it doesn't fit in int32_t, rather than wrapping around + check_status(desc, lib.GxB_Desc_set_INT32(desc, lib.GxB_COMPRESSION, compression)) return desc diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 0ebd91a..06d2dbc 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -1,4 +1,5 @@ import bz2 +import collections import functools import gzip import struct @@ -693,6 +694,50 @@ def test_serialize_compression_reaches_graphblas(): assert none > serialize.serialize_vector(v, lib.GxB_COMPRESSION_ZSTD).nbytes +class _CountingLib: + """`lib`, counting the lookups of each name in `counts`.""" + + def __init__(self): + self.counts = collections.Counter() + + def __getattr__(self, name): + self.counts[name] += 1 + return getattr(lib, name) + + +@pytest.mark.thread_unsafe(reason="replaces `lib` in the serialize module") +@pytest.mark.parametrize("kind", ["matrix", "vector"]) +def test_serialize_compression_out_of_range(monkeypatch, kind): + # The method plus the level goes to GraphBLAS as an int32_t. It used to wrap around, so + # ZSTD with level 2**32 + 1 serialized with level 1, and a float level was truncated. + # Now they raise, before anything is serialized. + if kind == "matrix": + A, ser, T = _numbered_matrix(10), serialize.serialize_matrix, "Matrix" + else: + A, ser, T = vector.vector_new(lib.GrB_INT64, 10), serialize.serialize_vector, "Vector" + vector.set_int64(A, 7, 2) + # Else the first serialization finishes that, and gives different bytes from the next + vector.vector_wait(A, lib.GrB_MATERIALIZE) + ZSTD, LZ4HC = lib.GxB_COMPRESSION_ZSTD, lib.GxB_COMPRESSION_LZ4HC + counting = _CountingLib() + monkeypatch.setattr(serialize, "lib", counting) + for compression, level in [ + (ZSTD, 2**32 + 1), + (LZ4HC, 2**32 + 1), + (ZSTD, 1 - 2**32), + (ZSTD + 2**32, None), + ]: + with pytest.raises(OverflowError): + ser(A, compression, level) + with pytest.raises(TypeError): + ser(A, ZSTD, 1.5) + monkeypatch.undo() + assert counting.counts["GxB_Desc_set_INT32"] == 5 # it got that far each time + assert counting.counts[f"GxB_{T}_serialize_arena"] == 0 + # Any kind of integer in range will do, as before + assert ser(A, ZSTD, np.int64(19)).tobytes() == ser(A, ZSTD, 19).tobytes() + + @pytest.mark.parametrize("free", [None, False], ids=["None", "False"]) def test_deserialize_without_free(free): # The caller frees the result From 300b36d03d44438b22c8b487e1606cde7cf0fa5e Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:48:47 -0600 Subject: [PATCH 12/17] serialize: check the Matrix that deserialize_matrix makes GxB_Matrix_deserialize checks only enough of a blob to read it without going past its end: a blob with column indices out of range, out of order or repeated deserialized to an invalid Matrix, which GxB_Matrix_fprint calls GrB_INVALID_OBJECT, and which later operations would index out of bounds with. GraphBLAS's User Guide says as much: the output "may still be corrupted", so check untrusted data "with GxB_*_fprint with the print level set to GxB_SILENT". So deserialize_matrix does that, as binread does. If the check fails, it frees the Matrix (with GrB_Matrix_free, not the caller's `free`, since the caller never gets it) and raises InvalidObject, whose message says what failed, where GraphBLAS has none. The check runs after _call_with_nthreads returns, and doesn't allocate, so the arenas and the Context work as before. 2000 failed deserializations of a 1.2 MB blob left the maximum RSS where it was. test_deserialize_matrix_invalid changes the column indices of an uncompressed blob in three ways, with and without nthreads, and checks that no Context is left engaged: deserialize_matrix returned a Matrix for each. The check takes O(nvals) time in one thread, where deserializing uses several, so it costs more than the deserializing itself. For 10M FP64 entries, deserialize_matrix took 0.006 s without it and 0.022 s with it (default compression) for a 1M x 1M matrix with 10 entries in each row, 0.007 s and 0.044 s for a 10M x 10M matrix with one in each row, and 0.008 s and 0.091 s for 10M entries in random places. The check can't help where the blob's header is corrupt in a way that makes GxB_Matrix_deserialize itself read out of bounds, a GraphBLAS bug of its own. --- suitesparse_graphblas/api/io/serialize.py | 29 ++++++++++++++++- suitesparse_graphblas/tests/test_io.py | 39 +++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index 34b2760..ed32ac8 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -5,7 +5,7 @@ from suitesparse_graphblas import check_status, ffi, lib from suitesparse_graphblas.api.global_options import global_get_int32 -from suitesparse_graphblas.exceptions import InvalidValue +from suitesparse_graphblas.exceptions import InvalidObject, InvalidValue from suitesparse_graphblas.utils import claim_buffer @@ -74,6 +74,24 @@ def _call_with_nthreads(nthreads, func, *args): lib.GxB_Context_free(ctx) +def _check_deserialized(obj, fprint, free, message): + """Free `obj` and raise InvalidObject(`message`) if `fprint` finds it invalid. + + GraphBLAS checks only enough of a blob to deserialize it without reading past its end, so + a corrupt blob can make an invalid object, and its User Guide says to check the result + with a silent ``GxB_*_fprint``. + """ + info = fprint(obj[0], b"", lib.GxB_SILENT, ffi.NULL) + if info == lib.GrB_SUCCESS: + return + try: + if info == lib.GrB_INVALID_OBJECT: + raise InvalidObject(message) + check_status(obj, info) + finally: + free(obj) + + def get_serialize_desc(compression=lib.GxB_COMPRESSION_DEFAULT, level=None, nthreads=None): """Create a descriptor for serializing or deserializing. @@ -201,6 +219,9 @@ def deserialize_matrix(data, *, free=True, nthreads=None): that is more than int32_t holds, and InvalidValue if a Context is engaged on this thread (which stays engaged: set its number of threads instead). Raises TypeError if `nthreads` isn't an integer, or is a bool. + + Raises InvalidObject if `data` doesn't hold a valid Matrix (GraphBLAS checks only that it + can read it), after freeing what it deserialized. The check takes O(nvals) time. """ data = np.frombuffer(data, np.uint8) A = ffi.new("GrB_Matrix*") @@ -214,6 +235,12 @@ def deserialize_matrix(data, *, free=True, nthreads=None): ffi.NULL, ) check_status(A, info) + _check_deserialized( + A, + lib.GxB_Matrix_fprint, + lib.GrB_Matrix_free, + "data does not hold a valid Matrix: GxB_Matrix_fprint rejects what it deserializes to", + ) if free: if callable(free): return ffi.gc(A, free) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 06d2dbc..5efe2d6 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -784,6 +784,45 @@ def test_deserialize_invalid(): deserialize(bytes(64)) +def _with_indices(blob, indices, new_indices): + """`blob`, uncompressed, with its array of `indices` (of 32 or 64 bits) made `new_indices`.""" + data = bytearray(blob) + for dtype in (np.uint32, np.uint64): + old = np.array(indices, dtype).tobytes() + if data.count(old) == 1: + k = data.index(old) + data[k : k + len(old)] = np.array(new_indices, dtype).tobytes() + return bytes(data) + raise AssertionError(f"{indices} are not in the blob just once") + + +# A 1000x1000 Matrix held by row, with entries in columns 101, 202 and 303, and ways its +# serialized column indices can make an invalid Matrix +_blob_entries = [(0, 101), (0, 202), (1, 303)] +_invalid_blob_indices = { + "index out of range": [101, 202, 1000], + "indices out of order": [202, 101, 303], + "duplicate index": [101, 101, 303], +} + + +@pytest.mark.parametrize("nthreads", [None, 2]) +@pytest.mark.parametrize("case", _invalid_blob_indices) +def test_deserialize_matrix_invalid(case, nthreads): + # GraphBLAS checks only enough of a blob to stay within it, so deserialize_matrix checks + # the Matrix it makes, and frees it if it's invalid + probe = context.context_new() + A = matrix.matrix_new(lib.GrB_INT64, 1000, 1000) + for k, (i, j) in enumerate(_blob_entries): + matrix.set_int64(A, k, i, j) + blob = serialize.serialize_matrix(A, lib.GxB_COMPRESSION_NONE).tobytes() + _assert_matrices_equal(A, serialize.deserialize_matrix(blob, nthreads=nthreads)) + blob = _with_indices(blob, [j for _, j in _blob_entries], _invalid_blob_indices[case]) + with pytest.raises(InvalidObject, match="does not hold a valid Matrix"): + serialize.deserialize_matrix(blob, nthreads=nthreads) + assert not _context_engaged(probe) + + def _context_engaged(probe): """Whether a GxB_Context is engaged on this thread. From 2cc06f62139aab6050a6108744bd61c91da0404f Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:50:20 -0600 Subject: [PATCH 13/17] serialize: check the Vector that deserialize_vector makes deserialize_vector had the same hole as deserialize_matrix: a blob with indices out of range, out of order or repeated made an invalid Vector. And GxB_Vector_deserialize takes a Matrix blob as well, so a 3x4 Matrix became a "Vector" of size 4 with 2 entries (held by row; 3 when held by column), which GxB_Vector_fprint calls GrB_INVALID_OBJECT. Check the result with a silent GxB_Vector_fprint, as deserialize_matrix does, and raise InvalidObject after freeing it. That rejects a Matrix blob unless its Matrix is n-by-1 and held by column, which is what a GrB_Vector is inside GraphBLAS (GB_VECTOR_OK), so such a blob still gives that Vector. For the others, the message says what the blob holds instead ("data holds a 3x4 Matrix, not a Vector"), from a GxB_Matrix_fprint that runs only when the Vector check has failed. Such a blob is still read by deserialize_matrix, as a Vector blob is (as an n-by-1 Matrix). test_deserialize_vector_invalid changes the indices of a Vector blob in the three ways the Matrix test does, and test_deserialize_vector_of_a_matrix tries 3x4, 4x3, 3x1 and 1x3 Matrices, held by row and by column: deserialize_vector returned something for each. For 10M FP64 entries in a Vector of size 1e8, deserialize_vector took 0.009 s without the check and 0.080 s with it for every tenth entry, and 0.024 s and 0.157 s for entries in random places. --- suitesparse_graphblas/api/io/serialize.py | 28 ++++++++++++--- suitesparse_graphblas/tests/test_io.py | 42 +++++++++++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index ed32ac8..ffb9b3f 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -74,8 +74,8 @@ def _call_with_nthreads(nthreads, func, *args): lib.GxB_Context_free(ctx) -def _check_deserialized(obj, fprint, free, message): - """Free `obj` and raise InvalidObject(`message`) if `fprint` finds it invalid. +def _check_deserialized(obj, fprint, free, describe): + """Free `obj` and raise InvalidObject(`describe()`) if `fprint` finds it invalid. GraphBLAS checks only enough of a blob to deserialize it without reading past its end, so a corrupt blob can make an invalid object, and its User Guide says to check the result @@ -86,12 +86,24 @@ def _check_deserialized(obj, fprint, free, message): return try: if info == lib.GrB_INVALID_OBJECT: - raise InvalidObject(message) + raise InvalidObject(describe()) check_status(obj, info) finally: free(obj) +def _describe_invalid_vector(v): + # GxB_Vector_deserialize takes a Matrix blob too, and its Matrix makes an invalid Vector + # unless it is n-by-1 and held by column, as a Vector is + A = ffi.cast("GrB_Matrix", v[0]) + if lib.GxB_Matrix_fprint(A, b"", lib.GxB_SILENT, ffi.NULL) == lib.GrB_SUCCESS: + nrows, ncols = ffi.new("GrB_Index*"), ffi.new("GrB_Index*") + check_status(v, lib.GrB_Matrix_nrows(nrows, A)) + check_status(v, lib.GrB_Matrix_ncols(ncols, A)) + return f"data holds a {nrows[0]}x{ncols[0]} Matrix, not a Vector" + return "data does not hold a valid Vector: GxB_Vector_fprint rejects what it deserializes to" + + def get_serialize_desc(compression=lib.GxB_COMPRESSION_DEFAULT, level=None, nthreads=None): """Create a descriptor for serializing or deserializing. @@ -239,7 +251,8 @@ def deserialize_matrix(data, *, free=True, nthreads=None): A, lib.GxB_Matrix_fprint, lib.GrB_Matrix_free, - "data does not hold a valid Matrix: GxB_Matrix_fprint rejects what it deserializes to", + lambda: "data does not hold a valid Matrix: GxB_Matrix_fprint rejects what it " + "deserializes to", ) if free: if callable(free): @@ -268,6 +281,10 @@ def deserialize_vector(data, *, free=True, nthreads=None): that is more than int32_t holds, and InvalidValue if a Context is engaged on this thread (which stays engaged: set its number of threads instead). Raises TypeError if `nthreads` isn't an integer, or is a bool. + + Raises InvalidObject if `data` doesn't hold a valid Vector (GraphBLAS checks only that it + can read it), after freeing what it deserialized. A Matrix blob holds a valid Vector + only if the Matrix is n-by-1 and held by column. The check takes O(nvals) time. """ data = np.frombuffer(data, np.uint8) v = ffi.new("GrB_Vector*") @@ -281,6 +298,9 @@ def deserialize_vector(data, *, free=True, nthreads=None): ffi.NULL, ) check_status(v, info) + _check_deserialized( + v, lib.GxB_Vector_fprint, lib.GrB_Vector_free, lambda: _describe_invalid_vector(v) + ) if free: if callable(free): return ffi.gc(v, free) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 5efe2d6..1d286f4 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -823,6 +823,48 @@ def test_deserialize_matrix_invalid(case, nthreads): assert not _context_engaged(probe) +@pytest.mark.parametrize("nthreads", [None, 2]) +@pytest.mark.parametrize("case", _invalid_blob_indices) +def test_deserialize_vector_invalid(case, nthreads): + # As for deserialize_matrix: a Vector of size 1000 with entries 101, 202 and 303 + probe = context.context_new() + v = vector.vector_new(lib.GrB_INT64, 1000) + for k, (_, i) in enumerate(_blob_entries): + vector.set_int64(v, k, i) + blob = serialize.serialize_vector(v, lib.GxB_COMPRESSION_NONE).tobytes() + _assert_vectors_equal(v, serialize.deserialize_vector(blob, nthreads=nthreads)) + blob = _with_indices(blob, [i for _, i in _blob_entries], _invalid_blob_indices[case]) + with pytest.raises(InvalidObject, match="does not hold a valid Vector"): + serialize.deserialize_vector(blob, nthreads=nthreads) + assert not _context_engaged(probe) + + +@pytest.mark.parametrize("format", _formats, ids=_formats.get) +def test_deserialize_vector_of_a_matrix(format): + # A Vector is an n-by-1 Matrix held by column, and GxB_Vector_deserialize takes any + # Matrix blob, whose Matrix makes an invalid Vector unless it's one of those + for nrows, ncols in [(3, 4), (4, 3), (3, 1), (1, 3)]: + A = matrix.matrix_new(lib.GrB_INT64, nrows, ncols) + matrix.set_int64(A, 7, nrows - 1, ncols - 1) + matrix.matrix_set_format(A, format) + blob = serialize.serialize_matrix(A) + _assert_matrices_equal(A, serialize.deserialize_matrix(blob)) + if ncols == 1 and format == lib.GxB_BY_COL: + v = serialize.deserialize_vector(blob) + assert vector.vector_size(v) == nrows + assert vector.vector_extract_tuples_int64(v)[0].tolist() == [nrows - 1] + else: + message = f"data holds a {nrows}x{ncols} Matrix, not a Vector" + with pytest.raises(InvalidObject, match=message): + serialize.deserialize_vector(blob) + # And a Vector blob is an n-by-1 Matrix blob + v = vector.vector_new(lib.GrB_INT64, 5) + vector.set_int64(v, 7, 3) + A = serialize.deserialize_matrix(serialize.serialize_vector(v)) + assert matrix.matrix_shape(A) == (5, 1) + assert [x.tolist() for x in matrix.matrix_extract_tuples_int64(A)] == [[3], [0], [7]] + + def _context_engaged(probe): """Whether a GxB_Context is engaged on this thread. From 6a910e68b08c57b4fb623445e6aad6fb0bf377b3 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:50:59 -0600 Subject: [PATCH 14/17] Tests: import test_io.py's modules with the others test_io.py imported five of its modules last, marked `isort:skip`, because they came after the module-level skip on Windows, which is gone. Import them with the other imports from suitesparse_graphblas, and drop the two blank lines left where the skip was. --- suitesparse_graphblas/tests/test_io.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 1d286f4..3faf0c6 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -24,19 +24,17 @@ unsigned_integer_types, vector, ) +from suitesparse_graphblas.api import context +from suitesparse_graphblas.api.global_options import global_get_int32 +from suitesparse_graphblas.exceptions import InvalidObject, InvalidValue +from suitesparse_graphblas.io import binary, serialize +from suitesparse_graphblas.utils import claim_buffer try: import lzma except ImportError: # Pyodide before 314 has it as a separate package lzma = None - -from suitesparse_graphblas.api import context # isort:skip -from suitesparse_graphblas.api.global_options import global_get_int32 # isort:skip -from suitesparse_graphblas.exceptions import InvalidObject, InvalidValue # isort:skip -from suitesparse_graphblas.io import binary, serialize # isort:skip -from suitesparse_graphblas.utils import claim_buffer # isort:skip - NULL = ffi.NULL From 331c6211225becbd47f37538fc2370cb2e06f001 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:51:16 -0600 Subject: [PATCH 15/17] Tests: say which floats an int32 setting rejects The comments of test_set_int32_rejects_non_int32 said that a float is now a TypeError. That holds for a Python float, and so for np.float64, its subclass, which the test uses. cffi converts other objects with `__int__`, as it did through the cast before: np.float32(4.7), Decimal("4.7") and Fraction(47, 10) still set 4. Say so. --- suitesparse_graphblas/tests/test_api_objects.py | 5 +++-- suitesparse_graphblas/tests/test_api_ops.py | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/suitesparse_graphblas/tests/test_api_objects.py b/suitesparse_graphblas/tests/test_api_objects.py index d592fe7..0f6c1fe 100644 --- a/suitesparse_graphblas/tests/test_api_objects.py +++ b/suitesparse_graphblas/tests/test_api_objects.py @@ -268,8 +268,9 @@ def test_set_int32_rejects_non_int32(name): with pytest.raises(OverflowError): set_(wrapped) assert get() == old - # So is a float or a str, rather than truncated (4.7 would set 4) or taken as a - # character code ("3" would set 51) + # So is a Python float (or np.float64), rather than truncated (4.7 would set 4), and a + # str, rather than taken as a character code ("3" would set 51). (cffi converts other + # objects with `__int__`, such as np.float32, Decimal and Fraction, as it did before.) for wrong in (value + 0.7, "3"): with pytest.raises(TypeError): set_(wrong) diff --git a/suitesparse_graphblas/tests/test_api_ops.py b/suitesparse_graphblas/tests/test_api_ops.py index 97233ca..da1dd56 100644 --- a/suitesparse_graphblas/tests/test_api_ops.py +++ b/suitesparse_graphblas/tests/test_api_ops.py @@ -312,8 +312,8 @@ def test_set_int32_not_allowed(kind): @pytest.mark.parametrize("kind", list(MODULES)) def test_set_int32_rejects_non_int32(kind): # A value that doesn't fit in an int32 is an error, rather than wrapping around to one that - # does (and that GraphBLAS then rejects, here). So is a float or a str, rather than - # truncated or taken as a character code. + # does (and that GraphBLAS then rejects, here). So is a Python float (or np.float64) or a + # str, rather than truncated or taken as a character code. get_int32 = _func(kind, "get_int32") set_int32 = _func(kind, "set_int32") obj = _user_defined(kind) From f2962dba8ffe0160e7cf26a17a197fc8b220fb83 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:52:30 -0600 Subject: [PATCH 16/17] Tests: cover a deserialize check that fails with another error _check_deserialized raises InvalidObject when GxB_*_fprint calls the deserialized object invalid, and otherwise raises what check_status raises for the code, freeing the object either way. A deserialized object never gets another code, so test that path with an fprint that returns GrB_OUT_OF_MEMORY: it raises OutOfMemory and frees the Matrix. --- suitesparse_graphblas/tests/test_io.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 3faf0c6..9ed8e5e 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -26,7 +26,7 @@ ) from suitesparse_graphblas.api import context from suitesparse_graphblas.api.global_options import global_get_int32 -from suitesparse_graphblas.exceptions import InvalidObject, InvalidValue +from suitesparse_graphblas.exceptions import InvalidObject, InvalidValue, OutOfMemory from suitesparse_graphblas.io import binary, serialize from suitesparse_graphblas.utils import claim_buffer @@ -837,6 +837,19 @@ def test_deserialize_vector_invalid(case, nthreads): assert not _context_engaged(probe) +def test_check_deserialized_other_error(): + # A check that fails other than with GrB_INVALID_OBJECT (which a deserialized object + # doesn't do) raises as check_status does, and still frees the object + A = matrix.matrix_new(lib.GrB_INT64, 2, 2, free=None) + + def fprint(*args): + return lib.GrB_OUT_OF_MEMORY + + with pytest.raises(OutOfMemory): + serialize._check_deserialized(A, fprint, lib.GrB_Matrix_free, None) + assert A[0] == NULL + + @pytest.mark.parametrize("format", _formats, ids=_formats.get) def test_deserialize_vector_of_a_matrix(format): # A Vector is an n-by-1 Matrix held by column, and GxB_Vector_deserialize takes any From a4189c8b11cfe6a660cc919dcf5b732c80895569 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 22:55:18 -0600 Subject: [PATCH 17/17] Say what binread and deserialize check, and tidy their tests The docstrings of binread, deserialize_matrix and deserialize_vector said that a corrupt file or blob can't make an invalid object, in O(nvals) time. GraphBLAS's check is of the structure only (indices, pointers, the hypersparse list and the bitmap), and takes O(nvec + nvals) time, or O(nrows * ncols) for a bitmap. It doesn't look at the values: a GrB_BOOL value byte of 2 in a binread file loads as it is. Say so. The test of a corrupt compression level said that a float level now raises. That's a Python float (or np.float64): cffi converts other objects with `__int__`, so np.float32(1.5) still gives level 1. Say so too. In the tests, escape the version strings that test_binread_other_version matches (their dots matched any character), and import gc with the other modules rather than in a test. --- suitesparse_graphblas/api/io/binary.py | 5 +++-- suitesparse_graphblas/api/io/serialize.py | 13 ++++++++----- suitesparse_graphblas/tests/test_io.py | 11 ++++++----- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/suitesparse_graphblas/api/io/binary.py b/suitesparse_graphblas/api/io/binary.py index daa8a6f..2f1e9d8 100644 --- a/suitesparse_graphblas/api/io/binary.py +++ b/suitesparse_graphblas/api/io/binary.py @@ -409,8 +409,9 @@ def binread(filename, opener=Path.open): ``opener`` opens the file for reading (e.g. ``gzip.open``). The file must be from this version of SuiteSparse:GraphBLAS, else this raises ValueError. GraphBLAS checks the - matrix it holds (in O(nvals) time), so a corrupt file raises InvalidObject rather than - making an invalid matrix. + structure of the matrix it holds (its indices, pointers and bitmap), in O(nvec + nvals) + time, or O(nrows * ncols) for a bitmap, and this raises InvalidObject if that is + invalid. It doesn't check the values: a GrB_BOOL value of 2, say, is read as it is. """ if isinstance(filename, str): filename = Path(filename) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index ffb9b3f..bbff1d8 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -232,8 +232,10 @@ def deserialize_matrix(data, *, free=True, nthreads=None): thread (which stays engaged: set its number of threads instead). Raises TypeError if `nthreads` isn't an integer, or is a bool. - Raises InvalidObject if `data` doesn't hold a valid Matrix (GraphBLAS checks only that it - can read it), after freeing what it deserialized. The check takes O(nvals) time. + Raises InvalidObject, after freeing what it deserialized, if the structure of the Matrix + in `data` (its indices, pointers and bitmap) is invalid: GraphBLAS checks only that it can + read the blob. The check takes O(nvec + nvals) time, or O(nrows * ncols) for a bitmap. + It doesn't check the values. """ data = np.frombuffer(data, np.uint8) A = ffi.new("GrB_Matrix*") @@ -282,9 +284,10 @@ def deserialize_vector(data, *, free=True, nthreads=None): thread (which stays engaged: set its number of threads instead). Raises TypeError if `nthreads` isn't an integer, or is a bool. - Raises InvalidObject if `data` doesn't hold a valid Vector (GraphBLAS checks only that it - can read it), after freeing what it deserialized. A Matrix blob holds a valid Vector - only if the Matrix is n-by-1 and held by column. The check takes O(nvals) time. + Raises InvalidObject, after freeing what it deserialized, if the structure of the Vector + in `data` (its indices and bitmap) is invalid: GraphBLAS checks only that it can read the + blob. A Matrix blob holds a valid Vector only if the Matrix is n-by-1 and held by column. + The check takes O(nvals) time, or O(size) for a bitmap. It doesn't check the values. """ data = np.frombuffer(data, np.uint8) v = ffi.new("GrB_Vector*") diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 9ed8e5e..d2f936d 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -1,7 +1,9 @@ import bz2 import collections import functools +import gc import gzip +import re import struct import sys from contextlib import contextmanager @@ -509,8 +511,6 @@ def test_binread_invalid_matrix_frees_only_its_own(tmp_path): # nothing else. (When GraphBLAS checked the matrix as it packed it, a failed check freed # the matrix itself, and binread's handle to it was left to free whatever matrix came to # use its memory next.) - import gc - path = tmp_path / "matrix.binfile" _invalid_binfile(path, lib.GxB_BY_ROW, "index out of range") with pytest.raises(InvalidObject) as excinfo: @@ -542,8 +542,8 @@ def test_binread_other_version(tmp_path): ]: struct.pack_into("=Q", data, binary.GRB_HEADER_LEN, version) path.write_bytes(data) - message = f"SuiteSparse:GraphBLAS {major}.{minor}.{sub}: its version is {name}$" - with pytest.raises(ValueError, match=message): + message = f"SuiteSparse:GraphBLAS {major}.{minor}.{sub}: its version is {name}" + with pytest.raises(ValueError, match=re.escape(message) + "$"): binary.binread(path) @@ -708,7 +708,8 @@ def __getattr__(self, name): def test_serialize_compression_out_of_range(monkeypatch, kind): # The method plus the level goes to GraphBLAS as an int32_t. It used to wrap around, so # ZSTD with level 2**32 + 1 serialized with level 1, and a float level was truncated. - # Now they raise, before anything is serialized. + # Now they raise, before anything is serialized. (Only a Python float, or np.float64: + # cffi converts other objects with `__int__`, so np.float32(1.5) still gives level 1.) if kind == "matrix": A, ser, T = _numbered_matrix(10), serialize.serialize_matrix, "Matrix" else: