Skip to content

serialize: honor nthreads with a GxB_Context - #167

Merged
eriknw merged 9 commits into
GraphBLAS:mainfrom
eriknw:serialize-nthreads
Nov 26, 2026
Merged

eriknw merged 9 commits into
GraphBLAS:mainfrom
eriknw:serialize-nthreads

Conversation

@eriknw

@eriknw eriknw commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Summary

nthreads= in serialize_matrix, serialize_vector, deserialize_matrix and deserialize_vector didn't work on GraphBLAS 10:

  • serialize put it in a descriptor, as GxB_NTHREADS, which GraphBLAS 10 rejects with InvalidValue;
  • deserialize passed it as the compression level, so it was ignored.

The number of threads is a GxB_Context setting now, so each call runs under a temporary Context:

_call_with_nthreads(nthreads, func, *args)
  nthreads None, 0 or negative -> func(*args)            # no Context work, as before
  bool or non-integer          -> TypeError
  new Context
  try
    any Context engaged on this thread? -> InvalidValue   # it can't be restored afterwards
    set GxB_CONTEXT_NTHREADS              (OverflowError past int32_t)
    copy the global header and data arenas                # a new Context starts at arena 0
    try
      engage; return func(*args)
    finally
      disengage
  finally
    disengage again, then free     # PyPy can interrupt a finally at its first bytecode
  • 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 raises InvalidValue on GraphBLAS 10 as before.

  • Tests: recording_arena, used by test_memory.py and now by test_io.py, moves into conftest.py as a session fixture (877bfb0).

Evidence

  • Before (main at 1dec9b0): test_serialize_nthreads is 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.
    • Other tests:
      • None, 0, -1 and -2**40 use the engaged or global setting;
      • a caller's Context is refused and stays engaged;
      • bool (Python's or NumPy's, which NumPy 2.2 still accepts as an index), float and str raise TypeError, and 2**31 raises OverflowError;
      • no Context is left engaged after an error or a KeyboardInterrupt, including one at the start of either finally;
      • deserialize puts its result in the global arenas;
      • the default path does no Context work: with a recording header arena, it frees no more blocks than the raw GraphBLAS call, while nthreads=2 frees one more (the Context);
      • the default path still raises for a wrong object, so it can't swallow errors.
  • Locally (macOS arm64):

    • 3.15.2: 819 passed, 1 skipped.
    • 3.15.2t with --parallel-threads=4 --iterations=10: 819 passed, 1 skipped.
    • Like the wheel jobs (pytest -W error --pyargs suitesparse_graphblas, outside the tree): 469 passed, 1 skipped.
    • PyPy 3.11 and Pyodide 314 (wasm32, no OpenMP): the serialize tests pass.
    • serialize.py: no missed lines. The one partial branch is in get_serialize_desc and can't be reached on GraphBLAS 10.
    • Mutants: each of these makes a test fail:
      • removing the probe, the arena copy, either disengage, the bool check or operator.index;
      • passing 0 through;
      • a default path that engages a Context, creates one without engaging it, or swallows exceptions.
  • Interrupt test: KeyboardInterrupt at random moments during nthreads=2 calls. Contexts left engaged:

    Version CPython 3.15.2 PyPy 3.11
    generator context manager 211 of 33690 5 of 1164
    one finally that disengages 0 of ~27000 4-5 of ~150
    this PR 0 of 32742 0 of 764
  • Default 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.

  • nthreads raised (serialize) or was ignored (deserialize) on GraphBLAS 10, so no working caller changes behavior.
  • New errors for a positive nthreads: InvalidValue while a Context is engaged, and TypeError for a bool.
  • get_serialize_desc(nthreads=...) now emits DeprecationWarning; with filterwarnings = error, a caller's own test suite would see it.
  • Windows: test_io.py skips its whole module on Windows (since 2021), so CI doesn't run these tests there.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.92%. Comparing base (1dec9b0) to head (56745f9).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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
eriknw force-pushed the serialize-nthreads branch from 111bff9 to 1629c77 Compare November 26, 2026 03:00
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
eriknw marked this pull request as ready for review November 26, 2026 03:45
@eriknw

eriknw commented Nov 26, 2026

Copy link
Copy Markdown
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.

@eriknw
eriknw merged commit e699f09 into GraphBLAS:main Nov 26, 2026
36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant