Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
cb20e2c
Raise OverflowError for int32 settings that don't fit, not wrap around
eriknw Nov 26, 2026
45b2eec
binread: check the file's GraphBLAS version with a ValueError, not as…
eriknw Nov 26, 2026
0dd132c
binread: have GraphBLAS check the matrix in the file
eriknw Nov 26, 2026
34f4742
initialize: raise GraphBLASException for an unknown failure code
eriknw Nov 26, 2026
e3920a4
binwrite: leave the comment line empty when there are no comments
eriknw Nov 26, 2026
d168a52
Tests: run test_io.py and binread's memory check on Windows too
eriknw Nov 26, 2026
d952f52
_capture_c_output: capture into a temporary file, not a pipe
eriknw Nov 26, 2026
4e0bd4a
binread: check the matrix after packing it, not with a secure pack
eriknw Nov 26, 2026
410dc00
binread: name the file's GraphBLAS version as major.minor.sub
eriknw Nov 26, 2026
60c5b77
Tests: drop a comment about the pipe _capture_c_output no longer uses
eriknw Nov 26, 2026
3509135
serialize: raise OverflowError for a compression that doesn't fit int…
eriknw Nov 26, 2026
300b36d
serialize: check the Matrix that deserialize_matrix makes
eriknw Nov 26, 2026
2cc06f6
serialize: check the Vector that deserialize_vector makes
eriknw Nov 26, 2026
6a910e6
Tests: import test_io.py's modules with the others
eriknw Nov 26, 2026
331c621
Tests: say which floats an int32 setting rejects
eriknw Nov 26, 2026
f2962db
Tests: cover a deserialize check that fails with another error
eriknw Nov 26, 2026
a4189c8
Say what binread and deserialize check, and tidy their tests
eriknw Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions suitesparse_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/binaryop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
)
Expand Down
4 changes: 2 additions & 2 deletions suitesparse_graphblas/api/global_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down Expand Up @@ -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}"
Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/grb_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/indexbinaryop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/indexunaryop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
37 changes: 31 additions & 6 deletions suitesparse_graphblas/api/io/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -67,14 +68,20 @@
_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.

``opener`` opens the file for writing (e.g. ``gzip.open`` to compress it). To avoid a
copy, ``A`` is unpacked while it is written and packed again afterwards (even if writing
fails), so other threads must not use ``A`` meanwhile.

``comments`` must be ASCII, and short enough that the text header fits in
``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):
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand All @@ -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")))
Expand Down Expand Up @@ -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
Expand All @@ -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])
Expand Down
58 changes: 53 additions & 5 deletions suitesparse_graphblas/api/io/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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*")
Expand All @@ -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)
Expand Down Expand Up @@ -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*")
Expand All @@ -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)
Expand Down
10 changes: 3 additions & 7 deletions suitesparse_graphblas/api/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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):
Expand Down Expand Up @@ -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,
),
)

Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/monoid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/semiring.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/unaryop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
20 changes: 8 additions & 12 deletions suitesparse_graphblas/api/utils.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 1 addition & 1 deletion suitesparse_graphblas/api/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
)

Expand Down
Loading
Loading