IndexFlat: Reconstruct validate if key < ntotal (#4415)

Summary:
Pull Request resolved: https://github.com/facebookresearch/faiss/pull/4415

https://github.com/facebookresearch/faiss/issues/4413: Customer report an issue when index.reconstruct resulted in an undefined behavior.

Reviewed By: pankajsingh88

Differential Revision: D77549128

fbshipit-source-id: d588380c7315a92376f64cef174f1128a856b2e7
This commit is contained in:
Trang Nguyen
2025-07-01 10:16:55 -07:00
committed by Facebook GitHub Bot
parent aad35f8bca
commit 22d9642633
2 changed files with 22 additions and 1 deletions
+1
View File
@@ -239,6 +239,7 @@ FlatCodesDistanceComputer* IndexFlat::get_FlatCodesDistanceComputer() const {
}
void IndexFlat::reconstruct(idx_t key, float* recons) const {
FAISS_THROW_IF_NOT(key < ntotal);
memcpy(recons, &(codes[key * code_size]), code_size);
}
+21 -1
View File
@@ -646,7 +646,7 @@ class TestReconsException(unittest.TestCase):
index.reconstruct, 100001
)
def test_reconstuct_after_add(self):
def test_reconstruct_after_add(self):
index = faiss.index_factory(10, 'IVF5,SQfp16')
index.train(faiss.randn((100, 10), 123))
index.add(faiss.randn((100, 10), 345))
@@ -657,6 +657,26 @@ class TestReconsException(unittest.TestCase):
index.reconstruct(5)
index.reconstruct(150)
def test_reconstruct_larger_ntotal(self):
vect_dim = 5
n_vectors = 10
# Create the dataset
data = np.random.randint(100, size=(n_vectors, vect_dim))
# Build index
index = faiss.IndexFlatL2(vect_dim)
index.add(data)
# Reconstruct < ntotal (10) without an issue
index.reconstruct(9)
# Reconstruct >= ntotal (10), assert exception raise
self.assertRaises(
RuntimeError,
index.reconstruct, 10
)
class TestReconsHash(unittest.TestCase):