graphrag-toolkit icon indicating copy to clipboard operation
graphrag-toolkit copied to clipboard

[BUG] LocalFaissDenseIndex returns FAISS padding as hits and reset() keeps old vectors

Open NopeCharon opened this issue 1 month ago • 0 comments

Package version

3.19.1 (current main)

Package

byokg-rag

Python version

3.11

Operating System

Linux

Description

LocalFaissDenseIndex turns FAISS's "no result" slots into real hits, and reset() leaves the old vectors in the FAISS index.

Padding read as the last document. FAISS fills a result row with index -1 (distance 3.4e38 for L2) when it cannot return topk vectors: the index holds fewer than topk vectors, or an id_selector allows fewer ids than topk. query() and match() use the index directly, as in self.doc_ids[match_idx] (indexing/dense_index.py:83-86 and 104-107), so -1 reads the last stored document. The results:

  • query(..., topk=5) on a 3-document index returns the last document three times.
  • query(..., id_selector=[...]) can return a document the selector excludes.
  • Querying an empty index raises IndexError. test_dense_index_query_empty_index currently asserts this and calls it a known limitation.

EntityLinker and query() callers then treat those padded slots as matches.

reset() keeps the vectors. reset() clears doc_store, doc_ids and id2idx but not self.faiss_index. Vector positions are then out of step with the documents: after reset() and add(), a query near a discarded vector returns whichever new document now sits at that position, with the discarded vector's distance. It can also raise IndexError when the old position is past the new documents.

Steps to reproduce

import numpy as np
from unittest.mock import Mock
from graphrag_toolkit.byokg_rag.indexing import LocalFaissDenseIndex

emb = Mock()
emb.embed.return_value = [1.0, 0.0, 0.0, 0.0]
index = LocalFaissDenseIndex(embedding=emb, embedding_dim=4)
index.add_with_ids(['company1', 'company2', 'company3'],
                   ['Amazon', 'Microsoft', 'Google'],
                   embeddings=np.eye(3, 4))

print(index.query('q', topk=3, id_selector=['company1', 'company2']))
# third hit: company3 / Google, match_score 3.4028235e+38, which the selector excludes

print(index.query('q', topk=5))
# company3 / Google appears twice more, each with match_score 3.4028235e+38

index.reset()
index.add(['Google'], embeddings=np.array([[0.0, 0.0, 1.0, 0.0]]))
print(index.query('q', topk=1))
# {'hits': [{'document_id': 'doc0', 'document': 'Google', 'match_score': 0.0}]}
# distance 0.0 is the discarded 'Amazon' vector; Google is at distance 2.0

Suggested fix

Skip result slots whose index is -1 in query() and match(), and call self.faiss_index.reset() in reset().

NopeCharon avatar Oct 30 '26 06:10 NopeCharon