Skip to content

Fix wrong answers from select by A.T, coo import and isclose - #668

Merged
eriknw merged 9 commits into
mainfrom
60-wrong-answer-fixes
Nov 13, 2026
Merged

eriknw merged 9 commits into
mainfrom
60-wrong-answer-fixes

Conversation

@eriknw

@eriknw eriknw commented Nov 12, 2026

Copy link
Copy Markdown
Member

Taken from #663 so that it can be reviewed and merged before the release. These are wrong answers with built-in types, all on main and in 2025.2.0. Each commit has its test and gives before and after in its message.

Select by a transposed comparison as by its mask, not by the untransposed one (on main since #252). A.select(A.T == x) was rewritten to select.valueeq(A, x), dropping the transpose: with S holding (0, 1) = 1 and (1, 0) = 5, S.select(S.T == 1) gave (0, 1) = 1 instead of (1, 0) = 5, and a 2 x 3 matrix gave a result instead of DimensionMismatch. Only A.select(A == x) is rewritten now; anything else takes the mask path. With autocompute=False, A.select(A.T == x) now raises "Use .new()", as A.select(B == x) always has.

Silent data loss in coo import (on main since 2021). Count each row's entries when importing coo, so empty rows keep indptr whole: import_coor and import_cooc, and so import_any of export("coo", sort=True), "coor" or "cooc", moved entries to another row when a row (or column) other than the first was empty. They lost every entry when the last one was, and isequal still said True. An index at or beyond nrows or ncols now raises IndexOutOfBound, where it was written past the end of indptr. Read 2-D coo indices as a flat buffer, and count them with numpy without Numba keeps that working for indices given as a 2-D array, and without Numba.

isclose.

  • Say an infinity is close only to itself in isclose, as math.isclose does. Scalar.from_value(inf).isclose(1.0), .isclose(-inf) and the Vector and Matrix forms were True, with Numba and without (main since 2023); numpy and math.isclose say False.
  • Compute isclose on integers without wrapping in x - y or abs(x). UINT64 0 was close to 2**64 - 1, INT64 -2**63 to 2**63 - 1, and with Numba UINT8 5 and 6 were not close at rel_tol=0.5. Mixed integer types went wrong the same ways, and Scalar.isclose raised OverflowError for a UINT64 above INT64's maximum.
  • Keep the imaginary part of x - y in isclose without Numba: without Numba, a complex difference lost it.

Freed memory after a failed export. Clear an exported object's handle as soon as GraphBLAS frees it: an error after the export left the handle pointing at the freed object, so A.nvals read freed memory, and a collected copy was freed twice (which aborted the process on SuiteSparse 7.4).

Decision taken (easy to reverse)

decision why
isclose on two integers takes the exact difference math.isclose and numpy convert x and y to float first, so isclose(2**62 + 1, 2**62, rel_tol=0) is True for them and False here. The code already did this wherever nothing wrapped, and with zero tolerances isclose then equals isequal. Converting to float first instead is a one-line change.

Differences from the commits in #663

The select and isclose commits leave out what concerns code that is not on main: #663's UDT select test, and its branch of Scalar.isclose for an int beyond 64 bits. #663 keeps those, with a commit that gives that branch the infinity rule from here. "Export an iso UDT matrix as coo" stays in #663 too: it reads the value with the UDT iterator that #605 adds. The export-handle test imports NullPointer, which test_matrix.py did not import on main. The tree at the top of the stack is unchanged by the move.

Checked locally on SuiteSparse:GraphBLAS 10.5.2: the full suite with --runslow, without Numba on both backends, and with C scalars as CI's second pass makes them.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.88%. Comparing base (52dc9b4) to head (5047fa7).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #668      +/-   ##
==========================================
- Coverage   98.96%   98.88%   -0.09%     
==========================================
  Files         105      105              
  Lines       31456    31641     +185     
  Branches     3665     3693      +28     
==========================================
+ Hits        31132    31289     +157     
- Misses        216      228      +12     
- Partials      108      124      +16     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@eriknw
eriknw force-pushed the 60-wrong-answer-fixes branch 8 times, most recently from 3083fed to 3a214e1 Compare November 13, 2026 04:32
Base automatically changed from 27-check-mask-move to main November 13, 2026 04:33
…osed one

select._match_expr rewrote A.select(A.T == x) as select.valueeq(A, x):
its clause "args[0] is parent or args[0].T is parent" matched the
transpose of the parent, and the rewrite then compared A itself, dropping
the transpose and, for a matrix that is not square, the dimension check:

    S = Matrix.from_coo([0, 1], [1, 0], [1, 5], nrows=2, ncols=2)
    S.select(S.T == 1)
    before: (0, 1) = 1
    after:  (1, 0) = 5, as S.select((S.T == 1).new()) gives
    B (2 x 3): B.select(B.T == 1)
    before: a 2 x 3 result
    after:  DimensionMismatch

The clause is now "args[0] is parent"; anything else takes the mask path.
On main since #252.
GraphBLAS frees the Matrix or Vector as it hands the arrays over in an
export. _export gave GraphBLAS a copy of the handle and cleared the
object's own handle only at the end, so an error in between, such as
psg's claim_buffer_2d raising for an array UDT, left that handle
pointing at the freed object:

    A.ss.export(format, give_ownership=True) raising after the export,
    then A.nvals
    before: UninitializedObject (a read of freed memory)
    after:  NullPointer, as after an export that succeeds

A plain export, of a copy, also freed that copy a second time when it
was collected, which can abort the process (it did on SuiteSparse 7.4).
GraphBLAS now gets the object's own handle, which it sets to NULL.
isclose used math.isclose's formula without its infinity check. With an
infinite x or y, abs(x - y) is inf and so is rel_tol * max(abs(x), abs(y)),
so infinity was close to every number, in binary.isclose (Vector and
Matrix isclose with Numba, Scalar.isclose) and in _isclose_recipe (without
Numba):

    Scalar.from_value(inf).isclose(1.0), .isclose(-inf)
    Vector.from_coo([0], [inf]).isclose(Vector.from_coo([0], [1.0]))
    before: True (all three)
    after:  False, as math.isclose and numpy.isclose say

Two infinities of the same sign are equal, and so still close; NaN is
still close to nothing.
isclose computed abs(x - y) and abs(x) in the integer type, where they
wrap: in UINT64, and with Numba in uint64 for any unsigned type (Numba
widens to 64 bits); in INT64 at its extremes, as is abs(-2**63); and
without Numba in every integer type. So, for Vector, Matrix and Scalar:

    UINT64 [0] and [2**64 - 1]:            before True, after False
    UINT8 or UINT32 5 and 6, rel_tol=0.5:  before False, after True
    INT64 -2**63 and 2**63 - 1:            before True, after False
    INT8 -128 and 127, rel_tol=0.5:        before True without Numba,
                                           after False

and Scalar.isclose raised OverflowError for a UINT64 value above INT64's
maximum, because Numba typed the Python int as int64. The difference is
now exact (in uint64, for an integer type), the magnitudes are in FP64,
and Scalar.isclose passes its values in the op's input types, as
ewise_mult does. Mixed types are compared in the type they unify to, as
before, so INT64 with UINT64 is in FP64.
_isclose_recipe, which Vector and Matrix isclose use without Numba,
stored x - y in an FP64 Vector before taking abs, and so kept only the
real part of a complex difference:

    Vector.from_coo([0], [0j]).isclose(Vector.from_coo([0], [1j]))
    before: True without Numba (False with it)
    after:  False, as cmath.isclose says

abs is now taken in the complex type first. abs(x) and abs(y) are taken
in the type x - y is in, as the Numba op does, so an FC32 operand beside
an FP64 one is not rounded to FP32 first.
…r whole

import_coor and import_cooc build CSR (or CSC) index pointers with
indices_to_indptr, which set indptr only at the rows that appear. Every
empty row after the first one left a 0 in indptr, so an empty row in
the middle moved entries to another row, and an empty last row lost
every entry. Exporting as "coo" with sort=True, as "coor" or as "cooc"
and importing back hit it, on main since 2021:

    A = Matrix.from_coo([0, 2], [1, 0], [1.0, 2.0], nrows=3, ncols=2)
    B = Matrix.ss.import_any(**A.ss.export("coo", sort=True))
    before: B holds (2, 1) and (2, 0), and A.isequal(B) said True
    after:  B holds (0, 1) and (2, 0), as A does
    A = Matrix.from_coo([0, 0], [0, 1], [1.0, 2.0], nrows=3, ncols=2)
    before: the round trip gives an empty Matrix
    after:  both entries

It now counts the entries of each row, then sums them. The indices are
converted to uint64 first, so lists work, and one at or beyond nrows (or
ncols) raises IndexOutOfBound, where it was written past the end of
indptr with no bounds check under Numba.
…out Numba

The new indptr kernel for import_coor and import_cooc indexed a 2-D rows
(or cols) array by its rows, past the end of its first axis:

    rows = np.array([[0, 1], [1, 2]], np.uint64)
    Matrix.ss.import_coor(rows=rows, cols=[0, 0, 1, 1], values=[1, 2, 3, 4],
                          nrows=3, ncols=2)
    before: Segmentation fault with Numba; IndexError without it
    after:  the Matrix from_coo(rows.ravel(), ...) gives, as other
            imports read 2-D indices

Without Numba the kernel ran in Python, once per entry and once per row
(1.1 s for 10**7 rows and 10**5 entries, where the old kernel took 12 ms).
It now counts with np.bincount and sums with np.cumsum (20 ms).
Without Numba, Scalar.isclose passed the Python values straight to the
isclose function. Every other path compares in the type the two dtypes
unify to: Vector and Matrix isclose, and Scalar.isclose with Numba,
which passes its values in the op's input types. INT64 and UINT64 unify
to FP64, where 2**62 + 1 rounds to 2**62:

    Scalar.from_value(2**62 + 1).isclose(
        Scalar.from_value(2**62, dtype="UINT64"), rel_tol=0)
    with Numba, and Vector.isclose of the same:  True
    Scalar.isclose without Numba:  False, now True

The values are converted to that type and back to Python numbers, so
x - y still cannot wrap.
The indices_to_indptr docstring told how the old kernel lost entries,
which the commit that fixed it already says. It now states the
invariant: every empty row gets an empty range. The select test's
docstring no longer names main as a reference point.
@eriknw
eriknw force-pushed the 60-wrong-answer-fixes branch from 3a214e1 to 5047fa7 Compare November 13, 2026 04:33
@eriknw

eriknw commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

There are a few things going on in this branch, but this seems probably okay at a glance.

@eriknw
eriknw merged commit 63830fd into main Nov 13, 2026
2 of 4 checks passed
@eriknw
eriknw deleted the 60-wrong-answer-fixes branch November 13, 2026 04:36
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