diff --git a/pgvector/sparsevec.py b/pgvector/sparsevec.py index 0d3434c..a76cea2 100644 --- a/pgvector/sparsevec.py +++ b/pgvector/sparsevec.py @@ -100,6 +100,8 @@ def _from_dict(self, d: dict[int, float], dim: int) -> None: self._dim = int(dim) self._indices = [int(v[0]) for v in elements] + if any(i < 0 or i >= self._dim for i in self._indices): + raise ValueError('sparsevec index out of bounds') self._values = [float(v[1]) for v in elements] def _from_sparse(self, arr: sparray | spmatrix, /) -> None: diff --git a/tests/test_sparse_vector.py b/tests/test_sparse_vector.py index 262e23a..986d87c 100644 --- a/tests/test_sparse_vector.py +++ b/tests/test_sparse_vector.py @@ -45,6 +45,11 @@ def test_dict(self) -> None: def test_dict_empty(self) -> None: assert SparseVector({}, 0).to_list() == [] + @pytest.mark.parametrize('index', [-1, 3]) + def test_dict_index_out_of_bounds(self, index: int) -> None: + with pytest.raises(ValueError, match='sparsevec index out of bounds'): + SparseVector({index: 1}, 3) + def test_dict_no_dimensions(self) -> None: with pytest.raises(ValueError) as error: SparseVector({0: 1, 2: 2, 4: 3}) # type: ignore