Skip to content

Commit 3da053a

Browse files
committed
Validate SparseVector dictionary indices
1 parent 7329d8a commit 3da053a

2 files changed

Lines changed: 7 additions & 0 deletions

File tree

‎pgvector/sparsevec.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ def _from_dict(self, d: dict[int, float], dim: int) -> None:
100100

101101
self._dim = int(dim)
102102
self._indices = [int(v[0]) for v in elements]
103+
if any(i < 0 or i >= self._dim for i in self._indices):
104+
raise ValueError('sparsevec index out of bounds')
103105
self._values = [float(v[1]) for v in elements]
104106

105107
def _from_sparse(self, arr: sparray | spmatrix, /) -> None:

‎tests/test_sparse_vector.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,11 @@ def test_dict(self) -> None:
4545
def test_dict_empty(self) -> None:
4646
assert SparseVector({}, 0).to_list() == []
4747

48+
@pytest.mark.parametrize('index', [-1, 3])
49+
def test_dict_index_out_of_bounds(self, index: int) -> None:
50+
with pytest.raises(ValueError, match='sparsevec index out of bounds'):
51+
SparseVector({index: 1}, 3)
52+
4853
def test_dict_no_dimensions(self) -> None:
4954
with pytest.raises(ValueError) as error:
5055
SparseVector({0: 1, 2: 2, 4: 3}) # type: ignore

0 commit comments

Comments
 (0)