Skip to content

Fix int32 wraparound, binread validation and smaller bugs - #168

Open
eriknw wants to merge 17 commits into
GraphBLAS:mainfrom
eriknw:small-fixes
Open

eriknw wants to merge 17 commits into
GraphBLAS:mainfrom
eriknw:small-fixes

Conversation

@eriknw

@eriknw eriknw commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Bugs found while raising coverage in #166, each fixed in its own commit with a test that fails without the fix.

Commit Bug Fix
cb20e2c 15 int32 setters (context, matrix, vector, descriptor, global, type, semiring, ops, monoid) passed values through ffi.cast("int32_t", ...), which wraps: context_set_nthreads(ctx, 2**32 + 3) set 3, and matrix_set_format(A, 2**32 + 1) made A by-column pass the value to the int32_t parameter, so cffi raises OverflowError
3509135 the same in get_serialize_desc: ZSTD with level=2**32+1 became level 1 the same
45b2eec, 410dc00 binread's version check was a bare assert, which python -O removes ValueError, naming both versions as major.minor.sub
0dd132c, 4e0bd4a binread accepted a file with out-of-range indices and returned an invalid matrix (GxB_Matrix_fprint: GrB_INVALID_OBJECT) pack as before, then check with GxB_Matrix_fprint(..., GxB_SILENT), and raise InvalidObject naming the file. 0dd132c's secure pack is replaced: on a failed check it frees the caller's matrix header (GraphBLAS mres #14), so the handle dangled
300b36d, 2cc06f6, f2962db deserialize_matrix and deserialize_vector accepted a blob with out-of-range, unsorted or duplicate indices and returned an invalid object; deserialize_vector also took a matrix blob (a 3x4 matrix came back as a "Vector" of size 4 with 2 entries) check the result with GxB_*_fprint(..., GxB_SILENT), as GraphBLAS's User Guide advises for untrusted data, and raise InvalidObject ("data holds a 3x4 Matrix, not a Vector"). An n x 1 matrix held by column, which is a vector to GraphBLAS, still reads
34f4742 initialize() raised RuntimeError for a failure code it has no class for GraphBLASException, as check_status does
e3920a4 binwrite(comments=None) wrote the word "None" into the header an empty comment line, as LAGraph writes; old files still read
d168a52 test_io.py skipped itself on Windows, since 2021 the reason (binary.py got malloc from libc by dlopen) went away with #157; run it there
6a910e6, 331c621 tidying test_io's imports in their group; the int32 test comment says which floats are rejected
d952f52, 60c5b77 _capture_c_output (a test helper) hung when a call printed more than a pipe holds capture into a temporary file

Evidence

  • Before: each new test fails on 1dec9b0.

    • The int32 tests: 16 of 16 fail. 9 said "DID NOT RAISE", because the wrapped value was set silently; 7 got InvalidValue for the wrapped value. On the old code a float was truncated (3.7 set 3 threads) and "3" set 51 threads; both now raise TypeError and leave the setting unchanged.
    • binread: AssertionError for another version, and with python -O it read the file. Every corruption read without error.
    • The secure-pack version (0dd132c) left a dangling handle: a kept exception, a new matrix, then dropping the exception destroyed the new matrix (test_binread_invalid_matrix_frees_only_its_own gets UninitializedObject there).
    • binwrite: the header held "None" at byte 174.
    • The capture test: 200 KB of output hung until a 30 s timeout.
  • After, locally (macOS arm64):

  • deserialize's check: before, all 14 new deserialize cases said "DID NOT RAISE". 2000 failed deserializations kept max RSS flat. The check is single-threaded, so it costs more than the parallel deserialize itself (10M FP64 entries, default compression): 0.006 s becomes 0.022 s (1M x 1M, 10 per row), 0.007 s becomes 0.044 s (10M x 10M, 1 per row), and 0.008 s becomes 0.091 s (10M random).

  • binread's check: 2000 failed reads kept max RSS flat. Read time for a valid FP64 file from the page cache:

    Matrix (10M entries) No check With the check
    1M x 1M, 10 per row 0.010 s 0.030 s
    10M x 10M, 1 per row 0.015 s 0.056 s
    10M x 10M, random 0.017 s 0.105 s
  • CI at a4189c8: green, 34 checks pass. Windows now runs test_io.py: the Windows test jobs give 874 passed, as on Linux and macOS.

Open question: binread and deserialize now check everything they read, for the costs above. An opt-out keyword for trusted data (e.g. check=False) would be new API, so it isn't here.

Merge Danger

Door: two-way.

Blast Radius: small.

  • int32 setters: out-of-range values raise OverflowError instead of wrapping. A Python float or str now raises TypeError; before, it was truncated (4.7 became 4) or turned into a char code ("3" became 51). Types that convert through __int__, such as np.float32, Decimal and Fraction, are still truncated, because that's how cffi converts to int32_t.
  • binread:
    • it checks every file it reads, at 0.02-0.09 s per 10M entries depending on the pattern;
    • a corrupt file raises InvalidObject instead of returning an invalid matrix;
    • a file from another GraphBLAS version raises ValueError instead of AssertionError.
  • deserialize checks what it makes: an invalid blob, or a matrix blob passed to deserialize_vector, raises InvalidObject. That adds the costs above to every call.
  • binwrite with no comments writes an empty comment line, not "None".
  • Windows: CI now runs test_io.py and binread's memory check there for the first time, and both pass.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.94366% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.91%. Comparing base (e699f09) to head (a4189c8).

Files with missing lines Patch % Lines
suitesparse_graphblas/tests/test_api_objects.py 93.54% 1 Missing and 1 partial ⚠️
suitesparse_graphblas/tests/test_io.py 99.40% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #168      +/-   ##
==========================================
- Coverage   98.92%   98.91%   -0.01%     
==========================================
  Files          42       42              
  Lines        4458     4706     +248     
  Branches      375      395      +20     
==========================================
+ Hits         4410     4655     +245     
- Misses         26       27       +1     
- Partials       22       24       +2     

☔ 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.

The functions that set an int32 option or property (context_set_int32
and context_set_nthreads, matrix_set_format, matrix_set_sparsity_control,
the *_option_set_int32 and *_set_int32 of each object, and the global
ones) passed the value through ffi.cast("int32_t", value), which wraps
around silently: context_set_nthreads(ctx, 2**32 + 3) set 3 threads, and
matrix_set_format(A, 2**32 + 1) made A held by column.

Each of the GraphBLAS functions they call takes an int32_t (none is
variadic), so pass the value as it is, as the element setters do: cffi
checks the range and raises OverflowError.  Integers in range, including
NumPy integers and integer cdata, are converted as before.

A float or a str is now a TypeError.  The cast truncated a float (4.7
set 4) and took a one-character str as its character code ("3" set 51
threads), which the docstrings ("from an int32") never promised.

test_set_int32_rejects_non_int32 tries values just out of range, a
float and a str with each of these functions.  Before, each call set
the wrapped, truncated or character-code value (or GraphBLAS rejected
it, for the read-only properties of types, semirings, monoids and
operators) instead of raising OverflowError or TypeError.
…sert

binread checked that a file is from this version of SuiteSparse:GraphBLAS
with an assert, so `python -O` skipped the check (and read the file
anyway), and otherwise the error was a bare AssertionError.  Raise
ValueError instead, saying what the version is and what it should be.

test_binread_other_version changes the version in a file: binread raised
AssertionError, and read the file under `python -O`.
binread packs the arrays it reads into a matrix with GxB_Matrix_pack_*,
which by default trusts them: GraphBLAS checks their sizes, but not
their content.  So a corrupt file made an invalid matrix.  For example,
binread returned a 3x4 matrix with an entry in column 1000, which
GxB_Matrix_fprint called GrB_INVALID_OBJECT, and which later operations
would index out of bounds with.

Pack with a descriptor whose GxB_IMPORT is GxB_SECURE_IMPORT: GraphBLAS
then checks the matrix as it does for GxB_Matrix_fprint.  It checks the
indices (in range, sorted, no duplicates), the row or column pointers,
the hypersparse list, and the bitmap, and binread raises InvalidObject
or IndexOutOfBound.  The check fails after GraphBLAS has taken the
arrays, so the matrix frees them.  2000 failed reads of a 1.6 MB file
left the maximum RSS where it was.

The check is a single pass over the matrix in one thread.  Reading a
10M x 10M FP64 matrix from the page cache took 0.016 s before and 0.10 s
after, with 10M entries (a 240 MB file), and 0.045 s before and 0.20 s
after, with 50M entries (880 MB).  Reading the file from disk, or
decompressing it, costs more than that.  Checking the same things in
NumPy was faster for CSR (0.03-0.04 s), but it would repeat GraphBLAS's
rules for each format in this module.

test_binread_invalid_matrix changes the arrays of a file in eight ways
(column out of range, out of order, or repeated; decreasing row
pointers; hypersparse rows out of range or out of order; a bitmap
holding 2, or more entries than nvals).  binread returned a matrix for
each one.
When GxB_init or GrB_init fails, initialize raises the exception for the
code from _error_code_lookup, as check_status does.  For a code that
isn't in the table, though, it fell back to RuntimeError, where
check_status and burble fall back to GraphBLASException, the base class
of the others.  Fall back to GraphBLASException here too.

Every GrB_Info error code of this GraphBLAS is in the table, so only a
code that a newer GraphBLAS adds would reach the fallback.  The
RuntimeError that the docstring promises, for initializing twice, comes
from the is_initialized() check before the call, and is unchanged.

test_initialize_fails makes the init call return a code (with
is_initialized patched to say GraphBLAS isn't initialized): an unknown
one raised RuntimeError.  It also covers this branch, so it no longer
needs its "no cover" pragma.
binwrite formatted `comments` into the text header as they were, so the
default, None, wrote a line saying "None".  Write an empty line instead,
as LAGraph's binwrite does when it has no comments.  binread skips the
text header, so it still reads the files with "None" in them.

test_binwrite_without_comments compares the header binwrite writes
without comments to the one with comments="": it had "None" where the
other had an empty line.  It also reads a file with "None" in it.
test_io.py skipped itself on Windows since it was added, in GraphBLAS#18 (2021),
without saying why.  The commits squashed into GraphBLAS#18 say: io/binary.py got
`malloc` from libc with cffi's `dlopen(None)`, and then from
`dlopen(find_library("c"))`, neither of which works on Windows, so
importing it failed ("cant call dlopen(None) on windows...", then "no
binary file cookies for you windows!", which added the skip).  The skip
went above the import of binary.

binary.py has needed neither since: 0b713dc dlopened ucrtbase on
Windows, and GraphBLAS#157 dropped libc's malloc for GraphBLAS's own allocator
(and doctest-modules has imported binary.py on Windows since).  So
remove the skip.  The tests write and read files in tmp_path, close
each file before opening it again, and use fixed-size fields.

The allocator check in test_memory.py also skipped binread and binwrite
on Windows ("see test_io.py").  Skip only its arena that uses libc's
allocator, which does need `dlopen(None)`.
The test helper pointed stdout at a pipe and read the pipe after the
call returned, so a call that printed more than the pipe holds (64 KiB
on Linux and macOS) blocked forever, waiting for a reader; and it read
only the first 100000 bytes.  A temporary file takes any amount of
output without a reader, and without a thread, which Pyodide doesn't
have.  An empty file also reads as "", where Emscripten raised
BlockingIOError for an empty pipe.

test_capture_c_output_of_more_than_a_pipe_holds prints a vector of
10000 entries (about 200 KB): it hung (and was killed after 30 s) with
the pipe.  The new helper passes the tests of the old one (no file
descriptor leaks, stdout restored after an error) here and on Pyodide.
29ac555 packed with GxB_SECURE_IMPORT, so that GraphBLAS would check
the matrix.  When that check fails, though, GB_import frees the matrix
it packed into (GB_FREE_ALL, on the pack's own copy of the handle),
header and all.  binread's handle was left pointing at freed memory:
check_status read the error string from it (always empty), and the
handle's ffi.gc freed it again once the exception was gone, by when a
new matrix could have been given the same memory, and was destroyed.

Pack as before, which checks only the sizes of the arrays, and then
check the matrix with GxB_Matrix_fprint(A, "", GxB_SILENT, NULL).  That
runs the same check (GB_matvec_check) and leaves A a valid header that
is freed as usual.  It returns GrB_INVALID_OBJECT for anything wrong
(also for indices out of order or repeated, which the secure pack
reported as GrB_INDEX_OUT_OF_BOUNDS), with no error string, so binread
raises InvalidObject with a message of its own, naming the file.

test_binread_invalid_matrix_frees_only_its_own keeps the exception of a
failed read, makes ten matrices, and drops the exception: after the
secure pack, the first new matrix had lost its header
(UninitializedObject).  test_binread_invalid_matrix now also corrupts
files of a matrix held by column, and checks the message.

The check costs what the secure pack's did.  Reading 10M FP64 entries
from the page cache took 0.010 s without it and 0.029 s with it, for a
1M x 1M matrix with 10 entries in each row; 0.015 s and 0.056 s for a
10M x 10M matrix with one in each row; and 0.017 s and 0.105 s for one
with 10M entries in random places (the case 29ac555 measured), where
GxB_Matrix_fprint alone takes 0.095 s.
The ValueError for a file from another version of GraphBLAS gave that
version as GraphBLAS encodes it, GxB_VERSION(major, minor, sub): "its
version is 10005004, not 10005003".  Say "SuiteSparse:GraphBLAS 10.5.3:
its version is 10.5.4" instead.

test_binread_other_version checks the message for three versions: the
next patch release, 11.0.0 and 9.4.12.  It got the encoded numbers.
test_print captures a silent and then a short fprint in one call
because, it said, a capture of no output failed on Emscripten, where
reading an empty pipe raised BlockingIOError.  _capture_c_output
captures into a temporary file now (97541fd), and no output reads as
"", so the comment no longer holds.
…32_t

get_serialize_desc passed the compression method plus the level through
ffi.cast("int32_t", ...), which wraps around silently:
serialize_matrix(A, GxB_COMPRESSION_ZSTD, level=2**32 + 1) serialized with
ZSTD level 1, and a float level was truncated.  GxB_Desc_set_INT32 takes an
int32_t, so pass the value as it is, as the other int32 setters now do:
cffi checks the range and raises OverflowError, and a float or a str is a
TypeError.  Integers in range, NumPy's included, are converted as before.

test_serialize_compression_out_of_range tries ZSTD and LZ4HC with levels
2**32 + 1 and 1 - 2**32, a method beyond int32_t, and a float level, with
a stand-in for the module's `lib` that counts lookups.  Each one raises
when the descriptor is set, and GraphBLAS's serialize function is never
reached.  Before this change, each call serialized at the wrapped or
truncated level.

The other cast left in serialize.py is the deprecated nthreads of
get_serialize_desc, where GraphBLAS rejects the field whatever its value.
GxB_Matrix_deserialize checks only enough of a blob to read it without
going past its end: a blob with column indices out of range, out of
order or repeated deserialized to an invalid Matrix, which
GxB_Matrix_fprint calls GrB_INVALID_OBJECT, and which later operations
would index out of bounds with.  GraphBLAS's User Guide says as much:
the output "may still be corrupted", so check untrusted data "with
GxB_*_fprint with the print level set to GxB_SILENT".

So deserialize_matrix does that, as binread does.  If the check fails,
it frees the Matrix (with GrB_Matrix_free, not the caller's `free`,
since the caller never gets it) and raises InvalidObject, whose message
says what failed, where GraphBLAS has none.  The check runs after
_call_with_nthreads returns, and doesn't allocate, so the arenas and
the Context work as before.  2000 failed deserializations of a 1.2 MB
blob left the maximum RSS where it was.

test_deserialize_matrix_invalid changes the column indices of an
uncompressed blob in three ways, with and without nthreads, and checks
that no Context is left engaged: deserialize_matrix returned a Matrix
for each.

The check takes O(nvals) time in one thread, where deserializing uses
several, so it costs more than the deserializing itself.  For 10M FP64
entries, deserialize_matrix took 0.006 s without it and 0.022 s with it
(default compression) for a 1M x 1M matrix with 10 entries in each row,
0.007 s and 0.044 s for a 10M x 10M matrix with one in each row, and
0.008 s and 0.091 s for 10M entries in random places.

The check can't help where the blob's header is corrupt in a way that
makes GxB_Matrix_deserialize itself read out of bounds, a GraphBLAS bug
of its own.
deserialize_vector had the same hole as deserialize_matrix: a blob with
indices out of range, out of order or repeated made an invalid Vector.
And GxB_Vector_deserialize takes a Matrix blob as well, so a 3x4 Matrix
became a "Vector" of size 4 with 2 entries (held by row; 3 when held by
column), which GxB_Vector_fprint calls GrB_INVALID_OBJECT.

Check the result with a silent GxB_Vector_fprint, as deserialize_matrix
does, and raise InvalidObject after freeing it.  That rejects a Matrix
blob unless its Matrix is n-by-1 and held by column, which is what a
GrB_Vector is inside GraphBLAS (GB_VECTOR_OK), so such a blob still
gives that Vector.  For the others, the message says what the blob
holds instead ("data holds a 3x4 Matrix, not a Vector"), from a
GxB_Matrix_fprint that runs only when the Vector check has failed.
Such a blob is still read by deserialize_matrix, as a Vector blob is
(as an n-by-1 Matrix).

test_deserialize_vector_invalid changes the indices of a Vector blob in
the three ways the Matrix test does, and
test_deserialize_vector_of_a_matrix tries 3x4, 4x3, 3x1 and 1x3
Matrices, held by row and by column: deserialize_vector returned
something for each.

For 10M FP64 entries in a Vector of size 1e8, deserialize_vector took
0.009 s without the check and 0.080 s with it for every tenth entry, and
0.024 s and 0.157 s for entries in random places.
test_io.py imported five of its modules last, marked `isort:skip`,
because they came after the module-level skip on Windows, which is
gone.  Import them with the other imports from suitesparse_graphblas,
and drop the two blank lines left where the skip was.
The comments of test_set_int32_rejects_non_int32 said that a float is
now a TypeError.  That holds for a Python float, and so for np.float64,
its subclass, which the test uses.  cffi converts other objects with
`__int__`, as it did through the cast before: np.float32(4.7),
Decimal("4.7") and Fraction(47, 10) still set 4.  Say so.
_check_deserialized raises InvalidObject when GxB_*_fprint calls the
deserialized object invalid, and otherwise raises what check_status
raises for the code, freeing the object either way.  A deserialized
object never gets another code, so test that path with an fprint that
returns GrB_OUT_OF_MEMORY: it raises OutOfMemory and frees the Matrix.
The docstrings of binread, deserialize_matrix and deserialize_vector
said that a corrupt file or blob can't make an invalid object, in
O(nvals) time.  GraphBLAS's check is of the structure only (indices,
pointers, the hypersparse list and the bitmap), and takes
O(nvec + nvals) time, or O(nrows * ncols) for a bitmap.  It doesn't
look at the values: a GrB_BOOL value byte of 2 in a binread file loads
as it is.  Say so.

The test of a corrupt compression level said that a float level now
raises.  That's a Python float (or np.float64): cffi converts other
objects with `__int__`, so np.float32(1.5) still gives level 1.  Say
so too.

In the tests, escape the version strings that test_binread_other_version
matches (their dots matched any character), and import gc with the
other modules rather than in a test.
@eriknw
eriknw marked this pull request as ready for review November 26, 2026 05:13

This branch has not been deployed

No deployments
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