From 1c7365faed9b63fb8e4fca57a8a21eae645ae8ad Mon Sep 17 00:00:00 2001 From: dance858 Date: Fri, 13 Nov 2026 08:48:39 -0800 Subject: [PATCH] Validate index_flat indices before casting to int32 index_flat converted indices with np.asarray(..., dtype=np.int32) before the bounds check, so 2**32 + 1 wrapped and 1.7 truncated to a valid index. An int32 array was also kept by reference, so editing it after the check reached the engine unchecked. Check dtype and range on the input, then cast (which copies). Part of #37. Co-Authored-By: Claude Opus 5.5 --- sparsediffpy/_expression.py | 5 ++++- tests/test_api.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/sparsediffpy/_expression.py b/sparsediffpy/_expression.py index d6c52a5..b178623 100644 --- a/sparsediffpy/_expression.py +++ b/sparsediffpy/_expression.py @@ -354,12 +354,15 @@ def _matmul_with_data(make, A): def index_flat(x, flat_indices, shape): """Gather entries of ``x`` by column-major flat indices into ``shape``.""" x = cast_to_const(x) - idx = np.asarray(flat_indices, dtype=np.int32).ravel() + idx = np.asarray(flat_indices).ravel() + if idx.size and not np.issubdtype(idx.dtype, np.integer): + raise TypeError(f"flat indices must be integers, got dtype {idx.dtype}") shape = _check_shape(*shape) if idx.size != shape[0] * shape[1]: raise ValueError(f"{idx.size} indices do not fill shape {shape}") if idx.size and (idx.min() < 0 or idx.max() >= x.size): raise IndexError(f"flat index out of range for size {x.size}") + idx = idx.astype(np.int32) # safe now that all are in range; also copies return Node(lambda c: _C.make_index(c, shape[0], shape[1], idx), [x], shape) diff --git a/tests/test_api.py b/tests/test_api.py index d1c7cfa..6c161e9 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -237,6 +237,21 @@ def test_index_flat_wraps_constants(scope): np.testing.assert_array_equal(fn.forward(), [[7.0]]) +def test_index_flat_checks_before_casting(scope): + """Indices are validated as given, not after conversion to int32.""" + x = scope.Variable(3, 1) + with pytest.raises(IndexError): + sp.index_flat(x, np.array([2**32 + 1]), (1, 1)) # would wrap to 1 + for bad in ([1.7], [True]): + with pytest.raises(TypeError): + sp.index_flat(x, bad, (1, 1)) + idx = np.array([0, 1], dtype=np.int32) + e = sp.index_flat(x, idx, (2, 1)) + idx[1] = 10**6 # editing the array afterwards must not reach the engine + x.value = [10.0, 20.0, 30.0] + np.testing.assert_array_equal(sp.compile(e).forward(), [[10.0], [20.0]]) + + def test_numpy_scalar_exponent(scope): x = scope.Variable(2, 1) f1, f2 = sp.compile(x ** np.int64(2)), sp.compile(x ** np.float32(2))