Repository navigation
serialize: honor nthreads with a GxB_Context - #167
Merged
Merged
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #167 +/- ##
==========================================
+ Coverage 98.79% 98.92% +0.12%
==========================================
Files 42 42
Lines 4231 4458 +227
Branches 354 375 +21
==========================================
+ Hits 4180 4410 +230
+ Misses 28 26 -2
+ Partials 23 22 -1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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.
_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.
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.
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.
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.
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.
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.
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.
eriknw
force-pushed
the
serialize-nthreads
branch
from
November 26, 2026 03:00
111bff9 to
1629c77
Compare
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.
eriknw
marked this pull request as ready for review
November 26, 2026 03:45
Member
Author
|
Huh, this is more nuanced with contexts and arenas than I expected. It also appears 0 and negative nthreads being set to 1 in SS:GB is unintended behavior in SS:GB (I think this is supposed to set the nthreads to "default", which is set by openmp). This looks reasonable to me. Merging. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
nthreads=inserialize_matrix,serialize_vector,deserialize_matrixanddeserialize_vectordidn't work on GraphBLAS 10:GxB_NTHREADS, which GraphBLAS 10 rejects withInvalidValue;level, so it was ignored.The number of threads is a
GxB_Contextsetting now, so each call runs under a temporary Context:0 or negative means the default: the engaged Context's thread count, or else the global one. On its own, GraphBLAS 10 turns 0 or negative into 1 thread (
GB_Context.c:178). 0 or negative meant the global setting for a descriptor in GraphBLAS 7.A caller's engaged Context is refused, not replaced. GraphBLAS can't say which Context is engaged, so it couldn't be engaged again afterwards. It can say whether one is: disengaging a Context that isn't engaged fails if another one is, and changes nothing (
GB_Context.c:107-122).get_serialize_desc(nthreads=...)is deprecated. It warns, then raisesInvalidValueon GraphBLAS 10 as before.Tests:
recording_arena, used bytest_memory.pyand now bytest_io.py, moves intoconftest.pyas a session fixture (877bfb0).Evidence
Before (main at 1dec9b0):
test_serialize_nthreadsis a strict xfail. 12 of the 14 new cases fail, and the 2 arena cases pass only because deserialize ignored nthreads.After:
serialize(nthreads=k)gives the same bytes as serializing under an engaged Context with k threads. 1 and 2 threads give different bytes: one thread compresses a 512 KiB array as one block, more threads as 64 KiB blocks.finally;nthreads=2frees one more (the Context);Locally (macOS arm64):
--parallel-threads=4 --iterations=10: 819 passed, 1 skipped.pytest -W error --pyargs suitesparse_graphblas, outside the tree): 469 passed, 1 skipped.serialize.py: no missed lines. The one partial branch is inget_serialize_descand can't be reached on GraphBLAS 10.operator.index;Interrupt test:
KeyboardInterruptat random moments duringnthreads=2calls. Contexts left engaged:finallythat disengagesDefault path: about 0.1 us slower per call on a 3-element vector (serialize 0.95 vs 0.87 us).
CI at 56745f9: green, 34 checks pass, Pyodide (NumPy 2.2.5) included. Codecov: 98.92% over 22 uploads.
Merge Danger
Door: two-way.
Blast Radius: small.
nthreadsraised (serialize) or was ignored (deserialize) on GraphBLAS 10, so no working caller changes behavior.nthreads: InvalidValue while a Context is engaged, and TypeError for a bool.get_serialize_desc(nthreads=...)now emits DeprecationWarning; withfilterwarnings = error, a caller's own test suite would see it.test_io.pyskips its whole module on Windows (since 2021), so CI doesn't run these tests there.