From 3dbd03e60704e4219deca0dcab6182e924f2d60f Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:07:14 -0600 Subject: [PATCH 1/9] serialize: set nthreads in a GxB_Context, not a descriptor serialize_matrix and serialize_vector set nthreads with GxB_Desc_set_INT32(desc, GxB_NTHREADS, ...), which GraphBLAS 10 rejects with GrB_INVALID_VALUE: the number of threads is a Context setting now. deserialize_matrix and deserialize_vector passed nthreads to get_serialize_desc as its `level`, so they ignored it. All four now make the GraphBLAS call under a new GxB_Context with GxB_CONTEXT_NTHREADS set, and disengage and free it afterwards, also on error. The Context is given the global header and data arenas, which GxB_Context_new leaves at arena 0; without them, deserialize would put its result in arena 0. None, 0 or negative nthreads means the default, as it did for a descriptor in GraphBLAS 7, and does no Context work at all. Any other value must be an integer (TypeError) that fits in int32_t (OverflowError). GraphBLAS can't say which Context is engaged on a thread, so a Context that the caller engaged couldn't be engaged again after the call. It can say whether there is one: disengaging a Context that isn't engaged fails with GrB_INVALID_VALUE if another one is, and changes nothing. So a positive nthreads raises InvalidValue while a Context is engaged, and that Context stays engaged. The strict xfail test_serialize_nthreads becomes a test that serializing with nthreads gives the same bytes as serializing under an engaged Context with that many threads, and that one thread and two give different bytes (GraphBLAS compresses each array as a single block when it uses one thread). Other tests check that None, 0 and -1 use the engaged Context or else GxB_CONTEXT_WORLD; that the caller's Context is refused and stays engaged; the TypeError and OverflowError; that no Context is left engaged, also after an error; and that deserialize with nthreads puts its result in the global arenas. How many threads deserialize uses doesn't show in its result. Before the fix, 12 of the 14 new cases fail. The other two, of the arenas, pass then because deserialize ignored nthreads. --- suitesparse_graphblas/api/io/serialize.py | 132 +++++++++++--- suitesparse_graphblas/tests/test_io.py | 200 ++++++++++++++++++++-- 2 files changed, 296 insertions(+), 36 deletions(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index c6aefde..81d434d 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -1,7 +1,17 @@ +import operator +from contextlib import contextmanager + import numpy as np from suitesparse_graphblas import check_status, ffi, lib +from suitesparse_graphblas.api.context import ( + context_disengage, + context_engage, + context_free, + context_new, +) from suitesparse_graphblas.api.global_options import global_get_int32 +from suitesparse_graphblas.exceptions import InvalidValue from suitesparse_graphblas.utils import claim_buffer @@ -11,10 +21,57 @@ def _free_desc(desc): lib.GrB_Descriptor_free(desc_ptr) +@contextmanager +def _nthreads_context(nthreads): + """Engage a new GxB_Context that uses at most `nthreads` threads, for the body. + + GraphBLAS 10 takes the number of threads from the Context engaged on the calling thread, + not from a descriptor. Apart from the number of threads, the new Context is a copy of + GxB_CONTEXT_WORLD: GxB_Context_new copies its chunk and GPUs, and the arenas are copied + here, since they would otherwise be arena 0. Nothing is done if `nthreads` is None, 0 or + negative. + """ + if nthreads is not None: + nthreads = operator.index(nthreads) # TypeError if it isn't an integer + if nthreads is None or nthreads <= 0: + yield + return + ctx = context_new(free=None) + try: + # A Context engaged on this thread would be lost: GraphBLAS can't say which one it + # is, so it can't be engaged again afterwards. But it can say whether there is one: + # disengaging a Context that isn't engaged fails with GrB_INVALID_VALUE if another + # one is, and changes nothing. + info = lib.GxB_Context_disengage(ctx[0]) + if info == lib.GrB_INVALID_VALUE: + raise InvalidValue( + "nthreads can't be given while a GxB_Context is engaged on this thread; " + "set GxB_CONTEXT_NTHREADS of that Context instead" + ) + check_status(ctx, info) + # OverflowError if `nthreads` doesn't fit in int32_t + check_status(ctx, lib.GxB_Context_set_INT(ctx[0], nthreads, lib.GxB_CONTEXT_NTHREADS)) + header_arena = global_get_int32(lib.GxB_ARENA_HEADER) + check_status(ctx, lib.GxB_Context_set_INT(ctx[0], header_arena, lib.GxB_ARENA_HEADER)) + data_arena = global_get_int32(lib.GxB_ARENA_DATA) + check_status(ctx, lib.GxB_Context_set_INT(ctx[0], data_arena, lib.GxB_ARENA_DATA)) + context_engage(ctx) + try: + yield + finally: + context_disengage(ctx) + finally: + context_free(ctx) + + def get_serialize_desc(compression=lib.GxB_COMPRESSION_DEFAULT, level=None, nthreads=None): """Create a descriptor for serializing or deserializing. This returns None (for NULL descriptor) or a GrB_Descriptor. + + The number of threads isn't a descriptor setting in GraphBLAS 10, which raises + InvalidValue if `nthreads` is given. The `nthreads` argument of the functions that + serialize and deserialize sets it in a GxB_Context instead. """ if nthreads is None and (compression is None or compression == lib.GxB_COMPRESSION_DEFAULT): return None @@ -50,18 +107,25 @@ def serialize_matrix(A, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *, level : int, optional For GxB_COMPRESSION_LZ4HC, should be between 1 and 9, where 9 is most compressed. For GxB_COMPRESSION_ZSTD, should be between 1 and 19, where 19 is most compressed. - nthreads : int, optional - The maximum number of OpenMP threads to use. + The maximum number of OpenMP threads to use. None (the default), 0 or negative + means the number of threads of the GxB_Context engaged on this thread, if any, or + else of GxB_CONTEXT_WORLD. A positive number makes the call run under a new + Context with that many threads, so it raises 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, OverflowError if it doesn't fit + in int32_t. """ - desc = get_serialize_desc(compression, level, nthreads) + desc = get_serialize_desc(compression, level) data_ptr = ffi.new("void**") size_ptr = ffi.new("GrB_Index*") # Name the arena for the result, which is otherwise that of the engaged Context (if # any), so that `claim_buffer` knows which allocator must free it arena = global_get_int32(lib.GxB_ARENA_DATA) desc = ffi.NULL if desc is None else desc - check_status(A, lib.GxB_Matrix_serialize_arena(data_ptr, size_ptr, A[0], arena, desc)) + with _nthreads_context(nthreads): + info = lib.GxB_Matrix_serialize_arena(data_ptr, size_ptr, A[0], arena, desc) + check_status(A, info) return claim_buffer(ffi, data_ptr[0], size_ptr[0], np.dtype(np.uint8), arena) @@ -77,14 +141,22 @@ def serialize_vector(v, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *, For GxB_COMPRESSION_LZ4HC, should be between 1 and 9, where 9 is most compressed. For GxB_COMPRESSION_ZSTD, should be between 1 and 19, where 19 is most compressed. nthreads : int, optional - The maximum number of OpenMP threads to use. + The maximum number of OpenMP threads to use. None (the default), 0 or negative + means the number of threads of the GxB_Context engaged on this thread, if any, or + else of GxB_CONTEXT_WORLD. A positive number makes the call run under a new + Context with that many threads, so it raises 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, OverflowError if it doesn't fit + in int32_t. """ - desc = get_serialize_desc(compression, level, nthreads) + desc = get_serialize_desc(compression, level) data_ptr = ffi.new("void**") size_ptr = ffi.new("GrB_Index*") arena = global_get_int32(lib.GxB_ARENA_DATA) # see `serialize_matrix` desc = ffi.NULL if desc is None else desc - check_status(v, lib.GxB_Vector_serialize_arena(data_ptr, size_ptr, v[0], arena, desc)) + with _nthreads_context(nthreads): + info = lib.GxB_Vector_serialize_arena(data_ptr, size_ptr, v[0], arena, desc) + check_status(v, info) return claim_buffer(ffi, data_ptr[0], size_ptr[0], np.dtype(np.uint8), arena) @@ -95,20 +167,29 @@ def deserialize_matrix(data, *, free=True, nthreads=None): collected, the default is `matrix.matrix_free()`. If `free` is None then there is no automatic garbage collection and it is up to the user to free the matrix. + + Parameters + ---------- + nthreads : int, optional + The maximum number of OpenMP threads to use. None (the default), 0 or negative + means the number of threads of the GxB_Context engaged on this thread, if any, or + else of GxB_CONTEXT_WORLD. A positive number makes the call run under a new + Context with that many threads, so it raises 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, OverflowError if it doesn't fit + in int32_t. """ data = np.frombuffer(data, np.uint8) - desc = get_serialize_desc(None, nthreads) A = ffi.new("GrB_Matrix*") - check_status( - A, - lib.GxB_Matrix_deserialize( + with _nthreads_context(nthreads): + info = lib.GxB_Matrix_deserialize( A, ffi.NULL, # dtype; we don't check for now ffi.from_buffer("void*", data), data.nbytes, - ffi.NULL if desc is None else desc, - ), - ) + ffi.NULL, + ) + check_status(A, info) if free: if callable(free): return ffi.gc(A, free) @@ -123,20 +204,29 @@ def deserialize_vector(data, *, free=True, nthreads=None): collected, the default is `vector.vector_free()`. If `free` is None then there is no automatic garbage collection and it is up to the user to free the vector. + + Parameters + ---------- + nthreads : int, optional + The maximum number of OpenMP threads to use. None (the default), 0 or negative + means the number of threads of the GxB_Context engaged on this thread, if any, or + else of GxB_CONTEXT_WORLD. A positive number makes the call run under a new + Context with that many threads, so it raises 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, OverflowError if it doesn't fit + in int32_t. """ data = np.frombuffer(data, np.uint8) - desc = get_serialize_desc(None, nthreads) v = ffi.new("GrB_Vector*") - check_status( - v, - lib.GxB_Vector_deserialize( + with _nthreads_context(nthreads): + info = lib.GxB_Vector_deserialize( v, ffi.NULL, # dtype; we don't check for now ffi.from_buffer("void*", data), data.nbytes, - ffi.NULL if desc is None else desc, - ), - ) + ffi.NULL, + ) + check_status(v, info) 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 00507ce..2825228 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -1,7 +1,9 @@ import bz2 +import functools import gzip import platform import struct +from contextlib import contextmanager from pathlib import Path import numpy as np @@ -30,6 +32,8 @@ 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 @@ -463,6 +467,9 @@ def test_get_serialize_desc(): assert _compression(get(LZ4HC, 9)) == LZ4HC + 9 assert _compression(get(lib.GxB_COMPRESSION_LZ4, 9)) == lib.GxB_COMPRESSION_LZ4 assert _compression(get(lib.GxB_COMPRESSION_NONE, 9)) == lib.GxB_COMPRESSION_NONE + # The number of threads is a Context setting in GraphBLAS 10, not a descriptor setting + with pytest.raises(InvalidValue): + get(nthreads=1) _serialize_options = { @@ -585,20 +592,183 @@ def test_deserialize_invalid(): deserialize(bytes(64)) -@pytest.mark.xfail( - strict=True, - raises=InvalidValue, - reason="serialize sets nthreads on a descriptor, which GraphBLAS 10 rejects with " - "GrB_INVALID_VALUE: the number of threads is a GxB_Context setting now", -) +def _context_engaged(probe): + """Whether a GxB_Context is engaged on this thread. + + GraphBLAS can't say which one, but disengaging a Context that isn't engaged, `probe`, + fails with GrB_INVALID_VALUE if another one is, and changes nothing. Make `probe` before + the Contexts it looks for: one freed while engaged (a bug) stays the engaged Context, and + a probe made later could be given its address. + """ + info = lib.GxB_Context_disengage(probe[0]) + assert info in {lib.GrB_SUCCESS, lib.GrB_INVALID_VALUE} + return info == lib.GrB_INVALID_VALUE + + +@contextmanager +def _engaged(nthreads): + """Engage a new Context that uses `nthreads` threads on this thread.""" + ctx = context.context_new() + context.context_set_nthreads(ctx, nthreads) + context.context_engage(ctx) + try: + yield + finally: + context.context_disengage(ctx) + + +def _assert_vectors_equal(v, w): + assert vector.vector_type(w) == vector.vector_type(v) + assert vector.vector_size(w) == vector.vector_size(v) + for x, y in zip( + vector.vector_extract_tuples_int64(v), vector.vector_extract_tuples_int64(w), strict=True + ): + np.testing.assert_array_equal(x, y) + + +def _big(kind): + """A Matrix or Vector whose blob shows how many threads serialized it. + + Returns the object, the functions that serialize and deserialize it, and one that asserts + that two of them are equal. GraphBLAS compresses an array as a single block if it uses + one thread, and as blocks of at least 64 KiB if it uses more (see GB_serialize_array.c). + It uses one thread for each GxB_CHUNK bytes (64 KiB by default), up to the number of + threads of the Context, and the 512 KiB of values here are enough for several. + """ + if kind == "matrix": + A = _numbered_matrix(256) + return A, serialize.serialize_matrix, serialize.deserialize_matrix, _assert_matrices_equal + n = 256 * 256 + v = vector.vector_new(lib.GrB_INT64, n) + indices = np.arange(n, dtype=np.uint64) + vector.vector_build_int64(v, indices, np.arange(n, dtype=np.int64), n, lib.GrB_PLUS_INT64) + return v, serialize.serialize_vector, serialize.deserialize_vector, _assert_vectors_equal + + @pytest.mark.parametrize("kind", ["matrix", "vector"]) def test_serialize_nthreads(kind): - if kind == "matrix": - A = _make_matrix(lib.GrB_INT64, "sparse") - B = serialize.deserialize_matrix(serialize.serialize_matrix(A, nthreads=1), nthreads=1) - _assert_matrices_equal(A, B) - else: - v = vector.vector_new(lib.GrB_INT64, 3) - vector.set_int64(v, 7, 2) - w = serialize.deserialize_vector(serialize.serialize_vector(v, nthreads=1), nthreads=1) - assert vector.vector_nvals(w) == 1 + # GraphBLAS 10 rejects the number of threads in a descriptor: it's a Context setting. + # Serializing with `nthreads` gives what serializing under a Context with that many + # threads gives, and one thread gives a different result from two. + probe = context.context_new() + A, ser, deser, assert_equal = _big(kind) + blobs = {} + for nthreads in (1, 2): + with _engaged(nthreads): + expected = ser(A).tobytes() + blobs[nthreads] = ser(A, nthreads=nthreads).tobytes() + assert blobs[nthreads] == expected + assert blobs[1] != blobs[2] + assert ser(A, nthreads=np.int64(2)).tobytes() == blobs[2] # any kind of integer will do + # How many threads deserialize uses doesn't show in its result + for blob in blobs.values(): + for nthreads in (1, 2): + assert_equal(A, deser(blob, nthreads=nthreads)) + assert not _context_engaged(probe) + + +@pytest.mark.parametrize("nthreads", [None, 0, -1]) +@pytest.mark.parametrize("kind", ["matrix", "vector"]) +def test_serialize_nthreads_default(kind, nthreads): + # These use the Context engaged on this thread, if any, or else GxB_CONTEXT_WORLD + probe = context.context_new() + A, ser, deser, assert_equal = _big(kind) + blob = ser(A).tobytes() + assert ser(A, nthreads=nthreads).tobytes() == blob + assert_equal(A, deser(blob, nthreads=nthreads)) + expected = {engaged: ser(A, nthreads=engaged).tobytes() for engaged in (1, 2)} + for engaged in (1, 2): + with _engaged(engaged): + assert ser(A, nthreads=nthreads).tobytes() == expected[engaged] + assert_equal(A, deser(blob, nthreads=nthreads)) + assert _context_engaged(probe) + assert not _context_engaged(probe) + + +@pytest.mark.parametrize("kind", ["matrix", "vector"]) +def test_serialize_nthreads_with_engaged_context(kind): + # GraphBLAS can't say which Context is engaged on this thread, so a call that engaged + # its own for `nthreads` couldn't engage that one again afterwards. It refuses instead, + # and the caller's Context stays engaged. + probe = context.context_new() + A, ser, deser, assert_equal = _big(kind) + blob = ser(A) + ctx = context.context_new() + context.context_engage(ctx) + try: + for call in (lambda: ser(A, nthreads=2), lambda: deser(blob, nthreads=2)): + with pytest.raises(InvalidValue, match="engaged on this thread"): + call() + assert _context_engaged(probe) + # ...and it's `ctx`: disengaging it fails if another Context is engaged + context.context_disengage(ctx) + assert not _context_engaged(probe) + finally: + lib.GxB_Context_disengage(NULL) # whichever is engaged, if the test failed + + +@pytest.mark.parametrize("kind", ["matrix", "vector"]) +def test_serialize_nthreads_invalid(kind): + probe = context.context_new() + A, ser, deser, assert_equal = _big(kind) + blob = ser(A) + for call in (lambda n: ser(A, nthreads=n), lambda n: deser(blob, nthreads=n)): + for nthreads in (2.0, 0.0, "2"): # not even 0.0, which would mean the default + with pytest.raises(TypeError): + call(nthreads) + with pytest.raises(OverflowError): + call(2**31) # more than int32_t holds + assert not _context_engaged(probe) + # Nor do failures. This one is while the Context is engaged. + other = vector.vector_new(lib.GrB_INT64) if kind == "matrix" else _numbered_matrix(2) + with pytest.raises(TypeError): + ser(other, nthreads=2) # the wrong kind of object + assert not _context_engaged(probe) + with pytest.raises(InvalidObject): + deser(bytes(64), nthreads=2) + assert not _context_engaged(probe) + + +@functools.cache +def _arena_like_0(): + """Arena 1, which allocates as arena 0 does. It's made once: arenas can't be changed. + + Other tests that run in this process keep arena 5 uninitialized (test_can_unclaim_buffer) + and use arena 6 (`recording_arena` in test_memory.py). + """ + k = 1 + malloc, free = ffi.new("void**"), ffi.new("void**") + info = lib.GrB_Global_get_VOID(lib.GrB_GLOBAL, malloc, lib.GxB_ARENA_MALLOC) + assert info == lib.GrB_SUCCESS + info = lib.GrB_Global_get_VOID(lib.GrB_GLOBAL, free, lib.GxB_ARENA_FREE) + assert info == lib.GrB_SUCCESS + malloc = ffi.cast("void *(*)(size_t)", malloc[0]) + free = ffi.cast("void (*)(void *)", free[0]) + assert lib.GxB_arena_init(k, malloc, NULL, NULL, free) == lib.GrB_SUCCESS + return k + + +@pytest.mark.thread_unsafe(reason="changes the global header and data arenas") +@pytest.mark.parametrize("kind", ["matrix", "vector"]) +def test_deserialize_nthreads_arenas(kind): + # The result is in the global arenas with or without `nthreads`. A new Context has arena + # 0 for both, so the one that `nthreads` engages is given the global arenas. + A, ser, deser, assert_equal = _big(kind) + blob = ser(A) + get = lib.GrB_Matrix_get_INT32 if kind == "matrix" else lib.GrB_Vector_get_INT32 + fields = (lib.GxB_ARENA_HEADER, lib.GxB_ARENA_DATA) + k = _arena_like_0() + old = [global_get_int32(field) for field in fields] + try: + for field in fields: + assert lib.GrB_Global_set_INT32(lib.GrB_GLOBAL, k, field) == lib.GrB_SUCCESS + for nthreads in (None, 2): + B = deser(blob, nthreads=nthreads) + arena = ffi.new("int32_t*") + for field in fields: + check_status(B, get(B[0], arena, field)) + assert arena[0] == k + assert_equal(A, B) + finally: + for field, value in zip(fields, old, strict=True): + assert lib.GrB_Global_set_INT32(lib.GrB_GLOBAL, value, field) == lib.GrB_SUCCESS From cfde1201814730290fcce898b6c992b1224dd6ff Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:11:43 -0600 Subject: [PATCH 2/9] serialize: skip the context manager when nthreads is the default _nthreads_context was a generator context manager, which costs about 0.3 us to enter and leave even when it does nothing. With the default nthreads=None, that made serialize_vector 40% slower and deserialize_vector 70% slower on a small Vector. Now it returns a single shared nullcontext in that case (a nullcontext keeps no state), and the generator only when it engages a Context. Measured on a 3-element Vector with CPython 3.15.2 on macOS arm64: serialize_vector took 0.89 us before nthreads support and 1.24 us with the generator, deserialize_vector 0.65 and 1.12 us. With this change, a later run measured 0.94 and 0.69 us, against 0.83 and 0.68 us before nthreads support. --- suitesparse_graphblas/api/io/serialize.py | 29 ++++++++++++++++------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index 81d434d..7908a26 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -1,5 +1,5 @@ import operator -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext import numpy as np @@ -21,21 +21,32 @@ def _free_desc(desc): lib.GrB_Descriptor_free(desc_ptr) -@contextmanager +_NO_CONTEXT = nullcontext() # it keeps no state, so it serves every call and thread + + def _nthreads_context(nthreads): - """Engage a new GxB_Context that uses at most `nthreads` threads, for the body. + """Return a context manager that engages a new GxB_Context with `nthreads` threads. GraphBLAS 10 takes the number of threads from the Context engaged on the calling thread, - not from a descriptor. Apart from the number of threads, the new Context is a copy of - GxB_CONTEXT_WORLD: GxB_Context_new copies its chunk and GPUs, and the arenas are copied - here, since they would otherwise be arena 0. Nothing is done if `nthreads` is None, 0 or - negative. + not from a descriptor. If `nthreads` is None, 0 or negative, the context manager does + nothing. """ if nthreads is not None: nthreads = operator.index(nthreads) # TypeError if it isn't an integer if nthreads is None or nthreads <= 0: - yield - return + return _NO_CONTEXT + return _engaged_context(nthreads) + + +@contextmanager +def _engaged_context(nthreads): + """Engage a new GxB_Context that uses at most `nthreads` threads, for the body. + + Apart from the number of threads, the new Context is a copy of GxB_CONTEXT_WORLD: + GxB_Context_new copies its chunk and GPUs, and the arenas are copied here, since they + would otherwise be arena 0. WORLD is the Context the call would use without `nthreads`, + because a Context engaged on this thread makes this raise. + """ ctx = context_new(free=None) try: # A Context engaged on this thread would be lost: GraphBLAS can't say which one it From 2c53eccb970a81f6045510eb5f56340845e66337 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:23:43 -0600 Subject: [PATCH 3/9] serialize: deprecate the nthreads argument of get_serialize_desc GraphBLAS 10 has no descriptor setting for the number of threads, so get_serialize_desc(nthreads=...) always raises InvalidValue. The functions that serialize and deserialize no longer pass it: their own nthreads argument sets it in a GxB_Context. Giving it now also emits a DeprecationWarning that names those functions, and otherwise behaves as before. test_get_serialize_desc_nthreads_deprecated checks the warning, that it points at the caller (stacklevel=2), and that InvalidValue is still raised, with and without compression. Before this change it fails because no warning is emitted. No other test or doctest passes nthreads to get_serialize_desc, so none of them sees the warning, which pytest would turn into an error. --- suitesparse_graphblas/api/io/serialize.py | 18 +++++++++++++++--- suitesparse_graphblas/tests/test_io.py | 15 ++++++++++++--- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index 7908a26..8d0bc70 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -1,4 +1,5 @@ import operator +import warnings from contextlib import contextmanager, nullcontext import numpy as np @@ -80,10 +81,21 @@ def get_serialize_desc(compression=lib.GxB_COMPRESSION_DEFAULT, level=None, nthr This returns None (for NULL descriptor) or a GrB_Descriptor. - The number of threads isn't a descriptor setting in GraphBLAS 10, which raises - InvalidValue if `nthreads` is given. The `nthreads` argument of the functions that - serialize and deserialize sets it in a GxB_Context instead. + .. deprecated:: 10.5.3.0 + The `nthreads` argument. The number of threads isn't a descriptor setting in + GraphBLAS 10, which raises InvalidValue if `nthreads` is given. Use the `nthreads` + argument of serialize_matrix, serialize_vector, deserialize_matrix or + deserialize_vector instead, which sets it in a GxB_Context. """ + if nthreads is not None: + warnings.warn( + "The `nthreads` argument of get_serialize_desc is deprecated: GraphBLAS 10 " + "rejects the number of threads in a descriptor. Use the `nthreads` argument " + "of serialize_matrix, serialize_vector, deserialize_matrix or " + "deserialize_vector instead.", + DeprecationWarning, + stacklevel=2, + ) if nthreads is None and (compression is None or compression == lib.GxB_COMPRESSION_DEFAULT): return None desc_ptr = ffi.new("GrB_Descriptor*") diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 2825228..bb4ac56 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -467,9 +467,18 @@ def test_get_serialize_desc(): assert _compression(get(LZ4HC, 9)) == LZ4HC + 9 assert _compression(get(lib.GxB_COMPRESSION_LZ4, 9)) == lib.GxB_COMPRESSION_LZ4 assert _compression(get(lib.GxB_COMPRESSION_NONE, 9)) == lib.GxB_COMPRESSION_NONE - # The number of threads is a Context setting in GraphBLAS 10, not a descriptor setting - with pytest.raises(InvalidValue): - get(nthreads=1) + + +@pytest.mark.parametrize( + "compression", [lib.GxB_COMPRESSION_DEFAULT, None], ids=["default", "None"] +) +def test_get_serialize_desc_nthreads_deprecated(compression): + # The number of threads is a Context setting in GraphBLAS 10, not a descriptor setting. + # The warning names the replacement and the caller, and GraphBLAS still rejects it. + with pytest.warns(DeprecationWarning, match="serialize_matrix") as record: + with pytest.raises(InvalidValue): + serialize.get_serialize_desc(compression, nthreads=1) + assert [w.filename for w in record] == [__file__] _serialize_options = { From 0a3f5c97f8254a6993318fabfadbdd38684fa855 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:35:09 -0600 Subject: [PATCH 4/9] serialize: engage the nthreads Context in the calling frame The Context for nthreads was engaged by a generator context manager. A KeyboardInterrupt can come as its __exit__ begins, before the generator resumes, and then the Context stays engaged until garbage collection closes the generator: on CPython while the exception unwinds, on PyPy later and perhaps in another thread, which leaves the Context engaged where it was, or freed while still engaged. Now _call_with_nthreads(nthreads, func, *args) makes the Context, engages it, calls func and disengages and frees it, all in one frame. With no Context to make, it just returns func(*args). One `finally` isn't enough on PyPy, which can deliver the KeyboardInterrupt at the first bytecode of the `finally` block. So the inner `finally` disengages the Context, and the outer one disengages it again before freeing it. Disengaging a Context that isn't engaged changes nothing, including when another Context is engaged. The Context is made before the outer `try`, so an interrupt there only leaks it, unengaged. Measured with _thread.interrupt_main() at random moments during serialize_vector and deserialize_vector with nthreads=2, counting the interrupts after which a Context was still engaged: - generator: CPython 211 of 33690, PyPy 5 of 1164; - one disengage, in the inner or the outer `finally`: CPython 0 of 25978 and 0 of 27929, PyPy 5 of 138 and 4 of 178; - both: CPython 0 of 32742, PyPy 0 of 169, and 0 of 595 in a longer run. test_call_with_nthreads_interrupted raises KeyboardInterrupt from the call. test_call_with_nthreads_interrupted_in_finally raises it at the start of each `finally` block, from a stand-in for `lib` whose second or third lookup of GxB_Context_disengage raises. Each test checks that no Context is left engaged. The second one fails if either disengage is removed. --- suitesparse_graphblas/api/io/serialize.py | 98 +++++++++++------------ suitesparse_graphblas/tests/test_io.py | 45 +++++++++++ 2 files changed, 93 insertions(+), 50 deletions(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index 8d0bc70..d19dfa0 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -1,16 +1,9 @@ import operator import warnings -from contextlib import contextmanager, nullcontext import numpy as np from suitesparse_graphblas import check_status, ffi, lib -from suitesparse_graphblas.api.context import ( - context_disengage, - context_engage, - context_free, - context_new, -) from suitesparse_graphblas.api.global_options import global_get_int32 from suitesparse_graphblas.exceptions import InvalidValue from suitesparse_graphblas.utils import claim_buffer @@ -22,33 +15,29 @@ def _free_desc(desc): lib.GrB_Descriptor_free(desc_ptr) -_NO_CONTEXT = nullcontext() # it keeps no state, so it serves every call and thread - - -def _nthreads_context(nthreads): - """Return a context manager that engages a new GxB_Context with `nthreads` threads. +def _call_with_nthreads(nthreads, func, *args): + """Return ``func(*args)``, called under a new GxB_Context with `nthreads` threads. GraphBLAS 10 takes the number of threads from the Context engaged on the calling thread, - not from a descriptor. If `nthreads` is None, 0 or negative, the context manager does - nothing. - """ - if nthreads is not None: - nthreads = operator.index(nthreads) # TypeError if it isn't an integer - if nthreads is None or nthreads <= 0: - return _NO_CONTEXT - return _engaged_context(nthreads) - - -@contextmanager -def _engaged_context(nthreads): - """Engage a new GxB_Context that uses at most `nthreads` threads, for the body. + not from a descriptor. If `nthreads` is None, 0 or negative, `func` is just called. Apart from the number of threads, the new Context is a copy of GxB_CONTEXT_WORLD: GxB_Context_new copies its chunk and GPUs, and the arenas are copied here, since they would otherwise be arena 0. WORLD is the Context the call would use without `nthreads`, because a Context engaged on this thread makes this raise. + + It all happens in this one frame, in try and finally blocks, rather than in a generator + context manager. A KeyboardInterrupt can come as the context manager's ``__exit__`` + begins, before the generator resumes, and that leaves disengaging and freeing the Context + to garbage collection: later, and on PyPy perhaps in another thread. """ - ctx = context_new(free=None) + if nthreads is not None: + nthreads = operator.index(nthreads) # TypeError if it isn't an integer + if nthreads is None or nthreads <= 0: + return func(*args) + ctx = ffi.new("GxB_Context*") + # A KeyboardInterrupt between here and `try` leaks the Context, which isn't engaged yet + check_status(ctx, lib.GxB_Context_new(ctx)) try: # A Context engaged on this thread would be lost: GraphBLAS can't say which one it # is, so it can't be engaged again afterwards. But it can say whether there is one: @@ -67,13 +56,18 @@ def _engaged_context(nthreads): check_status(ctx, lib.GxB_Context_set_INT(ctx[0], header_arena, lib.GxB_ARENA_HEADER)) data_arena = global_get_int32(lib.GxB_ARENA_DATA) check_status(ctx, lib.GxB_Context_set_INT(ctx[0], data_arena, lib.GxB_ARENA_DATA)) - context_engage(ctx) try: - yield + check_status(ctx, lib.GxB_Context_engage(ctx[0])) + return func(*args) finally: - context_disengage(ctx) + lib.GxB_Context_disengage(ctx[0]) finally: - context_free(ctx) + # Disengaging a Context that isn't engaged changes nothing, so disengage it again, in + # case a KeyboardInterrupt stopped the `finally` above before it could (PyPy may stop + # it at its first bytecode). Freeing it while engaged would leave the thread with a + # dangling Context. + lib.GxB_Context_disengage(ctx[0]) + lib.GxB_Context_free(ctx) def get_serialize_desc(compression=lib.GxB_COMPRESSION_DEFAULT, level=None, nthreads=None): @@ -146,8 +140,9 @@ def serialize_matrix(A, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *, # any), so that `claim_buffer` knows which allocator must free it arena = global_get_int32(lib.GxB_ARENA_DATA) desc = ffi.NULL if desc is None else desc - with _nthreads_context(nthreads): - info = lib.GxB_Matrix_serialize_arena(data_ptr, size_ptr, A[0], arena, desc) + info = _call_with_nthreads( + nthreads, lib.GxB_Matrix_serialize_arena, data_ptr, size_ptr, A[0], arena, desc + ) check_status(A, info) return claim_buffer(ffi, data_ptr[0], size_ptr[0], np.dtype(np.uint8), arena) @@ -177,8 +172,9 @@ def serialize_vector(v, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *, size_ptr = ffi.new("GrB_Index*") arena = global_get_int32(lib.GxB_ARENA_DATA) # see `serialize_matrix` desc = ffi.NULL if desc is None else desc - with _nthreads_context(nthreads): - info = lib.GxB_Vector_serialize_arena(data_ptr, size_ptr, v[0], arena, desc) + info = _call_with_nthreads( + nthreads, lib.GxB_Vector_serialize_arena, data_ptr, size_ptr, v[0], arena, desc + ) check_status(v, info) return claim_buffer(ffi, data_ptr[0], size_ptr[0], np.dtype(np.uint8), arena) @@ -204,14 +200,15 @@ def deserialize_matrix(data, *, free=True, nthreads=None): """ data = np.frombuffer(data, np.uint8) A = ffi.new("GrB_Matrix*") - with _nthreads_context(nthreads): - info = lib.GxB_Matrix_deserialize( - A, - ffi.NULL, # dtype; we don't check for now - ffi.from_buffer("void*", data), - data.nbytes, - ffi.NULL, - ) + info = _call_with_nthreads( + nthreads, + lib.GxB_Matrix_deserialize, + A, + ffi.NULL, # dtype; we don't check for now + ffi.from_buffer("void*", data), + data.nbytes, + ffi.NULL, + ) check_status(A, info) if free: if callable(free): @@ -241,14 +238,15 @@ def deserialize_vector(data, *, free=True, nthreads=None): """ data = np.frombuffer(data, np.uint8) v = ffi.new("GrB_Vector*") - with _nthreads_context(nthreads): - info = lib.GxB_Vector_deserialize( - v, - ffi.NULL, # dtype; we don't check for now - ffi.from_buffer("void*", data), - data.nbytes, - ffi.NULL, - ) + info = _call_with_nthreads( + nthreads, + lib.GxB_Vector_deserialize, + v, + ffi.NULL, # dtype; we don't check for now + ffi.from_buffer("void*", data), + data.nbytes, + ffi.NULL, + ) check_status(v, info) if free: if callable(free): diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index bb4ac56..9f783ff 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -738,6 +738,51 @@ def test_serialize_nthreads_invalid(kind): assert not _context_engaged(probe) +def test_call_with_nthreads_interrupted(): + # The call runs under the Context, which is disengaged whatever it raises + probe = context.context_new() + + def interrupted(): + assert _context_engaged(probe) + raise KeyboardInterrupt + + with pytest.raises(KeyboardInterrupt): + serialize._call_with_nthreads(2, interrupted) + assert not _context_engaged(probe) + + +class _InterruptedLib: + """`lib`, except that the `n`th lookup of GxB_Context_disengage raises KeyboardInterrupt.""" + + def __init__(self, n): + self.lookups = 0 + self.n = n + + def __getattr__(self, name): + if name == "GxB_Context_disengage": + self.lookups += 1 + if self.lookups == self.n: + raise KeyboardInterrupt + return getattr(lib, name) + + +@pytest.mark.thread_unsafe(reason="replaces `lib` in the serialize module") +@pytest.mark.parametrize("n", [2, 3], ids=["inner", "outer"]) +def test_call_with_nthreads_interrupted_in_finally(monkeypatch, n): + # A KeyboardInterrupt can come at the first bytecode of a `finally` block (PyPy can stop + # it there), before the block disengages the Context. Each of the two `finally` blocks + # disengages it, so the other one still does. The lookups of GxB_Context_disengage are + # for the probe, then the inner `finally` block, then the outer one. + probe = context.context_new() + interrupted = _InterruptedLib(n) + monkeypatch.setattr(serialize, "lib", interrupted) + with pytest.raises(KeyboardInterrupt): + serialize._call_with_nthreads(2, lambda: None) + monkeypatch.undo() + assert not _context_engaged(probe) + assert interrupted.lookups == 3 + + @functools.cache def _arena_like_0(): """Arena 1, which allocates as arena 0 does. It's made once: arenas can't be changed. From d6fbae7ba3e063a79ab00b3336ebf69b90d1986b Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:37:14 -0600 Subject: [PATCH 5/9] serialize: reject a bool nthreads; document data, free and nthreads operator.index takes Python's bool, so nthreads=True meant one thread and nthreads=False meant the default. A bool is now a TypeError, like a float. NumPy's bool was already one: operator.index refuses it in every NumPy that psg supports (bool_.__index__ went in NumPy 1.20). The nthreads docstrings now say what is checked: any negative integer means the default, even one beyond int32_t. OverflowError is only for a positive integer too big for int32_t. deserialize_matrix and deserialize_vector document `data` and `free` under Parameters, with their old prose moved there. test_serialize_nthreads_invalid now expects TypeError for True, False and np.True_, and test_serialize_nthreads_default covers -2**40. Before this change the cases for True and False fail: they are accepted. --- suitesparse_graphblas/api/io/serialize.py | 83 ++++++++++++----------- suitesparse_graphblas/tests/test_io.py | 5 +- 2 files changed, 49 insertions(+), 39 deletions(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index d19dfa0..31febbf 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -20,6 +20,7 @@ def _call_with_nthreads(nthreads, func, *args): GraphBLAS 10 takes the number of threads from the Context engaged on the calling thread, not from a descriptor. If `nthreads` is None, 0 or negative, `func` is just called. + `nthreads` must be an integer, and not a bool. Apart from the number of threads, the new Context is a copy of GxB_CONTEXT_WORLD: GxB_Context_new copies its chunk and GPUs, and the arenas are copied here, since they @@ -32,6 +33,8 @@ def _call_with_nthreads(nthreads, func, *args): to garbage collection: later, and on PyPy perhaps in another thread. """ if nthreads is not None: + if isinstance(nthreads, bool): # `operator.index` refuses NumPy's bool, not Python's + raise TypeError("nthreads must be an integer, not a bool") nthreads = operator.index(nthreads) # TypeError if it isn't an integer if nthreads is None or nthreads <= 0: return func(*args) @@ -125,13 +128,13 @@ def serialize_matrix(A, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *, For GxB_COMPRESSION_LZ4HC, should be between 1 and 9, where 9 is most compressed. For GxB_COMPRESSION_ZSTD, should be between 1 and 19, where 19 is most compressed. nthreads : int, optional - The maximum number of OpenMP threads to use. None (the default), 0 or negative - means the number of threads of the GxB_Context engaged on this thread, if any, or - else of GxB_CONTEXT_WORLD. A positive number makes the call run under a new - Context with that many threads, so it raises 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, OverflowError if it doesn't fit - in int32_t. + The maximum number of OpenMP threads to use. None (the default), 0 or any negative + integer, however large, means the number of threads of the GxB_Context engaged on + this thread, if any, or else of GxB_CONTEXT_WORLD. A positive integer makes the + call run under a new Context with that many threads. It raises OverflowError if + 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. """ desc = get_serialize_desc(compression, level) data_ptr = ffi.new("void**") @@ -159,13 +162,13 @@ def serialize_vector(v, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *, For GxB_COMPRESSION_LZ4HC, should be between 1 and 9, where 9 is most compressed. For GxB_COMPRESSION_ZSTD, should be between 1 and 19, where 19 is most compressed. nthreads : int, optional - The maximum number of OpenMP threads to use. None (the default), 0 or negative - means the number of threads of the GxB_Context engaged on this thread, if any, or - else of GxB_CONTEXT_WORLD. A positive number makes the call run under a new - Context with that many threads, so it raises 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, OverflowError if it doesn't fit - in int32_t. + The maximum number of OpenMP threads to use. None (the default), 0 or any negative + integer, however large, means the number of threads of the GxB_Context engaged on + this thread, if any, or else of GxB_CONTEXT_WORLD. A positive integer makes the + call run under a new Context with that many threads. It raises OverflowError if + 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. """ desc = get_serialize_desc(compression, level) data_ptr = ffi.new("void**") @@ -182,21 +185,23 @@ def serialize_vector(v, compression=lib.GxB_COMPRESSION_DEFAULT, level=None, *, def deserialize_matrix(data, *, free=True, nthreads=None): """Deserialize a Matrix from bytes. - The `free` argument is called when the object is garbage - collected, the default is `matrix.matrix_free()`. If `free` is None then - there is no automatic garbage collection and it is up to the user - to free the matrix. - Parameters ---------- + data : bytes-like + A serialized Matrix, such as the result of `serialize_matrix`: bytes, a NumPy array, or + anything else with the buffer protocol. + free : callable or bool, optional + Called with the result when it is garbage collected. True (the default) means + `matrix.matrix_free`. If `free` is None or False, there is no automatic garbage + collection, and it is up to the caller to free the Matrix. nthreads : int, optional - The maximum number of OpenMP threads to use. None (the default), 0 or negative - means the number of threads of the GxB_Context engaged on this thread, if any, or - else of GxB_CONTEXT_WORLD. A positive number makes the call run under a new - Context with that many threads, so it raises 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, OverflowError if it doesn't fit - in int32_t. + The maximum number of OpenMP threads to use. None (the default), 0 or any negative + integer, however large, means the number of threads of the GxB_Context engaged on + this thread, if any, or else of GxB_CONTEXT_WORLD. A positive integer makes the + call run under a new Context with that many threads. It raises OverflowError if + 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. """ data = np.frombuffer(data, np.uint8) A = ffi.new("GrB_Matrix*") @@ -220,21 +225,23 @@ def deserialize_matrix(data, *, free=True, nthreads=None): def deserialize_vector(data, *, free=True, nthreads=None): """Deserialize a Vector from bytes. - The `free` argument is called when the object is garbage - collected, the default is `vector.vector_free()`. If `free` is None then - there is no automatic garbage collection and it is up to the user - to free the vector. - Parameters ---------- + data : bytes-like + A serialized Vector, such as the result of `serialize_vector`: bytes, a NumPy array, or + anything else with the buffer protocol. + free : callable or bool, optional + Called with the result when it is garbage collected. True (the default) means + `vector.vector_free`. If `free` is None or False, there is no automatic garbage + collection, and it is up to the caller to free the Vector. nthreads : int, optional - The maximum number of OpenMP threads to use. None (the default), 0 or negative - means the number of threads of the GxB_Context engaged on this thread, if any, or - else of GxB_CONTEXT_WORLD. A positive number makes the call run under a new - Context with that many threads, so it raises 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, OverflowError if it doesn't fit - in int32_t. + The maximum number of OpenMP threads to use. None (the default), 0 or any negative + integer, however large, means the number of threads of the GxB_Context engaged on + this thread, if any, or else of GxB_CONTEXT_WORLD. A positive integer makes the + call run under a new Context with that many threads. It raises OverflowError if + 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. """ 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 9f783ff..104cf60 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -676,7 +676,7 @@ def test_serialize_nthreads(kind): assert not _context_engaged(probe) -@pytest.mark.parametrize("nthreads", [None, 0, -1]) +@pytest.mark.parametrize("nthreads", [None, 0, -1, -(2**40)]) # -2**40: beyond int32_t @pytest.mark.parametrize("kind", ["matrix", "vector"]) def test_serialize_nthreads_default(kind, nthreads): # These use the Context engaged on this thread, if any, or else GxB_CONTEXT_WORLD @@ -725,6 +725,9 @@ def test_serialize_nthreads_invalid(kind): for nthreads in (2.0, 0.0, "2"): # not even 0.0, which would mean the default with pytest.raises(TypeError): call(nthreads) + for nthreads in (True, False, np.True_): # nor a bool, which would mean 1 or 0 + with pytest.raises(TypeError, match="bool"): + call(nthreads) with pytest.raises(OverflowError): call(2**31) # more than int32_t holds assert not _context_engaged(probe) From 96da10d451a41edc8342b927c823a1f48446a556 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:44:45 -0600 Subject: [PATCH 6/9] test_io: check that the default nthreads path doesn't swallow errors test_serialize_nthreads_invalid checked that a TypeError from the GraphBLAS call gets out when nthreads is given, but not with the default, so a default path that swallowed exceptions went unnoticed. It now also expects the TypeError from serializing the wrong kind of object without nthreads. A _call_with_nthreads whose default path returns None when the call raises fails this check, and passed every test before. --- suitesparse_graphblas/tests/test_io.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 104cf60..969e165 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -736,6 +736,8 @@ def test_serialize_nthreads_invalid(kind): with pytest.raises(TypeError): ser(other, nthreads=2) # the wrong kind of object assert not _context_engaged(probe) + with pytest.raises(TypeError): + ser(other) # nor does the default path swallow the error with pytest.raises(InvalidObject): deser(bytes(64), nthreads=2) assert not _context_engaged(probe) From 877bfb030e07694229c36a92e316aaad6953d95e Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:49:34 -0600 Subject: [PATCH 7/9] tests: make the recording arena a conftest.py fixture The arena that records the addresses it frees was a helper in test_memory.py, and test_io.py is about to use it too. It is now a session-scoped fixture, recording_arena, beside the other session fixtures in conftest.py, so neither test module imports the other. The installed package already ships that conftest.py, which `pytest --pyargs suitesparse_graphblas` finds. pytest sets up fixtures before pytest-run-parallel starts its threads, so the lock that made the arena once goes. The callbacks stay in a module global: GraphBLAS may call them until the process ends. test_claim_buffer_frees_on_error takes the fixture and is otherwise unchanged. --- suitesparse_graphblas/conftest.py | 44 +++++++++++++++++++++- suitesparse_graphblas/tests/test_io.py | 2 +- suitesparse_graphblas/tests/test_memory.py | 42 +-------------------- 3 files changed, 46 insertions(+), 42 deletions(-) diff --git a/suitesparse_graphblas/conftest.py b/suitesparse_graphblas/conftest.py index 17e8144..e5d6f3d 100644 --- a/suitesparse_graphblas/conftest.py +++ b/suitesparse_graphblas/conftest.py @@ -1,6 +1,8 @@ +import threading + import pytest -from suitesparse_graphblas import initialize +from suitesparse_graphblas import ffi, initialize, lib try: from numpy._core._multiarray_umath import _set_numpy_warn_if_no_mem_policy @@ -37,3 +39,43 @@ def warn_if_no_memory_handler(): old = _set_numpy_warn_if_no_mem_policy(True) yield _set_numpy_warn_if_no_mem_policy(old) + + +class _FreedInThisThread(threading.local): + # Every thread starts with an empty list, so a free in any thread is recorded: an + # AttributeError in the cffi callback would only be printed, and the free not seen. + def __init__(self): + self.addresses = [] + + +# GraphBLAS may call the recording arena's functions until the process ends +_recording_arena_callbacks = [] + + +@pytest.fixture(scope="session") +def recording_arena(): + """An arena that records the addresses it frees: ``(k, freed)``. + + `k` is its index. Tests may run in several threads at once, so each thread records only + its own frees, in ``freed.addresses``. An arena can't be changed, so it's made once. It + needs cffi callbacks, which Pyodide doesn't have. + """ + blocks = {} + freed = _FreedInThisThread() + + @ffi.callback("void *(size_t)") + def malloc(size): + block = ffi.new("char[]", size or 1) + blocks[int(ffi.cast("uintptr_t", block))] = block + return block + + @ffi.callback("void (void *)") + def free(ptr): + address = int(ffi.cast("uintptr_t", ptr)) + blocks.pop(address, None) + freed.addresses.append(address) + + k = lib.GxB_NARENAS - 2 # not 5: test_can_unclaim_buffer needs it uninitialized + assert lib.GxB_arena_init(k, malloc, ffi.NULL, ffi.NULL, free) == lib.GrB_SUCCESS + _recording_arena_callbacks.extend([malloc, free]) + return k, freed diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 969e165..6758838 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -793,7 +793,7 @@ def _arena_like_0(): """Arena 1, which allocates as arena 0 does. It's made once: arenas can't be changed. Other tests that run in this process keep arena 5 uninitialized (test_can_unclaim_buffer) - and use arena 6 (`recording_arena` in test_memory.py). + and use arena 6 (the `recording_arena` fixture in conftest.py). """ k = 1 malloc, free = ffi.new("void**"), ffi.new("void**") diff --git a/suitesparse_graphblas/tests/test_memory.py b/suitesparse_graphblas/tests/test_memory.py index 1021267..651bd14 100644 --- a/suitesparse_graphblas/tests/test_memory.py +++ b/suitesparse_graphblas/tests/test_memory.py @@ -2,7 +2,6 @@ import subprocess import sys import textwrap -import threading import numpy as np import pytest @@ -234,43 +233,6 @@ def test_claim_buffer(): claim_buffer_2d(ffi, ffi.NULL, 6, 2, 3, int64, True) -# An arena that records the addresses it frees, made once (arenas can't be changed). Tests may -# run in several threads at once, so each thread records only its own frees. -_recording_arena = {} -_recording_arena_lock = threading.Lock() - - -class _FreedInThisThread(threading.local): - # Every thread starts with an empty list, so a free in any thread is recorded: an - # AttributeError in the cffi callback would only be printed, and the free not seen. - def __init__(self): - self.addresses = [] - - -def recording_arena(): - with _recording_arena_lock: - if not _recording_arena: - blocks = {} - freed = _FreedInThisThread() - - @ffi.callback("void *(size_t)") - def malloc(size): - block = ffi.new("char[]", size or 1) - blocks[int(ffi.cast("uintptr_t", block))] = block - return block - - @ffi.callback("void (void *)") - def free(ptr): - address = int(ffi.cast("uintptr_t", ptr)) - blocks.pop(address, None) - freed.addresses.append(address) - - k = lib.GxB_NARENAS - 2 # not 5: test_can_unclaim_buffer needs it uninitialized - assert lib.GxB_arena_init(k, malloc, ffi.NULL, ffi.NULL, free) == lib.GrB_SUCCESS - _recording_arena.update(k=k, freed=freed, callbacks=(malloc, free)) - return _recording_arena["k"], _recording_arena["freed"] - - @pytest.mark.skipif(sys.platform == "emscripten", reason="needs cffi callbacks") # PyPy runs C extension code (utils.pyx here) holding the GIL, and a cffi callback takes the # GIL on entry without checking whether its own thread holds it, so the first call into this @@ -279,9 +241,9 @@ def free(ptr): sys.implementation.name == "pypy", reason="on PyPy, a cffi callback called from a C extension module deadlocks", ) -def test_claim_buffer_frees_on_error(): +def test_claim_buffer_frees_on_error(recording_arena): # GraphBLAS has handed the buffer over, so if claiming it fails, nothing else frees it - k, freed = recording_arena() + k, freed = recording_arena int64 = np.dtype(np.int64) huge = sys.maxsize // 4 # too many int64s for NumPy for claim, match in [ From 1629c77cf9575573bafd20796f55363f56454221 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 20:46:44 -0600 Subject: [PATCH 8/9] test_io: check that the default nthreads makes no Context With nthreads None, 0 or negative, serialize and deserialize must do no Context work at all, but no test could see a Context made and freed without being engaged: the results are the same. GxB_Context_new allocates the Context's header in the global header arena, though, so test_serialize_nthreads_default_makes_no_context makes the recording_arena fixture the header arena and counts the blocks freed there. The default path must free as many as the GraphBLAS call alone, and serializing with nthreads=2 shows that a Context adds one. A _call_with_nthreads whose default path makes and frees a Context fails all six cases, and passed every test before. The test needs cffi callbacks, so it's skipped on Pyodide. --- suitesparse_graphblas/tests/test_io.py | 55 ++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 6758838..180ad84 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -3,6 +3,7 @@ import gzip import platform import struct +import sys from contextlib import contextmanager from pathlib import Path @@ -36,6 +37,7 @@ 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 @@ -694,6 +696,59 @@ def test_serialize_nthreads_default(kind, nthreads): assert not _context_engaged(probe) +@pytest.mark.skipif(sys.platform == "emscripten", reason="needs cffi callbacks") +@pytest.mark.thread_unsafe(reason="changes the global header arena") +@pytest.mark.parametrize("nthreads", [None, 0, -1]) +@pytest.mark.parametrize("kind", ["matrix", "vector"]) +def test_serialize_nthreads_default_makes_no_context(kind, nthreads, recording_arena): + # The default does no Context work at all. A new Context's header comes from the global + # header arena, so making and freeing one frees a block there that the GraphBLAS call + # alone doesn't free. The recording arena records the blocks freed in this thread. + A, ser, deser, assert_equal = _big(kind) + blob = ser(A) + data = np.frombuffer(blob, np.uint8) + T = "Matrix" if kind == "matrix" else "Vector" + free = matrix.matrix_free if kind == "matrix" else vector.vector_free + + def serialize_raw(): + data_ptr, size_ptr = ffi.new("void**"), ffi.new("GrB_Index*") + info = getattr(lib, f"GxB_{T}_serialize_arena")(data_ptr, size_ptr, A[0], 0, NULL) + check_status(A, info) + return claim_buffer(ffi, data_ptr[0], size_ptr[0], np.dtype(np.uint8), 0) + + def deserialize_raw(): + B = ffi.new(f"GrB_{T}*") + blob_ptr = ffi.from_buffer("void*", data) + check_status(B, getattr(lib, f"GxB_{T}_deserialize")(B, NULL, blob_ptr, data.nbytes, NULL)) + return B + + calls = { + "serialize_raw": serialize_raw, + "serialize": lambda: ser(A, nthreads=nthreads), + "serialize_2": lambda: ser(A, nthreads=2), # this one does make a Context + "deserialize_raw": deserialize_raw, + "deserialize": lambda: deser(blob, free=None, nthreads=nthreads), + } + k, freed = recording_arena + old = global_get_int32(lib.GxB_ARENA_HEADER) + results, frees = {}, {} + assert lib.GrB_Global_set_INT32(lib.GrB_GLOBAL, k, lib.GxB_ARENA_HEADER) == lib.GrB_SUCCESS + try: + for name, call in calls.items(): + freed.addresses = [] + results[name] = call() + frees[name] = len(freed.addresses) + finally: + assert lib.GrB_Global_set_INT32(lib.GrB_GLOBAL, old, lib.GxB_ARENA_HEADER) == 0 + assert frees["serialize"] == frees["serialize_raw"] + assert frees["serialize_2"] == frees["serialize_raw"] + 1 + assert frees["deserialize"] == frees["deserialize_raw"] + assert results["serialize"].tobytes() == results["serialize_raw"].tobytes() + for name in ("deserialize_raw", "deserialize"): + assert_equal(A, results[name]) + free(results[name]) + + @pytest.mark.parametrize("kind", ["matrix", "vector"]) def test_serialize_nthreads_with_engaged_context(kind): # GraphBLAS can't say which Context is engaged on this thread, so a call that engaged From 56745f9c8d14a2a544b68854f2a296077e936cdd Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 25 Nov 2026 21:19:01 -0600 Subject: [PATCH 9/9] serialize: reject NumPy's bool nthreads explicitly NumPy 2.2 (Pyodide's) still lets operator.index take np.bool_, with a DeprecationWarning, so np.True_ reached GraphBLAS as 1 thread, and under -W error test_serialize_nthreads_invalid got the warning instead of TypeError. The previous commit said operator.index refuses NumPy's bool in every NumPy psg supports; that holds for current NumPy (2.5) but not for 2.2, and psg supports numpy>=1.24. Check for np.bool_ as well as bool, before operator.index, and test np.False_ too. --- suitesparse_graphblas/api/io/serialize.py | 3 ++- suitesparse_graphblas/tests/test_io.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/suitesparse_graphblas/api/io/serialize.py b/suitesparse_graphblas/api/io/serialize.py index 31febbf..1d9e114 100644 --- a/suitesparse_graphblas/api/io/serialize.py +++ b/suitesparse_graphblas/api/io/serialize.py @@ -33,7 +33,8 @@ def _call_with_nthreads(nthreads, func, *args): to garbage collection: later, and on PyPy perhaps in another thread. """ if nthreads is not None: - if isinstance(nthreads, bool): # `operator.index` refuses NumPy's bool, not Python's + # NumPy 2.2 still lets `operator.index` take its bool, with a DeprecationWarning + if isinstance(nthreads, (bool, np.bool_)): raise TypeError("nthreads must be an integer, not a bool") nthreads = operator.index(nthreads) # TypeError if it isn't an integer if nthreads is None or nthreads <= 0: diff --git a/suitesparse_graphblas/tests/test_io.py b/suitesparse_graphblas/tests/test_io.py index 180ad84..c5b3de9 100644 --- a/suitesparse_graphblas/tests/test_io.py +++ b/suitesparse_graphblas/tests/test_io.py @@ -780,7 +780,7 @@ def test_serialize_nthreads_invalid(kind): for nthreads in (2.0, 0.0, "2"): # not even 0.0, which would mean the default with pytest.raises(TypeError): call(nthreads) - for nthreads in (True, False, np.True_): # nor a bool, which would mean 1 or 0 + for nthreads in (True, False, np.True_, np.False_): # nor a bool, which would mean 1 or 0 with pytest.raises(TypeError, match="bool"): call(nthreads) with pytest.raises(OverflowError):