Repository navigation
Conversation
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
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
marked this pull request as ready for review
November 26, 2026 05:13
This branch has not been deployed
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
Bugs found while raising coverage in #166, each fixed in its own commit with a test that fails without the fix.
ffi.cast("int32_t", ...), which wraps:context_set_nthreads(ctx, 2**32 + 3)set 3, andmatrix_set_format(A, 2**32 + 1)made A by-columnint32_tparameter, so cffi raises OverflowErrorget_serialize_desc: ZSTD withlevel=2**32+1became level 1assert, whichpython -OremovesGxB_Matrix_fprint: GrB_INVALID_OBJECT)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 dangleddeserialize_matrixanddeserialize_vectoraccepted a blob with out-of-range, unsorted or duplicate indices and returned an invalid object;deserialize_vectoralso took a matrix blob (a 3x4 matrix came back as a "Vector" of size 4 with 2 entries)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 readsinitialize()raised RuntimeError for a failure code it has no class forcheck_statusdoesbinwrite(comments=None)wrote the word "None" into the headertest_io.pyskipped itself on Windows, since 2021dlopen) went away with #157; run it there_capture_c_output(a test helper) hung when a call printed more than a pipe holdsEvidence
Before: each new test fails on 1dec9b0.
python -Oit read the file. Every corruption read without error.test_binread_invalid_matrix_frees_only_its_owngets UninitializedObject there).After, locally (macOS arm64):
--parallel-threads=4 --iterations=10: the same.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:
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.
floatorstrnow 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 asnp.float32,DecimalandFraction, are still truncated, because that's how cffi converts toint32_t.deserialize_vector, raises InvalidObject. That adds the costs above to every call.test_io.pyand binread's memory check there for the first time, and both pass.