MongoDBAtlasDocumentStore: DuplicatePolicy.FAIL / NONE never raises, duplicate IDs are inserted (store does not create a unique index on `id`)

Aperta
#4,265 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
Mezza giornata
Idoneità per principianti
74/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
mongodb, python
Ambito
databases

Direzione di ricerca

Start in integrations/mongodb_atlas/src/haystack_integrations/document_stores/mongodb_atlas/document_store.py at the FAIL branches (lines 738, 785) and _ensure_connection_setup/_ensure_connection_setup_async; AzureDocumentDBDocumentStore._ensure_connection_setup already does the index creation. tests/conftest.py line 70 adds the unique index by hand, masking the bug—run the mongodb_atlas tests without it. Done when both setup paths create the unique id index, the docstring notes it, and a test expects DuplicateDocumentError on a repeated id; the pre-existing-duplicates question needs a maintainer decision.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

integration:mongodb-atlas P2

Describe the bug

MongoDBAtlasDocumentStore.write_documents does not enforce DuplicatePolicy.FAIL (or NONE, which it maps to FAIL). Writing a document whose ID is already stored inserts a second copy instead of raising DuplicateDocumentError. Re-running an indexing pipeline with the default DocumentWriter duplicates every document.

Cause

At 8249f30, in integrations/mongodb_atlas/src/haystack_integrations/document_stores/mongodb_atlas/document_store.py, the FAIL branch issues plain InsertOne operations (line 738, async line 785) and relies on MongoDB rejecting them. Documents are keyed by the id field, not _id, so MongoDB only rejects the insert if the collection has a unique index on id.

The store never creates that index, and neither the class docstring nor the init parameters mention that one is needed. The test suite passes because tests/conftest.py (line 70) creates it by hand: database[collection_name].create_index("id", unique=True).

AzureDocumentDBDocumentStore in this repo, which uses the same write logic, creates the index itself in _ensure_connection_setup.

To Reproduce

Against mongodb/mongodb-atlas-local, on a collection created with create_collection only:

import os
from uuid import uuid4
from haystack import Document
from haystack.components.writers import DocumentWriter
from haystack.document_stores.types import DuplicatePolicy
from haystack_integrations.document_stores.mongodb_atlas import MongoDBAtlasDocumentStore
from pymongo import MongoClient

DB, COLLECTION = "haystack_repro", "docs_" + uuid4().hex[:8]
client = MongoClient(os.environ["MONGO_CONNECTION_STRING"])
client[DB].create_collection(COLLECTION)

store = MongoDBAtlasDocumentStore(database_name=DB, collection_name=COLLECTION,
                                  vector_search_index="unused", full_text_search_index="unused")
doc = Document(id="A", content="original")

for label, write in [
    ("write_documents(policy=FAIL)", lambda: store.write_documents([doc], policy=DuplicatePolicy.FAIL)),
    ("write_documents() default", lambda: store.write_documents([doc])),
    ("DocumentWriter default", lambda: DocumentWriter(document_store=store).run(documents=[doc])),
]:
    try:
        write(); result = "no error"
    except Exception as e:
        result = "RAISE " + type(e).__name__
    print(f"{label:30} -> {result:12} count_documents={store.count_documents()}")
print("stored ids:", [d["id"] for d in client[DB][COLLECTION].find()])

Output:

write_documents(policy=FAIL)   -> no error    count_documents=1
write_documents() default      -> no error    count_documents=2
DocumentWriter default         -> no error    count_documents=3
stored ids: ['A', 'A', 'A']

Expected: the second and third writes raise DuplicateDocumentError and the count stays at 1.

Suggested fix

Create the unique index on id in _ensure_connection_setup and _ensure_connection_setup_async, as AzureDocumentDBDocumentStore does, and document it. One open question: on an existing collection that already contains duplicate IDs, create_index will fail. Should the store raise a DocumentStoreError explaining the problem, or log a warning and continue?

Happy to open a PR with tests once the direction is confirmed.

Describe your environment (please complete the following information):

  • OS: Windows 11 (NT 10.0.26200)
  • Haystack version: haystack-ai 3.5.0
  • Integration version: mongodb-atlas-haystack 5.0.0
  • pymongo: 4.20.0
  • MongoDB: mongodb/mongodb-atlas-local Docker image
  • Python: 3.13.15
Lingua principale
Python
Stelle
212
Fork
396
Merge medio
2g 9h
PR unite (30g)
95

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di deepset-ai/haystack-core-integrations

Tutte le issue di deepset-ai/haystack-core-integrations

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.