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/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/io/binary.py b/suitesparse_graphblas/api/io/binary.py index 5265d21..2f1e9d8 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,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. @@ -74,7 +80,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): @@ -244,7 +251,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") @@ -400,7 +407,11 @@ 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. GraphBLAS checks the + 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) @@ -416,8 +427,11 @@ 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"{_version(lib.GxB_IMPLEMENTATION)}: its version is {_version(impl[0])}" + ) format = frombuff("GxB_Format_Value*", fread(sizeof("GxB_Format_Value"))) sparsity_status = frombuff("int32_t*", fread(sizeof("int32_t"))) @@ -487,7 +501,8 @@ def read(nbytes, ctype): read(typesize[0] if is_iso[0] else nx * typesize[0], "void*") # Ax with ExitStack() as stack: - # The buffers become GraphBLAS's only if the pack succeeds + # 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 @@ -496,6 +511,16 @@ def read(nbytes, ctype): sizes = [nbytes for _, nbytes, _ in given] 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]) matrix.matrix_set_bitmap_switch(A, bitmap_switch[0]) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index 1d9e114..bbff1d8 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,36 @@ def _call_with_nthreads(nthreads, func, *args): lib.GxB_Context_free(ctx) +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 + 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(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. @@ -110,10 +140,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 @@ -203,6 +231,11 @@ 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, 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*") @@ -216,6 +249,13 @@ 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, + lambda: "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) @@ -243,6 +283,11 @@ 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, 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*") @@ -256,6 +301,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/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/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/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..0f6c1fe 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,125 @@ 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 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) + 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..da1dd56 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 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) + 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"), [ @@ -361,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) 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 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) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index c5b3de9..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 platform +import re import struct import sys from contextlib import contextmanager @@ -24,21 +26,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, OutOfMemory +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 -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 -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 @@ -428,6 +426,143 @@ 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 _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 `_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, 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 + 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) +_bitmap = [1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1] +_invalid_arrays = { + "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"} + + +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) + + +@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.) + 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): + # 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()) + # 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=re.escape(message) + "$"): + 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 @@ -557,6 +692,51 @@ 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. (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: + 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 @@ -603,6 +783,100 @@ 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) + + +@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) + + +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 + # 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. 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