OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
Scope chunk IDs by owner (#2109)
Edwin Josec6d2e9293506
diff --git a/src/models/processors.py b/src/models/processors.pyindex c8b7bee4a..a45171705 100644--- a/src/models/processors.py+++ b/src/models/processors.py@@ -733,7 +733,11 @@ class DocumentFileProcessor(TaskProcessor):elif filename_exists and self.replace_duplicates:# Delete existing document before uploading new onelogger.info(f"Replacing existing document: {original_filename}")- await self.delete_document_by_filename(original_filename, opensearch_client)+ await self.delete_document_by_filename(+ original_filename,+ opensearch_client,+ owner_user_id=self.owner_user_id,+ )# Refresh index to make deletion visible before processing.# refresh is index-wide (indices:admin/refresh) and cannot be DLS-scoped,# so it must run under the admin/service client, not the user client.diff --git a/src/services/document_index_writer.py b/src/services/document_index_writer.pyindex a1eff9767..0db09b860 100644--- a/src/services/document_index_writer.py+++ b/src/services/document_index_writer.py@@ -8,6 +8,7 @@ indexing chunks into the documents index.from __future__ import annotationsimport datetime+import hashlibimport jsonfrom dataclasses import dataclass, fieldfrom typing import Any@@ -80,8 +81,8 @@ class DocumentIndexWriter:) -> dict[str, Any]:"""Index one batch of chunks.- Repeated calls with the same chunk ids are idempotent because the write- operation is an index/upsert.+ Repeated calls with the same chunk ids in the same ownership scope are+ idempotent because the write operation is an index/upsert."""from config.settings import get_index_name@@ -112,7 +113,14 @@ class DocumentIndexWriter:"Embedding dimension mismatch in batch: "f"expected {dimensions}, got {len(chunk.vector)} for {chunk.chunk_id}")- bulk_body.append({"index": {"_index": index_name, "_id": chunk.chunk_id}})+ bulk_body.append(+ {+ "index": {+ "_index": index_name,+ "_id": self._scoped_chunk_id(context, chunk.chunk_id),+ }+ }+ )bulk_body.append(self._build_chunk_document(context=context,@@ -141,6 +149,13 @@ class DocumentIndexWriter:"document_id": context.document_id,}+ @staticmethod+ def _scoped_chunk_id(context: DocumentIndexContext, chunk_id: str) -> str:+ """Keep idempotent chunk upserts isolated to one ownership scope."""+ scope = "shared" if context.owner is None else f"owner:{context.owner}"+ scope_digest = hashlib.sha256(scope.encode("utf-8")).hexdigest()[:24]+ return f"{scope_digest}_{chunk_id}"+async def delete_ingest_run(self, ingest_run_id: str, *, index_name: str | None = None) -> int:"""Delete partially indexed chunks for a failed callback run."""if not ingest_run_id:diff --git a/tests/unit/test_document_index_writer_ownership.py b/tests/unit/test_document_index_writer_ownership.pynew file mode 100644index 000000000..4e1e6740c--- /dev/null+++ b/tests/unit/test_document_index_writer_ownership.py@@ -0,0 +1,92 @@+from typing import Any++import pytest++from services.document_index_writer import (+ DocumentIndexChunk,+ DocumentIndexContext,+ DocumentIndexWriter,+)+from utils.embedding_fields import get_embedding_field_name+++class InMemoryIndices:+ async def exists(self, *, index: str) -> bool:+ return True++ async def get_mapping(self, *, index: str) -> dict[str, Any]:+ field = get_embedding_field_name("test-model")+ return {index: {"mappings": {"properties": {field: {"type": "knn_vector"}}}}}++ async def refresh(self, *, index: str) -> None:+ return None+++class InMemoryOpenSearch:+ def __init__(self) -> None:+ self.documents: dict[str, dict[str, Any]] = {}+ self.indices = InMemoryIndices()++ async def bulk(self, *, body: list[dict[str, Any]], refresh: bool | str) -> dict[str, Any]:+ for offset in range(0, len(body), 2):+ document_id = body[offset]["index"]["_id"]+ self.documents[document_id] = body[offset + 1]+ return {"errors": False}++ def visible_documents(self, owner: str) -> list[dict[str, Any]]:+ return [document for document in self.documents.values() if document.get("owner") == owner]+++def make_context(owner: str | None) -> DocumentIndexContext:+ return DocumentIndexContext(+ document_id="same-content-hash",+ filename="report.pdf",+ mimetype="application/pdf",+ embedding_model="test-model",+ owner=owner,+ )+++def make_chunk(text: str = "same file") -> DocumentIndexChunk:+ return DocumentIndexChunk(+ chunk_id="same-content-hash_0",+ text=text,+ vector=[0.1, 0.2, 0.3],+ )+++async def test_identical_chunks_remain_available_to_each_owner():+ opensearch = InMemoryOpenSearch()+ writer = DocumentIndexWriter(opensearch_client=opensearch)++ await writer.index_chunks(make_context("user-a"), [make_chunk()])+ await writer.index_chunks(make_context("user-b"), [make_chunk()])++ assert len(opensearch.documents) == 2+ assert len(opensearch.visible_documents("user-a")) == 1+ assert len(opensearch.visible_documents("user-b")) == 1+++async def test_reingesting_a_chunk_for_the_same_owner_updates_it_in_place():+ opensearch = InMemoryOpenSearch()+ writer = DocumentIndexWriter(opensearch_client=opensearch)++ await writer.index_chunks(make_context("user-a"), [make_chunk("old text")])+ await writer.index_chunks(make_context("user-a"), [make_chunk("new text")])++ assert len(opensearch.documents) == 1+ assert opensearch.visible_documents("user-a")[0]["text"] == "new text"+++async def test_reingesting_a_shared_chunk_updates_it_in_place():+ opensearch = InMemoryOpenSearch()+ writer = DocumentIndexWriter(opensearch_client=opensearch)++ await writer.index_chunks(make_context(None), [make_chunk("old shared text")])+ await writer.index_chunks(make_context(None), [make_chunk("new shared text")])++ assert len(opensearch.documents) == 1+ assert next(iter(opensearch.documents.values()))["text"] == "new shared text"diff --git a/tests/unit/test_processor_mapping_client.py b/tests/unit/test_processor_mapping_client.pyindex 24e45c38f..f0396e166 100644--- a/tests/unit/test_processor_mapping_client.py+++ b/tests/unit/test_processor_mapping_client.py@@ -132,7 +132,8 @@ async def test_standard_processor_uses_shared_writer_for_embedding_mapping_and_wassert user_client.index_calls == []assert admin_client.bulk_callsbulk_body = admin_client.bulk_calls[0]["body"]- assert bulk_body[0] == {"index": {"_index": "documents", "_id": "file-1_0"}}+ assert bulk_body[0]["index"]["_index"] == "documents"+ assert bulk_body[0]["index"]["_id"].endswith("_file-1_0")assert bulk_body[1]["document_id"] == "file-1"assert bulk_body[1]["owner"] == "user-1"assert bulk_body[1]["chunk_embedding_text_embedding_3_small"] == [0.1, 0.2, 0.3]diff --git a/tests/unit/test_traditional_duplicate_handling.py b/tests/unit/test_traditional_duplicate_handling.pyindex 50f94f601..30570f5e9 100644--- a/tests/unit/test_traditional_duplicate_handling.py+++ b/tests/unit/test_traditional_duplicate_handling.py@@ -1,6 +1,6 @@"""Unit tests for duplicate filename handling in DocumentFileProcessor."""-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import ANY, AsyncMock, MagicMock, patchimport pytest@@ -87,7 +87,11 @@ async def test_traditional_processor_duplicate_exists_with_replace():assert upload_task.successful_files == 1processor.check_filename_exists.assert_called_once()- processor.delete_document_by_filename.assert_called_once()+ processor.delete_document_by_filename.assert_awaited_once_with(+ "test.txt",+ ANY,+ owner_user_id="user-123",+ )processor.process_document_standard.assert_called_once()mock_session_manager.get_user_opensearch_client.assert_called_once_with("user-123", "mock-token"