diff --git a/docs/modules/rag.md b/docs/modules/rag.md index 310f6e39..03c56b63 100644 --- a/docs/modules/rag.md +++ b/docs/modules/rag.md @@ -362,14 +362,20 @@ if __name__ == "__main__": |--------|-------------|------------|--------------| | `__init__` | Initializes the RAGEngine with RAG and storage configurations. | `config: RAGConfig`, `storage_handler: StorageHandler` | None | | `read` | Loads and chunks documents into a corpus. | `file_paths`, `exclude_files`, `filter_file_by_suffix`, `merge_by_file`, `show_progress`, `corpus_id` | `Corpus` | -| `add` | Adds nodes to an index for a specific corpus. | `index_type`, `nodes`, `corpus_id` | None | +| `add` | Adds nodes to an index for a specific corpus. | `index_type`, `nodes`, `corpus_id` | Inserted chunk IDs; `[]` on failure | | `delete` | Deletes nodes or an entire index from a corpus. | `corpus_id`, `index_type`, `node_ids`, `metadata_filters` | None | | `clear` | Clears indices for a specific corpus or all corpora. | `corpus_id` | None | | `save` | Saves indices to files or a database. | `output_path`, `corpus_id`, `index_type`, `table` | None | -| `load` | Loads indices from files or a database. | `source`, `corpus_id`, `index_type`, `table` | None | +| `load` | Loads indices from files or a database. | `source`, `corpus_id`, `index_type`, `table` | Loaded chunk IDs | | `query` | Executes a query and returns processed results. | `query`, `corpus_id`, `query_transforms` | `RagResult` | ## Notes - **Query Transforms**: The `query` method supports optional query transforms for preprocessing, which can be customized to enhance retrieval (e.g., HyDE, query decomposition). - **Storage Backend**: Ensure `StorageHandler` is properly configured to handle vector and metadata storage. -- **Warning**: Loading indices multiple times may cause issues (e.g., duplicate node insertion in vector stores). Clear indices before reloading. \ No newline at end of file +- **Corpus ownership**: Each vector index has its own FAISS backend. Chunk IDs may repeat across corpora; querying, updating or deleting one corpus does not affect another. `add(nodes=corpus, ...)` uses the corpus's ID unless an explicit `corpus_id` is supplied. +- **Batch updates**: A repeated chunk ID replaces its prior value; within one batch the final value wins. Embedding or storage failures preserve the previous vector index. Direct `VectorIndexing.insert_nodes` callers receive the error, while `RAGEngine.add` retains its `[]` failure result. Batch related updates to reduce LlamaIndex catalog serialization overhead. +- **Snapshot replacement**: Loading a vector snapshot replaces the selected index, including removal of nodes absent from the snapshot. Repeated loads are safe. Configure the same embedding model, dimensions and modality as the saved data; incompatible snapshots fail before replacing live vector indices. +- **Portable files**: New snapshots use a metadata pointer, immutable JSONL content and a checksum. Keep the referenced files together. Older JSONL/metadata pairs remain readable; saving into their directory upgrades the selected snapshot. Prior content generations remain available for readers already using them, so repeated saves can grow the directory. +- **Database snapshots**: Multiple index types share a versioned payload in the existing corpus row. Saving one type preserves the others, and legacy single-index rows need no schema migration. `StorageHandler.load_index(..., index_type="vector")` selects one payload. +- **Deletion selectors**: Omitting both node selectors deletes the selected index. Explicit empty node IDs or metadata filters select no nodes; an empty corpus selector does not clear all corpora. +- **Graph persistence**: Graph indices retain their external backend lifecycle; the vector rollback guarantees do not imply a distributed transaction with a graph database. \ No newline at end of file diff --git a/evoagentx/rag/indexings/_transaction.py b/evoagentx/rag/indexings/_transaction.py new file mode 100644 index 00000000..a5f60b45 --- /dev/null +++ b/evoagentx/rag/indexings/_transaction.py @@ -0,0 +1,62 @@ +"""A delta journal for the in-memory catalogs used by vector indexing.""" +from contextlib import contextmanager +from copy import deepcopy +from typing import Any, Dict, Iterator, Optional, Tuple + +from llama_index.core.storage.kvstore.simple_kvstore import SimpleKVStore +from llama_index.core.storage.kvstore.types import DEFAULT_COLLECTION + + +class JournaledKVStore(SimpleKVStore): + """Undo writes to node, reference-document and index catalog records. + + Only changed keys are retained. In particular, adding a node does not copy + the text/metadata of every existing node. Serialized index records contain + immutable JSON strings, so journaling them does not duplicate that payload. + Reads are detached because LlamaIndex may update nested reference-node lists + while preparing a subsequent put; a shallow read would change live state + before the journal had a chance to capture it. + """ + + def __init__(self): + super().__init__() + self._journal: Optional[Dict[Tuple[str, str], Any]] = None + + @contextmanager + def transaction(self) -> Iterator[None]: + """Restore every changed record if the enclosing vector write fails.""" + if self._journal is not None: + yield + return + self._journal = {} + try: + yield + except BaseException: + for (collection, key), previous in reversed(list(self._journal.items())): + if previous is None: + super().delete(key, collection=collection) + else: + super().put(key, previous, collection=collection) + raise + finally: + self._journal = None + + def _remember(self, key: str, collection: str) -> None: + """Capture a key's original value once per transaction.""" + identity = (collection, key) + if self._journal is not None and identity not in self._journal: + self._journal[identity] = deepcopy(super().get(key, collection=collection)) + + def get(self, key: str, collection: str = DEFAULT_COLLECTION): + """Return detached data so nested caller changes cannot bypass journaling.""" + return deepcopy(super().get(key, collection=collection)) + + def put(self, key: str, val: dict, collection: str = DEFAULT_COLLECTION) -> None: + """Record the prior value before publishing a catalog record.""" + self._remember(key, collection) + super().put(key, deepcopy(val), collection=collection) + + def delete(self, key: str, collection: str = DEFAULT_COLLECTION) -> bool: + """Record a deletion before removing the catalog record.""" + self._remember(key, collection) + return super().delete(key, collection=collection) diff --git a/evoagentx/rag/indexings/vector_index.py b/evoagentx/rag/indexings/vector_index.py index 2a505801..aebafe88 100644 --- a/evoagentx/rag/indexings/vector_index.py +++ b/evoagentx/rag/indexings/vector_index.py @@ -1,203 +1,196 @@ -import asyncio +"""Corpus-owned vector indexing with atomic updates to all node catalogs.""" +from contextlib import contextmanager from typing import List, Dict, Any, Union, Optional, Sequence -from llama_index.core.schema import BaseNode +from llama_index.core.schema import BaseNode, ImageNode, NodeWithScore from llama_index.core import VectorStoreIndex from llama_index.core.storage import StorageContext +from llama_index.core.storage.docstore import SimpleDocumentStore +from llama_index.core.storage.index_store import SimpleIndexStore from llama_index.core.embeddings import BaseEmbedding from .base import BaseIndexWrapper, IndexType -from evoagentx.rag.schema import Chunk -from evoagentx.core.logging import logger +from ._transaction import JournaledKVStore +from evoagentx.rag.schema import Chunk, ImageChunk from evoagentx.storages.base import StorageHandler + class VectorIndexing(BaseIndexWrapper): - """Wrapper for LlamaIndex VectorStoreIndex.""" + """Own a FAISS namespace and keep its LlamaIndex catalogs consistent. + + ``storage_handler.vector_store`` supplies configuration, not shared corpus + data. Embeddings are prepared before mutation. Native changes are journaled + and LlamaIndex metadata is restored if any stage of a write fails. + """ def __init__( self, embed_model: BaseEmbedding, storage_handler: StorageHandler, - index_config: Dict[str, Any] = None + index_config: Dict[str, Any] = None, ): super().__init__() self.index_type = IndexType.VECTOR self.embed_model = embed_model self.storage_handler = storage_handler - # create a storage_context for llama_index - self._create_storage_context() - # for caching llama_index node - self.id_to_node = dict() - self.index_config = index_config or {} - try: - self.index = VectorStoreIndex( - nodes=[], - embed_model=self.embed_model, - storage_context=self.storage_context, - show_progress=self.index_config.get("show_progress", False) - ) - except Exception as e: - logger.error(f"Failed to initialize VectorStoreIndex: {str(e)}") - raise - - def _create_storage_context(self, ): - # Construct a storage_context for llama_index - assert self.storage_handler.vector_store is not None, "VectorIndexing must init a vector backend in 'storageHandler'" + self.id_to_node = {} + self._create_storage_context() + self.index = VectorStoreIndex( + nodes=[], + embed_model=self.embed_model, + storage_context=self.storage_context, + show_progress=self.index_config.get("show_progress", False), + ) + # The same lock must cover search and docstore resolution. Keeping the + # LlamaIndex object stable preserves callers of get_index(). + self.index._evoagentx_mutation_lock = self.mutation_lock + + def _create_storage_context(self): + """Create an independent backend using the supported FAISS wrapper.""" + template = self.storage_handler.vector_store + if template is None: + raise ValueError("VectorIndexing requires a configured vector backend") + if not callable(getattr(template, "create_empty", None)): + raise TypeError("Vector backend must support isolated create_empty() stores") + self.vector_store = template.create_empty() + backend = self.vector_store.get_vector_store() + self.mutation_lock = backend.mutation_lock + self._catalog = JournaledKVStore() self.storage_context = StorageContext.from_defaults( - vector_store=self.storage_handler.vector_store.get_vector_store() + vector_store=backend, + docstore=SimpleDocumentStore(simple_kvstore=self._catalog), + index_store=SimpleIndexStore(simple_kvstore=self._catalog), ) + return self.storage_context def get_index(self) -> VectorStoreIndex: + """Return the stable LlamaIndex object backing this corpus.""" return self.index - - def insert_nodes(self, nodes: List[Union[Chunk, BaseNode]]) -> Sequence[str]: - """ - Insert or update nodes into the vector index. - - Converts Chunk objects to LlamaIndex nodes, serializes metadata as JSON strings, and inserts - them into the VectorStoreIndex. Nodes are cached in id_to_node for quick access. - Args: - nodes (List[Union[Chunk, BaseNode]]): List of nodes to insert, either Chunk or BaseNode. - - Returns: + @contextmanager + def _write_transaction(self, node_ids): + """Journal changed native vectors, catalog records and index entries. + The undo state is proportional to the batch, not the corpus. LlamaIndex + still serializes its index-ID mapping on each write, as it did before; + no additional full corpus or native embedding copy is introduced here. """ - try: - filtered_nodes = [] - for node in nodes: - llama_node = node.to_llama_node() if isinstance(node, Chunk) else node - node_id = llama_node.id if hasattr(llama_node, "id") else llama_node.id_ - if node_id in self.id_to_node: - # Delete the node - self.delete_nodes([node_id]) - logger.info(f"Find the same node in vector database: {node_id}. Update it.") - - filtered_nodes.extend([llama_node]) - - # TODO: find a better way to manage the node - # Caching the node - nodes_with_embedding = self.index._get_node_with_embedding(nodes=filtered_nodes) - for node in nodes_with_embedding: - self.id_to_node[node.node_id] = node.model_copy() - self.index.insert_nodes(nodes_with_embedding) - logger.info(f"Inserted {len(nodes_with_embedding)} nodes into VectorStoreIndex") - return list([n.node_id for n in filtered_nodes]) - - except Exception as e: - logger.error(f"Failed to insert nodes: {str(e)}") - return [] + with self.mutation_lock: + mapping = self.index.index_struct.nodes_dict + previous = {identifier: mapping.get(identifier) for identifier in node_ids} + try: + with self.vector_store.get_vector_store().transaction(): + with self._catalog.transaction(): + yield + except BaseException: + for identifier, old_value in previous.items(): + if old_value is None: + mapping.pop(identifier, None) + else: + mapping[identifier] = old_value + raise + + @staticmethod + def _prepare_nodes(nodes): + """Copy inputs and keep the final value of duplicate IDs in a batch.""" + prepared = {} + for node in nodes: + if isinstance(node, NodeWithScore): + node = node.node + if isinstance(node, (Chunk, ImageChunk)): + node = node.to_llama_node() + if not isinstance(node, BaseNode): + raise TypeError("Expected Chunk, ImageChunk, BaseNode or NodeWithScore") + if not node.node_id: + raise ValueError("Node IDs must be nonempty") + prepared[node.node_id] = node.model_copy(deep=True) + return list(prepared.values()) - def delete_nodes(self, node_ids: Optional[List[str]] = None, - metadata_filters: Optional[Dict[str, Any]] = None) -> None: - """ - Delete nodes from the vector index based on node IDs or metadata filters. - - Removes specified nodes from the index and the id_to_node cache. If metadata_filters are - provided, nodes matching the filters are deleted. + def insert_nodes(self, nodes: List[Union[Chunk, BaseNode]]) -> Sequence[str]: + """Insert or replace a batch without losing the prior state on failure. - Args: - node_ids (Optional[List[str]]): List of node IDs to delete. Defaults to None. - metadata_filters (Optional[Dict[str, Any]]): Metadata filters to select nodes for deletion. Defaults to None. + The final occurrence of a duplicate ID wins. Callers retain ownership + of their input objects; neither metadata nor embeddings are mutated. + Errors propagate to the engine, which retains its historical ``[]`` + failure result. Direct wrapper callers receive the original exception. """ - try: - if node_ids: - for node_id in node_ids: - if node_id in self.id_to_node: - self.index.delete_nodes([node_id], delete_from_docstore=False) - if self.index.storage_context.docstore._kvstore._collections_mappings.get(node_id, None) is not None: - self.index.storage_context.docstore._kvstore._collections_mappings.pop(node_id) - self.id_to_node.pop(node_id) - logger.info(f"Deleted node {node_id} from VectorStoreIndex") + prepared = self._prepare_nodes(nodes) + if not prepared: + return [] + # No live node has been deleted when embedding raises. + embedded = self.index._get_node_with_embedding(nodes=prepared) + # Validate before entering the native transaction, including embeddings + # supplied by callers rather than generated by the embedding model. + self.vector_store.get_vector_store()._prepare_batch(embedded) + identifiers = [node.node_id for node in embedded] + with self._write_transaction(identifiers): + existing = [identifier for identifier in identifiers if identifier in self.id_to_node] + if existing: + self.index.delete_nodes(existing, delete_from_docstore=True) + self.index.insert_nodes(embedded) + self.id_to_node.update({node.node_id: node for node in embedded}) + return identifiers + + def delete_nodes( + self, + node_ids: Optional[List[str]] = None, + metadata_filters: Optional[Dict[str, Any]] = None, + ) -> None: + """Delete selected nodes and their docstore/index references atomically. + Explicit IDs take precedence over metadata filters, preserving the + existing selection contract. Unknown IDs are harmless. + """ + with self.mutation_lock: + if node_ids is not None: + selected = [identifier for identifier in dict.fromkeys(node_ids) if identifier in self.id_to_node] elif metadata_filters: - nodes_to_delete = [] - for node_id, node in self.id_to_node.items(): - if all(node.metadata.get(k) == v for k, v in metadata_filters.items()): - nodes_to_delete.append(node_id) - if nodes_to_delete: - self.index.delete_nodes(nodes_to_delete, delete_from_docstore=True) - - for node_id in nodes_to_delete: - del self.id_to_node[node_id] - logger.info(f"Deleted {len(nodes_to_delete)} nodes matching metadata filters from VectorStoreIndex") + selected = [ + identifier for identifier, node in self.id_to_node.items() + if all(node.metadata.get(key) == value for key, value in metadata_filters.items()) + ] else: - logger.warning("No node_ids or metadata_filters provided for deletion") - except Exception as e: - logger.error(f"Failed to delete nodes: {str(e)}") - raise + return + if not selected: + return + with self._write_transaction(selected): + self.index.delete_nodes(selected, delete_from_docstore=True) + for identifier in selected: + self.id_to_node.pop(identifier) async def aload(self, nodes: List[Union[Chunk, BaseNode]]) -> Sequence[str]: - """ - Asynchronously load nodes into the vector index and its backend store. - - Caches nodes in id_to_node and loads them into the FAISS vector store, ensuring - no duplicates are inserted by relying on the backend's duplicate checking. - - Args: - nodes (List[Union[Chunk, BaseNode]]): The nodes to load. - - Returns: - chunk_ids (List[str]): The id of loaded chunk. - """ - try: - node_ids = self.insert_nodes(nodes) - - return node_ids - except Exception as e: - logger.error(f"Failed to load nodes into VectorStoreIndex: {str(e)}") - raise + """Load a batch using the same transactional path as insertion.""" + return self.insert_nodes(nodes) def load(self, nodes: List[Union[Chunk, BaseNode]]) -> Sequence[str]: - """ - Synchronously load nodes into the vector index. - - Args: - nodes (List[Union[Chunk, BaseNode]]): The nodes to load. - """ - return asyncio.run(self.aload(nodes)) + """Load without starting a nested event loop.""" + return self.insert_nodes(nodes) def clear(self) -> None: - """ - Clear all nodes from the vector index and its cache. - - Deletes all nodes from the VectorStoreIndex and clears the id_to_node cache. - """ - try: - - node_ids = list(self.id_to_node.keys()) - self.index.delete_nodes(node_ids, delete_from_docstore=False) - self.id_to_node.clear() - self.index.storage_context.docstore._kvstore._collections_mappings.clear() - logger.info("Cleared all nodes from VectorStoreIndex") - except Exception as e: - logger.error(f"Failed to clear index: {str(e)}") - raise - - async def _get(self, node_id: str) -> Optional[Chunk]: - """Get a node by node_id from cache or vector store.""" - try: - # Check cache first - node = self.id_to_node.get(node_id, None) - if node: - if isinstance(node, Chunk): - return node.model_copy() - return Chunk.from_llama_node(node) - - logger.warning(f"Node with ID {node_id} not found in cache or vector store") - return None - except Exception as e: - logger.error(f"Failed to get node {node_id}: {str(e)}") - return None - - async def get(self, node_ids: Sequence[str]) -> List[Chunk]: - """Get nodes by node_ids from cache or vector store.""" - try: - nodes = await asyncio.gather(*[self._get(node) for node in node_ids]) - nodes = [node for node in nodes if node is not None] - logger.info(f"Retrieved {len(nodes)} nodes for node_ids: {node_ids}") - return nodes - except Exception as e: - logger.error(f"Failed to get nodes: {str(e)}") - return [] \ No newline at end of file + """Clear this corpus without modifying another index's backend.""" + self.delete_nodes(node_ids=list(self.id_to_node)) + + def snapshot_nodes(self) -> List[BaseNode]: + """Return detached nodes from one consistent state for persistence.""" + with self.mutation_lock: + return [node.model_copy(deep=True) for node in self.id_to_node.values()] + + async def _get(self, node_id: str) -> Optional[Union[Chunk, ImageChunk]]: + """Read one detached chunk from the committed cache.""" + with self.mutation_lock: + node = self.id_to_node.get(node_id) + if node is None: + return None + node = node.model_copy(deep=True) + chunk_class = ImageChunk if isinstance(node, ImageNode) else Chunk + return chunk_class.from_llama_node(node) + + async def get(self, node_ids: Sequence[str]) -> List[Union[Chunk, ImageChunk]]: + """Read selected chunks in requested order from one committed state.""" + with self.mutation_lock: + nodes = [self.id_to_node[identifier].model_copy(deep=True) for identifier in node_ids if identifier in self.id_to_node] + return [ + (ImageChunk if isinstance(node, ImageNode) else Chunk).from_llama_node(node) + for node in nodes + ] diff --git a/evoagentx/rag/postprocessors/simple_reranker.py b/evoagentx/rag/postprocessors/simple_reranker.py index 6638c235..07b15a32 100644 --- a/evoagentx/rag/postprocessors/simple_reranker.py +++ b/evoagentx/rag/postprocessors/simple_reranker.py @@ -48,8 +48,10 @@ def postprocess(self, query: Query, results: List[RagResult]) -> RagResult: for result in results: for chunk, score in zip(result.corpus.chunks, result.scores): node = chunk.to_llama_node() + # IDs are local to a corpus. Use a request-local identity + # while postprocessors combine nodes from several corpora. + node.id_ = str(len(nodes)) nodes.append(NodeWithScore(node=node, score=score)) - # Map node ID to original chunk chunk_to_original[node.id_] = chunk # Apply postprocessors diff --git a/evoagentx/rag/rag.py b/evoagentx/rag/rag.py index 4e430c30..5c909ae3 100644 --- a/evoagentx/rag/rag.py +++ b/evoagentx/rag/rag.py @@ -1,23 +1,26 @@ -import os -import json import asyncio from uuid import uuid4 from datetime import datetime +from threading import RLock from typing import List, Union, Optional, Sequence, Dict, Any, Tuple -from llama_index.core.schema import NodeWithScore, TextNode, ImageNode, RelatedNodeInfo +from llama_index.core.schema import BaseNode, NodeWithScore, TextNode, ImageNode from .rag_config import RAGConfig from .readers import LLamaIndexReader, MultimodalReader from .indexings import IndexFactory, BaseIndexWrapper from .chunkers import ChunkFactory -from .embeddings import EmbeddingFactory, EmbeddingProvider +from .embeddings import EmbeddingFactory from .retrievers import RetrieverFactory, BaseRetrieverWrapper from .postprocessors import PostprocessorFactory from .indexings.base import IndexType from .retrievers.base import RetrieverType from .schema import Corpus, ChunkMetadata, IndexMetadata, Query, RagResult, ImageChunk, TextChunk from evoagentx.storages.base import StorageHandler -from evoagentx.storages.schema import IndexStore +from evoagentx.storages.schema import IndexStore, expand_index_record +from .snapshots import ( + IndexSnapshot, load_file_snapshots, + save_file_snapshot, snapshot_from_record, +) from evoagentx.models.base_model import BaseLLM from evoagentx.core.logging import logger @@ -25,7 +28,12 @@ class RAGEngine: def __init__(self, config: RAGConfig, storage_handler: StorageHandler, llm: Optional[BaseLLM] = None): self.config = config - self.storage_handler = storage_handler # Maybe reinit the vector_store by the load funcion. + self.storage_handler = storage_handler + # Readers hold this only while capturing registry references. Lifecycle + # writers use a separate gate so slow embedding/backend calls cannot + # block an unrelated query's event loop during registry selection. + self._registry_lock = RLock() + self._lifecycle_lock = RLock() self.embedding_factory = EmbeddingFactory() self.index_factory = IndexFactory() self.chunk_factory = ChunkFactory() @@ -155,57 +163,78 @@ def read(self, file_paths: Union[Sequence[str], str], logger.error(f"Failed to read documents for corpus {corpus_id}: {str(e)}") raise - def add(self, index_type: str, nodes: Union[Corpus, List[NodeWithScore], List[TextNode], List[ImageNode]], - corpus_id: str = None) -> None: - """Add nodes to an index for a specific corpus. - - Initializes an index if it doesn't exist and inserts nodes, updating metadata with corpus_id and index_type. + def _new_index(self, index_type: str) -> BaseIndexWrapper: + """Construct an unregistered index using the engine's embedding model.""" + return self.index_factory.create( + index_type=index_type, + embed_model=self.embed_model.get_embedding_model(), + storage_handler=self.storage_handler, + index_config=self.config.index.model_dump(exclude_unset=True) if self.config.index else {}, + llm=self.llm, + ) - Args: - index_type (str): Type of index (e.g., VECTOR, GRAPH). - nodes (Union[Corpus, List[NodeWithScore], List[TextNode]]): Nodes or Corpus to add. - corpus_id (str, optional): Identifier for the corpus. Defaults to a UUID if None. + def _new_retriever(self, index_type: str, index: BaseIndexWrapper): + """Bind a retriever to the same corpus-owned index and node catalog.""" + retriever_type = RetrieverType.GRAPH if index_type == IndexType.GRAPH else RetrieverType.VECTOR + return self.retriever_factory.create( + retriever_type=retriever_type, + llm=self.llm, + index=index.get_index(), + graph_store=index.get_index().storage_context.graph_store, + embed_model=self.embed_model.get_embedding_model(), + query=Query(query_str="", top_k=self.config.retrieval.top_k), + storage_handler=self.storage_handler, + chunk_class=self.chunk_class, + ) - Return: - return a sequence with id of each added node. - - Raises: - Exception: If index creation or node insertion fails. + @staticmethod + def _owned_nodes(nodes, corpus_id, index_type): + """Copy a caller's nodes before assigning index ownership metadata.""" + source = nodes.to_llama_nodes() if isinstance(nodes, Corpus) else nodes + owned = [] + for node in source: + if isinstance(node, NodeWithScore): + node = node.node + if isinstance(node, (TextChunk, ImageChunk)): + node = node.to_llama_node() + if not isinstance(node, BaseNode): + raise TypeError("Expected Corpus, chunks, BaseNode or NodeWithScore inputs") + node = node.model_copy(deep=True) + node.metadata.update(corpus_id=corpus_id, index_type=index_type) + owned.append(node) + return owned + + def add(self, index_type: str, nodes: Union[Corpus, List[NodeWithScore], List[TextNode], List[ImageNode]], + corpus_id: str = None) -> Sequence[str]: + """Insert a batch and publish a new corpus only after successful ingestion. + + Uses the Corpus identity when no explicit corpus_id is supplied. Input + nodes remain caller-owned. As before, ingestion failures return an empty + list; transactional vector writes retain the previous committed state. """ try: - corpus_id = corpus_id or str(uuid4()) - if corpus_id not in self.indices: - self.indices[corpus_id] = {} - self.retrievers[corpus_id] = {} - - if index_type not in self.indices[corpus_id]: - index = self.index_factory.create( - index_type=index_type, - embed_model=self.embed_model.get_embedding_model(), - storage_handler=self.storage_handler, - index_config=self.config.index.model_dump(exclude_unset=True) if self.config.index else {}, - llm=self.llm, - ) - self.indices[corpus_id][index_type] = index - self.retrievers[corpus_id][index_type] = self.retriever_factory.create( - retriever_type=self.config.retrieval.retrivel_type, - llm=self.llm, - index=index.get_index(), - graph_store=index.get_index().storage_context.graph_store, - embed_model=self.embed_model.get_embedding_model(), - query=Query(query_str="", top_k=self.config.retrieval.top_k if self.config.retrieval else 5), - storage_handler=self.storage_handler, - chunk_class=self.chunk_class - ) - - nodes_to_insert = nodes.to_llama_nodes() if isinstance(nodes, Corpus) else nodes - for node in nodes_to_insert: - node.metadata.update({"corpus_id": corpus_id, "index_type": index_type}) - nodes_ids = self.indices[corpus_id][index_type].insert_nodes(nodes_to_insert) - logger.info(f"Added {len(nodes_to_insert)} nodes to {index_type} index for corpus {corpus_id}") - return nodes_ids - except Exception as e: - logger.error(f"Failed to add nodes to {index_type} index for corpus {corpus_id}: {str(e)}") + if corpus_id is None: + corpus_id = str(nodes.corpus_id) if isinstance(nodes, Corpus) else str(uuid4()) + if not isinstance(corpus_id, str) or not corpus_id: + raise ValueError("corpus_id must be a nonempty string") + owned = self._owned_nodes(nodes, corpus_id, index_type) + if not owned: + return [] + with self._lifecycle_lock: + with self._registry_lock: + index = self.indices.get(corpus_id, {}).get(index_type) + new = index is None + if new: + index = self._new_index(index_type) + retriever = self._new_retriever(index_type, index) + identifiers = index.insert_nodes(owned) + if new: + with self._registry_lock: + self.indices.setdefault(corpus_id, {})[index_type] = index + self.retrievers.setdefault(corpus_id, {})[index_type] = retriever + return identifiers + except Exception as error: + logger.error(f"Failed to add nodes to {index_type} in corpus {corpus_id}: {error}") return [] def delete(self, corpus_id: str, index_type: Optional[str] = None, @@ -225,375 +254,186 @@ def delete(self, corpus_id: str, index_type: Optional[str] = None, Exception: If deletion fails. """ try: - if corpus_id not in self.indices: - logger.warning(f"No indices found for corpus {corpus_id}") - return - - target_indices = [index_type] if index_type else self.indices[corpus_id].keys() - for idx_type in list(target_indices): # Use list to avoid runtime modification issues - if idx_type not in self.indices[corpus_id]: - logger.warning(f"Index type {idx_type} not found for corpus {corpus_id}") - continue - - index = self.indices[corpus_id][idx_type] - if node_ids or metadata_filters: - # Convert single node_id to list for consistency - node_ids_list = [node_ids] if isinstance(node_ids, str) else node_ids - index.delete_nodes(node_ids=node_ids_list, metadata_filters=metadata_filters) - logger.info(f"Deleted nodes from {idx_type} index for corpus {corpus_id}") - else: - # Delete entire index - index.clear() - del self.indices[corpus_id][idx_type] - del self.retrievers[corpus_id][idx_type] - logger.info(f"Deleted entire {idx_type} index for corpus {corpus_id}") - - # Clean up corpus if no indices remain - if not self.indices[corpus_id]: - del self.indices[corpus_id] - del self.retrievers[corpus_id] - logger.info(f"Removed empty corpus {corpus_id}") - - except Exception as e: - logger.error(f"Failed to delete from corpus {corpus_id}, index {index_type}: {str(e)}") + with self._lifecycle_lock: + with self._registry_lock: + indices = self.indices.get(corpus_id) + if indices is None: + logger.warning(f"No indices found for corpus {corpus_id}") + return + kinds = [index_type] if index_type is not None else list(indices) + selected = [(kind, indices.get(kind)) for kind in kinds] + for kind, index in selected: + if index is None: + logger.warning(f"Index type {kind} not found for corpus {corpus_id}") + continue + if node_ids is not None or metadata_filters is not None: + identifiers = [node_ids] if isinstance(node_ids, str) else node_ids + index.delete_nodes(node_ids=identifiers, metadata_filters=metadata_filters) + else: + index.clear() + with self._registry_lock: + del self.indices[corpus_id][kind] + del self.retrievers[corpus_id][kind] + with self._registry_lock: + if not self.indices[corpus_id]: + del self.indices[corpus_id] + del self.retrievers[corpus_id] + except Exception as error: + logger.error(f"Failed to delete from corpus {corpus_id}, index {index_type}: {error}") raise def clear(self, corpus_id: Optional[str] = None) -> None: - """Clear all indices for a specific corpus or all corpora. - - Args: - corpus_id (Optional[str]): Specific corpus to clear. If None, clears all corpora. - - Raises: - Exception: If clearing fails. - """ - try: - target_corpora = [corpus_id] if corpus_id else list(self.indices.keys()) - for cid in target_corpora: - if cid not in self.indices: - logger.warning(f"No indices found for corpus {cid}") - continue - - for idx_type in list(self.indices[cid].keys()): - index = self.indices[cid][idx_type] - index.clear() - del self.indices[cid][idx_type] - del self.retrievers[cid][idx_type] - logger.info(f"Cleared {idx_type} index for corpus {cid}") + """Clear selected corpora in lifecycle order without blocking readers. - # Clean up corpus if no indices remain - del self.indices[cid] - del self.retrievers[cid] - logger.info(f"Cleared corpus {cid}") - - except Exception as e: - logger.error(f"Failed to clear indices for corpus {corpus_id or 'all'}: {str(e)}") - raise - - def save(self, output_path: Optional[str] = None, corpus_id: Optional[str] = None, - index_type: Optional[str] = None, table: Optional[str] = None, - graph_exported: bool = False) -> None: - """Save indices to files or database. - - Serializes corpus chunks to JSONL files and metadata to JSON files if output_path is provided, - or saves to the SQLite database via StorageHandler if output_path is None. - - Args: - output_path (Optional[str]): Directory to save JSONL and JSON files. If None, saves to database. - corpus_id (Optional[str]): Specific corpus to save. If None, saves all corpora. - index_type (Optional[str]): Specific index type to save. If None, saves all indices. - table (Optional[str]): Database table name for index data. Defaults to 'indexing' if None. - graph_exported (bool): If True, export graph nodes and relations for graph indices. Defaults to False. - - Raises: - Exception: If saving fails or file operations encounter errors. + The writer gate also orders this operation after an in-flight add/load, + so a pending new index cannot be published after the clear completes. """ - try: - target_corpora = [corpus_id] if corpus_id else list(self.indices.keys()) - table = table or "indexing" - - for cid in target_corpora: - if cid not in self.indices: - logger.warning(f"No indices found for corpus {cid}") + with self._lifecycle_lock: + with self._registry_lock: + corpora = [corpus_id] if corpus_id is not None else list(self.indices) + for cid in corpora: + self.delete(cid) + + def _index_snapshots(self, corpus_id, index_type, graph_exported): + """Capture detached committed data for exactly the selected indices.""" + with self._registry_lock: + selected = [ + (cid, kind, index) + for cid, indices in self.indices.items() + if corpus_id is None or cid == corpus_id + for kind, index in indices.items() + if index_type is None or kind == index_type + ] + for cid, kind, index in selected: + if kind == IndexType.GRAPH: + if not graph_exported: continue + index.build_kv_store() + nodes = index.snapshot_nodes() if hasattr(index, "snapshot_nodes") else list(index.id_to_node.values()) + corpus = Corpus.from_llama_nodes(nodes) + corpus.corpus_id = cid + vector = self.storage_handler.storageConfig.vectorConfig + graph = self.storage_handler.storageConfig.graphConfig + metadata = IndexMetadata( + corpus_id=cid, + index_type=kind, + dimension=self.embed_model.dimensions, + vector_db_type=vector.vector_name if vector else None, + graph_db_type=graph.graph_name if graph else None, + embedding_model_name=self.config.embedding.model_name, + collection_name=vector.qdrant_collection_name if vector else None, + date=str(datetime.now()), + ) + yield IndexSnapshot(metadata=metadata, corpus=corpus) - target_indices = [index_type] if index_type and index_type in self.indices[cid] else self.indices[cid].keys() - for idx_type in target_indices: - index = self.indices[cid][idx_type] - - # Skip saving for graph indices unless graph_exported is True - if idx_type == IndexType.GRAPH and not graph_exported: - logger.warning(f"Skipping save for graph index {idx_type} in corpus {cid} as graph_exported is False") - continue - - # For graph indices, include kg_nodes and kg_rels if graph_exported is True - if idx_type == IndexType.GRAPH and graph_exported: - index.build_kv_store() # FIXME: Computer's memory may increase dramatically - - # Convert index nodes to Corpus - chunks = [ - self.chunk_class.from_llama_node(node_data) - for node_id, node_data in index.id_to_node.items() - ] - corpus = Corpus(chunks=chunks, corpus_id=cid) - - # Prepare metadata - vector_config = self.storage_handler.storageConfig.vectorConfig.model_dump() if self.storage_handler.storageConfig.vectorConfig else {} - graph_config = self.storage_handler.storageConfig.graphConfig.model_dump() if self.storage_handler.storageConfig.graphConfig else {} - metadata = IndexMetadata( - corpus_id=cid, - index_type=idx_type, - collection_name=vector_config.get("qdrant_collection_name", "default_collection"), - dimension=self.embed_model.dimensions, - vector_db_type=vector_config.get("vector_name", None), - graph_db_type=graph_config.get("graph_name", None), - embedding_model_name=self.config.embedding.model_name, - date=str(datetime.now()), - ) - - if output_path: - # File-based saving - os.makedirs(output_path, exist_ok=True) - safe_cid = "".join(c if c.isalnum() or c in ["-", "_"] else "_" for c in cid) - safe_idx_type = "".join(c if c.isalnum() or c in ["-", "_"] else "_" for c in idx_type) - nodes_file = os.path.join(output_path, f"{safe_cid}_{safe_idx_type}_nodes.jsonl") - metadata_file = os.path.join(output_path, f"{safe_cid}_{safe_idx_type}_metadata.json") - - # Save corpus as JSONL - corpus.to_jsonl(nodes_file, indent=0) - logger.info(f"Saved {len(corpus.chunks)} chunks to {nodes_file}") - - # Save metadata as JSON - with open(metadata_file, "w", encoding="utf-8") as f: - json.dump(metadata.model_dump(), f, indent=2, ensure_ascii=False) - logger.info(f"Saved metadata to {metadata_file}") - else: - # Database saving - index_data = { - "corpus_id": cid, - "content": corpus.model_dump(), - "date": str(datetime.now()), - "metadata": metadata.model_dump() - } - self.storage_handler.save_index(index_data, table=table) - logger.info(f"Saved {idx_type} index with {len(corpus.chunks)} chunks for corpus {cid} to database table {table}") - - except Exception as e: - logger.error(f"Failed to save indices for corpus {corpus_id or 'all'}: {str(e)}") - raise - - def load(self, source: Optional[str] = None, corpus_id: Optional[str] = None, - index_type: Optional[str] = None, table: Optional[str] = None) -> None: - """Load indices from files or database. - - Reconstructs indices and retrievers from JSONL/JSON files or SQLite database records. - Validates the embedding model name and dimension before reinitializing the embedding model. - - Args: - source (Optional[str]): Directory containing JSONL/JSON files. If None, loads from database. - corpus_id (Optional[str]): Specific corpus to load. If None, loads all corpora. - index_type (Optional[str]): Specific index type to load. If None, loads all indices. - table (Optional[str]): Database table name for index data. Defaults to 'indexing' if None. + def save(self, output_path: Optional[str] = None, corpus_id: Optional[str] = None, + index_type: Optional[str] = None, table: Optional[str] = None, + graph_exported: bool = False) -> None: + """Save committed snapshots to portable files or the configured database. - Returns: - The Sequence with id of loaded chunk. - - Raises: - Exception: If loading fails due to file or database errors, invalid data, or unsupported embedding model/dimension. - - Warning: - Try to call this function may cause some Bugs, when you load the nodes from file or database storage systems at twice. - Because All the indexing share the same storage backend from storageHandler. - For example: - The vector database (.e.g Faiss) can insert again, even thougt there is a same node. + File metadata is published after immutable content, with a checksum and + the original logical corpus identity. Database rows retain all saved + index types in a corpus, including types not selected by this call. """ - try: - table = table or "indexing" - config_dimension = self.storage_handler.storageConfig.vectorConfig.dimensions - loaded_chunk_ids: List[str] = [] - - if source: - # File-based loading - if not os.path.exists(source): - logger.error(f"Source directory {source} does not exist") - raise FileNotFoundError(f"Source directory {source} does not exist") - - for file_name in os.listdir(source): - if not file_name.endswith("_metadata.json"): - continue - parts = file_name.split("_") - if len(parts) < 3: - logger.warning(f"Skipping invalid metadata file: {file_name}") - continue - cid = "_".join(parts[:-2]) - idx_type = parts[-2] - - if (corpus_id and corpus_id != cid) or (index_type and index_type != idx_type): - continue - - metadata_file = os.path.join(source, file_name) - nodes_file = os.path.join(source, f"{cid}_{idx_type}_nodes.jsonl") - - # Load metadata - with open(metadata_file, "r", encoding="utf-8") as f: - metadata = IndexMetadata.model_validate(json.load(f)) - - # Validate embedding model - if not self.embed_model.validate_model(self.config.embedding.provider, metadata.embedding_model_name): - raise ValueError( - f"Embedding model '{metadata.embedding_model_name}' is not supported by provider '{self.config.embedding.provider}'. " - f"Supported models: {EmbeddingProvider.SUPPORTED_MODELS.get(self.config.embedding.provider, [])}" - ) - - # Validate dimension - if metadata.dimension != config_dimension: - raise ValueError( - f"Embedding dimension {metadata.dimension} in metadata does not match configured dimension {config_dimension}." - ) - - # Load corpus - if not os.path.exists(nodes_file): - logger.warning(f"Nodes file {nodes_file} not found for metadata {metadata_file}") - continue - corpus = Corpus.from_jsonl(nodes_file, corpus_id=cid) - - # Reinitialize embedding model if needed - if metadata.embedding_model_name != self.config.embedding.model_name: - logger.info(f"Reinitializing embedding model to {metadata.embedding_model_name}") - self.embed_model = self.embedding_factory.create( - provider=self.config.embedding.provider, - model_config=self.config.embedding.model_dump(exclude_unset=True) - ) - - # Load index - chunk_ids = self._load_index(corpus, cid, idx_type) - loaded_chunk_ids.extend(chunk_ids) - logger.info(f"Loaded {idx_type} index with {len(corpus.chunks)} chunks for corpus {cid} from {nodes_file}") + for snapshot in self._index_snapshots(corpus_id, index_type, graph_exported): + if output_path is not None: + save_file_snapshot(snapshot, output_path) else: - # Database loading - records = self.storage_handler.load(tables=[table]).get(table, []) - - if not records: - logger.warning(f"No records found in table {table}") - return - - for record in records: - parsed = self.storage_handler.parse_result(record, IndexStore) - cid = parsed["corpus_id"] - idx_type = parsed["metadata"]["index_type"] - if (corpus_id and corpus_id != cid) or (index_type and index_type != idx_type): - continue - - # Reconstruct corpus - chunks = [] - for chunk_data in parsed["content"]["chunks"]: - metadata = ChunkMetadata.model_validate(chunk_data["metadata"]) - - if self.config.modality == "multimodal": - # Create ImageChunk for multimodal mode - chunk = ImageChunk( - chunk_id=chunk_data["chunk_id"], - image_path=chunk_data["image_path"], - image_mimetype=chunk_data.get("image_mimetype"), - metadata=metadata, - embedding=chunk_data["embedding"], - excluded_embed_metadata_keys=chunk_data["excluded_embed_metadata_keys"], - excluded_llm_metadata_keys=chunk_data["excluded_llm_metadata_keys"], - relationships={k: RelatedNodeInfo(**v) for k, v in chunk_data["relationships"].items()} - ) - else: - # Create TextChunk for text mode - chunk = TextChunk( - chunk_id=chunk_data["chunk_id"], - text=chunk_data["text"], - metadata=metadata, - embedding=chunk_data["embedding"], - start_char_idx=chunk_data["start_char_idx"], - end_char_idx=chunk_data["end_char_idx"], - excluded_embed_metadata_keys=chunk_data["excluded_embed_metadata_keys"], - excluded_llm_metadata_keys=chunk_data["excluded_llm_metadata_keys"], - relationships={k: RelatedNodeInfo(**v) for k, v in chunk_data["relationships"].items()} - ) - chunks.append(chunk) - - corpus = Corpus( - chunks=chunks, - corpus_id=cid, - metadata=IndexMetadata.model_validate(parsed["metadata"]) - ) - - # Validate embedding model - metadata = IndexMetadata.model_validate(parsed["metadata"]) - if not self.embed_model.validate_model(self.config.embedding.provider, metadata.embedding_model_name): - raise ValueError( - f"Embedding model '{metadata.embedding_model_name}' is not supported by provider '{self.config.embedding.provider}'. " - f"Supported models: {EmbeddingProvider.SUPPORTED_MODELS.get(self.config.embedding.provider, [])}" - ) - - # Validate dimension - if metadata.dimension != config_dimension: - raise ValueError( - f"Embedding dimension {metadata.dimension} in metadata does not match configured dimension {config_dimension}." - ) - - # Reinitialize embedding model if needed - if metadata.embedding_model_name != self.config.embedding.model_name: - logger.info(f"Reinitializing embedding model to {metadata.embedding_model_name}") - self.embed_model = self.embedding_factory.create( - provider=self.config.embedding.provider, - model_config=self.config.embedding.model_dump(exclude_unset=True) - ) - - # Load index - chunk_ids = self._load_index(corpus, cid, idx_type) - loaded_chunk_ids.extend(chunk_ids) - logger.info(f"Loaded {idx_type} index with {len(corpus.chunks)} chunks for corpus {cid} from database table {table}") - - return loaded_chunk_ids - except Exception as e: - logger.error(f"Failed to load indices: {str(e)}") - raise + self.storage_handler.save_index(snapshot.to_record(), table=table or "indexing") + + def _validate_snapshot(self, snapshot: IndexSnapshot) -> None: + """Reject incompatible data before modifying any live vector index.""" + metadata = snapshot.metadata + IndexType(metadata.index_type) + if metadata.index_type != IndexType.VECTOR: + return + vector = self.storage_handler.storageConfig.vectorConfig + if vector is None: + raise ValueError("Loading vector snapshots requires a vector backend") + if metadata.dimension != vector.dimensions: + raise ValueError( + f"Embedding dimension {metadata.dimension} does not match configured dimension {vector.dimensions}" + ) + if metadata.embedding_model_name != self.config.embedding.model_name: + raise ValueError( + f"Snapshot embedding model {metadata.embedding_model_name!r} does not match " + f"configured model {self.config.embedding.model_name!r}; configure an engine for the saved model" + ) + if not self.embed_model.validate_model(self.config.embedding.provider, metadata.embedding_model_name): + raise ValueError(f"Snapshot embedding model {metadata.embedding_model_name!r} is not supported") + if metadata.vector_db_type is not None and metadata.vector_db_type != vector.vector_name: + raise ValueError("Snapshot vector backend does not match the configured backend") + expected_image = self.config.modality == "multimodal" + if any(isinstance(chunk, ImageChunk) != expected_image for chunk in snapshot.corpus.chunks): + raise ValueError("Snapshot chunk modality does not match the configured engine") + + def load(self, source: Optional[str] = None, corpus_id: Optional[str] = None, + index_type: Optional[str] = None, table: Optional[str] = None) -> Sequence[str]: + """Replace selected vector indices with validated, isolated snapshots. + + Repeated loading is idempotent and removes nodes absent from the saved + snapshot. All selected vector indices are prepared before publication; + a parsing, compatibility, embedding or backend failure leaves the live + registry untouched. Other corpora and unselected index types are kept. + Legacy JSONL/metadata pairs and single-index DB rows remain readable. + """ + if source is not None: + snapshots = list(load_file_snapshots(source, corpus_id, index_type)) + else: + snapshots = [] + records = self.storage_handler.load(tables=[table or "indexing"]).get(table or "indexing", []) + for record in records: + parsed = self.storage_handler.parse_result(record, IndexStore) + if corpus_id is not None and parsed["corpus_id"] != corpus_id: + continue + for single in expand_index_record(parsed): + if index_type is None or single["metadata"].get("index_type") == index_type: + snapshots.append(snapshot_from_record(single)) + seen = set() + for snapshot in snapshots: + self._validate_snapshot(snapshot) + identity = (snapshot.metadata.corpus_id, snapshot.metadata.index_type) + if identity in seen: + raise ValueError(f"Multiple snapshots found for {identity}") + seen.add(identity) + with self._lifecycle_lock: + prepared = [] + identifiers = [] + for snapshot in snapshots: + cid, kind = snapshot.metadata.corpus_id, snapshot.metadata.index_type + if kind == IndexType.VECTOR: + index = self._new_index(kind) + retriever = self._new_retriever(kind, index) + owned = self._owned_nodes(snapshot.corpus, cid, kind) + loaded = index.load(owned) + if len(loaded) != len(owned): + raise RuntimeError(f"Incomplete snapshot ingestion for corpus {cid}") + prepared.append((cid, kind, index, retriever)) + identifiers.extend(loaded) + else: + # Graph persistence has its own external backend lifecycle. + # Retain that path without promising vector-style rollback. + identifiers.extend(self._load_index(snapshot.corpus, cid, kind)) + with self._registry_lock: + for cid, kind, index, retriever in prepared: + self.indices.setdefault(cid, {})[kind] = index + self.retrievers.setdefault(cid, {})[kind] = retriever + return identifiers def _load_index(self, corpus: Corpus, corpus_id: str, index_type: str) -> Sequence[str]: - """Helper method to load an index and its retriever.""" - try: - if corpus_id not in self.indices: - self.indices[corpus_id] = {} - self.retrievers[corpus_id] = {} - - if index_type not in self.indices[corpus_id]: - index = self.index_factory.create( - index_type=index_type, - embed_model=self.embed_model.get_embedding_model(), - storage_handler=self.storage_handler, - index_config=self.config.index.model_dump(exclude_unset=True) if self.config.index else {}, - llm=self.llm - ) - self.indices[corpus_id][index_type] = index - retriever_type = RetrieverType.GRAPH if index_type == IndexType.GRAPH else RetrieverType.VECTOR - self.retrievers[corpus_id][index_type] = self.retriever_factory.create( - retriever_type=retriever_type, - llm=self.llm, - index=index.get_index(), - graph_store=index.get_index().storage_context.graph_store, - embed_model=self.embed_model.get_embedding_model(), - query=Query(query_str="", top_k=self.config.retrieval.top_k if self.config.retrieval else 5), - storage_handler=self.storage_handler, - chunk_class=self.chunk_class - - ) - - nodes = corpus.to_llama_nodes() - - for node in nodes: - node.metadata.update({"corpus_id": corpus_id, "index_type": index_type}) - - chunk_ids = self.indices[corpus_id][index_type].load(nodes) - logger.info(f"Inserted {len(nodes)} nodes into {index_type} index for corpus {corpus_id}") - return chunk_ids - except Exception as e: - logger.error(f"Failed to load index for corpus {corpus_id}, index_type {index_type}: {str(e)}") - raise + """Load one index; vector snapshots replace rather than append data.""" + with self._lifecycle_lock: + with self._registry_lock: + index = self.indices.get(corpus_id, {}).get(index_type) + retriever = self.retrievers.get(corpus_id, {}).get(index_type) + if index_type == IndexType.VECTOR or index is None: + index = self._new_index(index_type) + retriever = self._new_retriever(index_type, index) + loaded = index.load(self._owned_nodes(corpus, corpus_id, index_type)) + with self._registry_lock: + self.indices.setdefault(corpus_id, {})[index_type] = index + self.retrievers.setdefault(corpus_id, {})[index_type] = retriever + return loaded async def aget(self, corpus_id: str, index_type: str, node_ids: List[str]) -> List[Union[TextChunk, ImageChunk]]: """Retrieve chunks by node_ids from the index.""" @@ -636,26 +476,32 @@ async def query_async(self, query: Union[str, Query], corpus_id: Optional[str] = query = t(query) results = [] - target_corpora = [corpus_id] if corpus_id else self.indices.keys() - - # Create all retrieval tasks + # Capture references before awaiting. A concurrent snapshot load can + # then publish a new registry while these requests finish against + # their original, internally consistent corpus-owned indices. + with self._registry_lock: + selected = [ + (cid, kind, retriever) + for cid, retrievers in self.retrievers.items() + if corpus_id is None or cid == corpus_id + for kind, retriever in retrievers.items() + ] tasks = [] - for cid in target_corpora: - for idx_type, retriever in self.retrievers[cid].items(): - if query.metadata_filters and query.metadata_filters.get("index_type") and \ - query.metadata_filters["index_type"] != idx_type: - continue - - task = retriever.aretrieve( - Query( - query_str=query.query_str, - top_k=query.top_k or self.config.retrieval.top_k, - similarity_cutoff=query.similarity_cutoff, - keyword_filters=query.keyword_filters, - metadata_filters=query.metadata_filters - ) + for cid, idx_type, retriever in selected: + if query.metadata_filters and query.metadata_filters.get("index_type") and \ + query.metadata_filters["index_type"] != idx_type: + continue + task = retriever.aretrieve( + Query( + query_str=query.query_str, + top_k=query.top_k if query.top_k is not None else self.config.retrieval.top_k, + custom_embedding_strs=query.custom_embedding_strs, + similarity_cutoff=query.similarity_cutoff, + keyword_filters=query.keyword_filters, + metadata_filters=query.metadata_filters, ) - tasks.append((task, cid, idx_type)) + ) + tasks.append((task, cid, idx_type)) # Run all retrievals concurrently retrieval_tasks = [task for task, _, _ in tasks] diff --git a/evoagentx/rag/retrievers/vector_retriever.py b/evoagentx/rag/retrievers/vector_retriever.py index e8419e3a..0ff5e387 100644 --- a/evoagentx/rag/retrievers/vector_retriever.py +++ b/evoagentx/rag/retrievers/vector_retriever.py @@ -1,84 +1,84 @@ +"""Vector retrieval with request-local parameters and consistent node lookup.""" +from contextlib import nullcontext + from llama_index.core.indices.base import BaseIndex from llama_index.core.retrievers import VectorIndexRetriever from .base import BaseRetrieverWrapper -from evoagentx.core.logging import logger from evoagentx.rag.schema import Query, RagResult, Corpus + class VectorRetriever(BaseRetrieverWrapper): - """Wrapper for vector-based retrieval.""" - + """Retrieve from one corpus without sharing mutable query parameters.""" + def __init__(self, index: BaseIndex, top_k: int = 5, chunk_class=None): super().__init__() self.index = index self.top_k = top_k - self.chunk_class = chunk_class # Use chunk class passed from RAGEngine based on config - self.retriever = VectorIndexRetriever( - index=self.index, - similarity_top_k=self.top_k + self.chunk_class = chunk_class + self._mutation_lock = getattr(index, "_evoagentx_mutation_lock", None) + # Retain the public compatibility attribute, but never mutate/reuse it + # for concurrent requests with different top_k values. + self.retriever = self._new_retriever(self.top_k) + + def _new_retriever(self, top_k): + """Construct a retriever whose settings belong to a single request.""" + if isinstance(top_k, bool) or not isinstance(top_k, int) or top_k <= 0: + raise ValueError("top_k must be a positive integer") + return VectorIndexRetriever(index=self.index, similarity_top_k=top_k) + + def _lock(self): + """Use the corpus lock when this index supports transactional writes.""" + return self._mutation_lock if self._mutation_lock is not None else nullcontext() + + def _result(self, query, nodes): + """Convert detached retrieved nodes without changing stored metadata.""" + if self.chunk_class is None: + raise ValueError("chunk_class not set - RAGEngine must pass the chunk class") + chunks = [] + scores = [] + for scored in nodes or []: + node = scored.node.model_copy(deep=True) + chunk = self.chunk_class.from_llama_node(node) + score = scored.score if scored.score is not None else 0.0 + chunk.metadata.similarity_score = score + chunks.append(chunk) + scores.append(score) + return RagResult( + corpus=Corpus(chunks=chunks), + scores=scores, + metadata={"query": query.query_str, "retriever": "vector"}, ) async def aretrieve(self, query: Query) -> RagResult: - try: - # config the top_k - self.retriever.similarity_top_k = query.top_k - nodes = await self.retriever.aretrieve(query.query_str) + """Embed asynchronously, then search and resolve nodes under one lock. - corpus = Corpus() - scores = [] - - if nodes is None: - return RagResult(corpus=corpus, scores=scores, metadata={"query": query.query_str, "retriever": "vector"}) - - for score_node in nodes: - if self.chunk_class is None: - raise ValueError("chunk_class not set - RAGEngine must pass chunk class based on config") - chunk = self.chunk_class.from_llama_node(score_node.node) - chunk.metadata.similarity_score = score_node.score or 0.0 - corpus.add_chunk(chunk) - scores.extend([score_node.score or 0.0]) - - result = RagResult( - corpus=corpus, - scores=scores, - metadata={"query": query.query_str, "retriever": "vector"} + No lock is held across an await. This allows another task to finish + ingesting while a slow embedding request is in flight; after embedding, + the query sees one complete committed state of vectors and docstore. + """ + bundle = query.to_QueryBundle() + if bundle.embedding is None and self.index.vector_store.is_embedding_query: + bundle.embedding = await self.index._embed_model.aget_agg_embedding_from_queries( + bundle.embedding_strs ) - logger.info(f"Vector retrieved {len(corpus.chunks)} chunks") - return result - except Exception as e: - logger.error(f"Vector retrieval failed: {str(e)}") - raise + with self._lock(): + retriever = self._new_retriever(query.top_k if query.top_k is not None else self.top_k) + nodes = retriever.retrieve(bundle) + return self._result(query, nodes) def retrieve(self, query: Query) -> RagResult: - try: - # config the top_k - self.retriever.similarity_top_k = query.top_k - nodes = self.retriever.retrieve(query.query_str) - corpus = Corpus() - scores = [] - - if nodes is None: - return RagResult(corpus=corpus, scores=scores, metadata={"query": query.query_str, "retriever": "vector"}) - - for score_node in nodes: - if self.chunk_class is None: - raise ValueError("chunk_class not set - RAGEngine must pass chunk class based on config") - chunk = self.chunk_class.from_llama_node(score_node.node) - chunk.metadata.similarity_score = score_node.score or 0.0 - corpus.add_chunk(chunk) - scores.extend([score_node.score or 0.0]) - - result = RagResult( - corpus=corpus, - scores=scores, - metadata={"query": query.query_str, "retriever": "vector"} + """Run a synchronous request with the same isolation guarantees.""" + bundle = query.to_QueryBundle() + if bundle.embedding is None and self.index.vector_store.is_embedding_query: + bundle.embedding = self.index._embed_model.get_agg_embedding_from_queries( + bundle.embedding_strs ) - logger.info(f"Vector retrieved {len(corpus.chunks)} chunks") - return result - except Exception as e: - logger.error(f"Vector retrieval failed: {str(e)}") - raise - + with self._lock(): + retriever = self._new_retriever(query.top_k if query.top_k is not None else self.top_k) + return self._result(query, retriever.retrieve(bundle)) + def get_retriever(self) -> VectorIndexRetriever: - logger.debug("Returning vector retriever") - return self.retriever \ No newline at end of file + """Return the compatibility retriever with the configured defaults.""" + with self._lock(): + return self._new_retriever(self.top_k) diff --git a/evoagentx/rag/snapshots.py b/evoagentx/rag/snapshots.py new file mode 100644 index 00000000..83b511d7 --- /dev/null +++ b/evoagentx/rag/snapshots.py @@ -0,0 +1,191 @@ +"""Portable corpus snapshots independent of vector-backend process state.""" +import hashlib +import json +import os +from dataclasses import dataclass +from pathlib import Path +from tempfile import NamedTemporaryFile +from typing import Any, Dict, Iterable, Optional +from uuid import uuid4 + +from .schema import Corpus, ImageChunk, IndexMetadata, TextChunk + + +@dataclass +class IndexSnapshot: + """A validated logical index payload, rather than a live backend handle.""" + + metadata: IndexMetadata + corpus: Corpus + + def to_record(self) -> Dict[str, Any]: + """Build the existing database record format without redundant indexes.""" + return { + "corpus_id": self.metadata.corpus_id, + "content": { + "corpus_id": self.metadata.corpus_id, + "chunks": [chunk.model_dump(mode="json") for chunk in self.corpus.chunks], + }, + "metadata": self.metadata.model_dump(mode="json", exclude_none=True), + "date": self.metadata.date or "", + } + + +def chunk_from_record(data: Dict[str, Any]): + """Reconstruct text or image chunks without losing formatting/relationships.""" + if not isinstance(data, dict): + raise ValueError("Snapshot chunks must be JSON objects") + if not isinstance(data.get("chunk_id"), str) or not data["chunk_id"]: + raise ValueError("Snapshot chunks must contain a nonempty chunk_id") + common = { + key: data[key] + for key in ( + "chunk_id", "metadata", "embedding", "excluded_embed_metadata_keys", + "excluded_llm_metadata_keys", "text_template", "relationships", + ) + if key in data + } + if "image_path" in data: + return ImageChunk( + image_path=data["image_path"], + image_mimetype=data.get("image_mimetype"), + **common, + ) + if "text" not in data: + raise ValueError("Snapshot chunks must contain text or image_path") + return TextChunk( + text=data["text"], + start_char_idx=data.get("start_char_idx"), + end_char_idx=data.get("end_char_idx"), + **common, + ) + + +def snapshot_from_record(record: Dict[str, Any]) -> IndexSnapshot: + """Read a legacy or current single-index database record.""" + metadata = IndexMetadata.model_validate(record["metadata"]) + if metadata.corpus_id != record["corpus_id"]: + raise ValueError("Snapshot corpus_id disagrees with its metadata") + content = record["content"] + if not isinstance(content, dict) or not isinstance(content.get("chunks"), list): + raise ValueError("Snapshot content must contain a chunks list") + if content.get("corpus_id", metadata.corpus_id) != metadata.corpus_id: + raise ValueError("Snapshot content belongs to a different corpus") + chunks = [chunk_from_record(data) for data in content["chunks"]] + identifiers = [chunk.chunk_id for chunk in chunks] + if len(set(identifiers)) != len(identifiers): + raise ValueError("Snapshot contains duplicate chunk IDs") + return IndexSnapshot( + metadata=metadata, + corpus=Corpus(chunks=chunks, corpus_id=metadata.corpus_id, metadata=metadata), + ) + + +def _atomic_write(path: Path, payload: bytes) -> None: + """Publish one complete file and remove temporary files after failures.""" + temporary = None + try: + with NamedTemporaryFile(dir=path.parent, prefix=".rag-", delete=False) as stream: + temporary = Path(stream.name) + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + +def save_file_snapshot(snapshot: IndexSnapshot, directory: str) -> None: + """Publish a collision-free metadata pointer to immutable JSONL content. + + Write content first and metadata last. If metadata publication fails, a + previous snapshot still points to its intact content. Unreferenced content + is removed on failure; older committed generations remain valid for readers + that already opened the previous metadata file. + """ + destination = Path(directory) + destination.mkdir(parents=True, exist_ok=True) + identity = json.dumps( + [snapshot.metadata.corpus_id, snapshot.metadata.index_type], ensure_ascii=False + ).encode("utf-8") + stem = hashlib.sha256(identity).hexdigest() + metadata_file = destination / f"{stem}_metadata.json" + nodes_file = destination / f"{stem}_{uuid4().hex}_nodes.jsonl" + nodes = "".join( + json.dumps(chunk.model_dump(mode="json"), ensure_ascii=False) + "\n" + for chunk in snapshot.corpus.chunks + ).encode("utf-8") + metadata = snapshot.metadata.model_dump(mode="json", exclude_none=True) + metadata.update( + snapshot_version=2, + nodes_file=nodes_file.name, + nodes_sha256=hashlib.sha256(nodes).hexdigest(), + ) + _atomic_write(nodes_file, nodes) + try: + _atomic_write( + metadata_file, + json.dumps(metadata, indent=2, ensure_ascii=False).encode("utf-8"), + ) + except BaseException: + nodes_file.unlink(missing_ok=True) + raise + + +def load_file_snapshots( + directory: str, + corpus_id: Optional[str] = None, + index_type: Optional[str] = None, +) -> Iterable[IndexSnapshot]: + """Read both legacy filename pairs and versioned metadata pointers. + + Logical identity always comes from metadata, including for legacy files + whose names contain sanitized corpus IDs. A pointer cannot escape the + selected directory. Selected corrupt/incomplete snapshots fail explicitly. + """ + source = Path(directory) + if not source.is_dir(): + raise FileNotFoundError(f"Source directory {directory} does not exist") + selected = {} + for metadata_file in sorted(source.glob("*_metadata.json")): + metadata = json.loads(metadata_file.read_text(encoding="utf-8")) + if (corpus_id is not None and metadata.get("corpus_id") != corpus_id) or ( + index_type is not None and metadata.get("index_type") != index_type + ): + continue + version = metadata.get("snapshot_version", 1) + if version not in (1, 2): + raise ValueError(f"Unsupported snapshot version: {version}") + identity = (metadata.get("corpus_id"), metadata.get("index_type")) + previous = selected.get(identity) + if previous is not None: + old_version = previous[1].get("snapshot_version", 1) + if old_version == version: + raise ValueError(f"Multiple snapshots found for {identity}") + # Saving into a legacy directory publishes a canonical versioned + # pointer. Retain old files for readers already using them, but + # prefer the new pointer when both formats describe the same index. + if old_version > version: + continue + selected[identity] = (metadata_file, metadata) + for metadata_file, metadata in selected.values(): + version = metadata.get("snapshot_version", 1) + nodes_name = metadata.get("nodes_file") + if nodes_name is None and version == 1: + nodes_name = metadata_file.name[:-len("_metadata.json")] + "_nodes.jsonl" + if not isinstance(nodes_name, str) or Path(nodes_name).name != nodes_name: + raise ValueError("Snapshot nodes_file must be a filename in the source directory") + nodes_file = source / nodes_name + if nodes_file.resolve().parent != source.resolve(): + raise ValueError("Snapshot nodes_file must remain in the source directory") + nodes = nodes_file.read_bytes() + checksum = metadata.get("nodes_sha256") + if version == 2 and (not checksum or hashlib.sha256(nodes).hexdigest() != checksum): + raise ValueError("Snapshot nodes checksum does not match metadata") + chunks = [json.loads(line) for line in nodes.decode("utf-8").splitlines() if line.strip()] + yield snapshot_from_record({ + "corpus_id": metadata["corpus_id"], + "metadata": metadata, + "content": {"chunks": chunks}, + }) diff --git a/evoagentx/storages/base.py b/evoagentx/storages/base.py index aedf4949..6f78f553 100644 --- a/evoagentx/storages/base.py +++ b/evoagentx/storages/base.py @@ -1,15 +1,17 @@ import os import json +from copy import deepcopy +from threading import RLock from typing import List, Dict, Any, Optional, Union -from pydantic import Field +from pydantic import Field, PrivateAttr from ..core.module import BaseModule from .storages_config import StoreConfig from .db_stores import DBStoreBase, DBStoreFactory from .graph_stores import GraphStoreFactory, GraphStoreBase from .vectore_stores import VectorStoreFactory, VectorStoreBase -from .schema import TableType, AgentStore, WorkflowStore, MemoryStore, HistoryStore, IndexStore +from .schema import TableType, AgentStore, WorkflowStore, MemoryStore, HistoryStore, IndexStore, expand_index_record class StorageHandler(BaseModule): @@ -24,6 +26,8 @@ class StorageHandler(BaseModule): vector_store: Optional[Union[VectorStoreBase, Any]] = Field(None, description="Single vector storage backend") graph_store: Optional[Union[GraphStoreBase, Any]] = Field(None, description="Optional graph storage backend") + _index_lock: Any = PrivateAttr(default_factory=RLock) + def init_module(self): """ Initialize all storage backends based on the provided configuration. @@ -326,19 +330,62 @@ def save_history(self, history_data: Dict[str, Any], table: Optional[str] = None else: self.storageDB.insert(metadata=history_data, store_type="history", table=table) - def load_index(self, corpus_id: str, table: Optional[str] = None) -> Optional[Dict[str, Any]]: - result = self.storageDB.get_by_id(corpus_id, store_type="indexing", table=table) - if result is not None: + def load_index( + self, corpus_id: str, table: Optional[str] = None, + index_type: Optional[str] = None, + ) -> Optional[Dict[str, Any]]: + """Load a corpus row, optionally selecting one index from its snapshots. + + Existing single-index rows remain readable without migration. An + unfiltered call returns the stored row, including an aggregate when + several index types share the corpus primary key. + """ + table = table or TableType.store_indexing.value + with self._index_lock: + result = self.storageDB.get_by_id(corpus_id, store_type="indexing", table=table) + if result is None: + return None result = self.parse_result(result, IndexStore) - - return result + if index_type is None: + return result + return next( + (record for record in expand_index_record(result) + if record.get("metadata", {}).get("index_type") == index_type), + None, + ) def save_index(self, index_data: Dict[str, Any], table: Optional[str] = None): - corpus_id = index_data.get("corpus_id") + """Upsert one index without overwriting other types in the same corpus. + + A single index retains the legacy row format. When a second type is + saved, both payloads are stored in a versioned content envelope using + the existing corpus_id primary key and columns. Updating one type + preserves the other snapshots, including those not loaded by an engine. + """ + table = table or TableType.store_indexing.value + data = IndexStore.model_validate(deepcopy(index_data)).model_dump() + corpus_id = data["corpus_id"] if not corpus_id: - raise ValueError("Index data must include an 'corpus_id' field") - existing = self.storageDB.get_by_id(corpus_id, store_type="indexing", table=table) - if existing: - self.storageDB.update(corpus_id, new_metadata=index_data, store_type="indexing", table=table) - else: - self.storageDB.insert(metadata=index_data, store_type="indexing", table=table) \ No newline at end of file + raise ValueError("Index data must include a nonempty corpus_id") + index_type = data["metadata"].get("index_type") + with self._index_lock: + existing = self.load_index(corpus_id, table=table) + if existing is not None and index_type is not None: + records = { + record["metadata"].get("index_type"): record + for record in expand_index_record(existing) + } + records[index_type] = data + if len(records) > 1: + data = { + "corpus_id": corpus_id, + "content": {"indices": records}, + "metadata": {"snapshot_format": 2}, + "date": data["date"], + } + elif existing is not None and existing.get("metadata", {}).get("snapshot_format") == 2: + raise ValueError("index_type is required to update an aggregate snapshot") + if existing is None: + self.storageDB.insert(metadata=data, store_type="indexing", table=table) + else: + self.storageDB.update(corpus_id, new_metadata=data, store_type="indexing", table=table) diff --git a/evoagentx/storages/schema.py b/evoagentx/storages/schema.py index d4c25e1c..0bdd4025 100644 --- a/evoagentx/storages/schema.py +++ b/evoagentx/storages/schema.py @@ -66,3 +66,23 @@ class IndexStore(BaseModel): content: Dict[str, Any] = Field(..., description="Serialized index content (e.g., LlamaIndex JSON)") date: Optional[str] = Field(default="", description="Creation or last update date") metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional metadata, e.g., vector store collection name") + + +def expand_index_record(record: Dict[str, Any]) -> List[Dict[str, Any]]: + """Expand an aggregate DB row, retaining support for old single-index rows.""" + if record.get("metadata", {}).get("snapshot_format") != 2: + return [record] + indices = record.get("content", {}).get("indices") + if not isinstance(indices, dict): + raise ValueError("Aggregate snapshot must contain an indices object") + records = [] + for index_type, payload in indices.items(): + if not isinstance(payload, dict): + raise ValueError("Aggregate index payload must be an object") + single = dict(payload, corpus_id=record["corpus_id"]) + if single.get("metadata", {}).get("index_type") != index_type: + raise ValueError("Aggregate index key disagrees with its metadata") + if single["metadata"].get("corpus_id", record["corpus_id"]) != record["corpus_id"]: + raise ValueError("Aggregate index belongs to a different corpus") + records.append(single) + return records diff --git a/evoagentx/storages/vectore_stores/faiss.py b/evoagentx/storages/vectore_stores/faiss.py index 1f0e9a67..751fa292 100644 --- a/evoagentx/storages/vectore_stores/faiss.py +++ b/evoagentx/storages/vectore_stores/faiss.py @@ -1,59 +1,242 @@ -from typing import Union, Literal +"""FAISS storage with stable node IDs and reversible vector mutations.""" +from contextlib import contextmanager +from threading import RLock +from typing import Any, Iterator, List, Optional, Union, Literal import faiss +import numpy as np +from pydantic import PrivateAttr from llama_index.core.schema import BaseNode -from llama_index.vector_stores.faiss import FaissMapVectorStore +from llama_index.core.vector_stores.types import MetadataFilters +from llama_index.vector_stores.faiss import FaissMapVectorStore, FaissVectorStore from .base import VectorStoreBase -from evoagentx.core.logging import logger + + +class TransactionalFaissMapVectorStore(FaissMapVectorStore): + """Keep FAISS IDs unique after deletions and undo unsuccessful batches. + + The upstream adapter allocates IDs from ``ntotal``. That value decreases + when a node is deleted, so an insertion can reuse a surviving vector's ID. + This adapter allocates monotonically and keeps an undo journal containing + only the vectors affected by a mutation. It does not clone the index. + + Transactions also cover a caller's subsequent docstore/index mutations. + They serialize access to native FAISS using the same lock as retrieval. + """ + + _next_id: int = PrivateAttr(default=0) + _journal: Optional[List[Any]] = PrivateAttr(default=None) + _mutation_lock: Any = PrivateAttr(default_factory=RLock) + + def __init__(self, faiss_index): + """Use native IVF IDs directly, and an IDMap for flat indexes. + + IVF already supports explicit IDs. Wrapping it in an IndexIDMap makes + deletion compact a second ID table independently of IVF's stored IDs. + A native hash direct map also permits reconstructing touched vectors + for the rollback journal without copying the whole vector corpus. + """ + if isinstance(faiss_index, faiss.IndexIVFFlat): + faiss_index.set_direct_map_type(faiss.DirectMap.Hashtable) + FaissVectorStore.__init__(self, faiss_index=faiss_index) + self._node_id_to_faiss_id_map = {} + self._faiss_id_to_node_id_map = {} + else: + super().__init__(faiss_index=faiss_index) + + @property + def mutation_lock(self): + """Return the lock protecting vectors and their associated node catalog.""" + return self._mutation_lock + + @contextmanager + def transaction(self) -> Iterator[None]: + """Commit vector changes together, or undo them in reverse order. + + Nested calls participate in the outer transaction. A rollback failure + is raised explicitly: callers must not treat that backend as healthy. + The counter deliberately does not rewind after rollback, so failed + attempts cannot cause a later numeric-ID collision. + """ + with self._mutation_lock: + if self._journal is not None: + yield + return + self._journal = [] + try: + yield + except BaseException as original: + rollback_errors = [] + for undo in reversed(self._journal): + try: + undo() + except Exception as error: + rollback_errors.append(error) + if rollback_errors: + raise RuntimeError( + "FAISS rollback failed; recreate the index from its saved corpus" + ) from original + raise + finally: + self._journal = None + + def _prepare_batch(self, nodes): + """Validate the entire batch before touching native state.""" + unique = {} + for node in nodes: + if not isinstance(node, BaseNode): + raise TypeError("FAISS nodes must be LlamaIndex BaseNode instances") + if not isinstance(node.node_id, str) or not node.node_id: + raise ValueError("FAISS node IDs must be nonempty strings") + unique[node.node_id] = node + if not unique: + return [], np.empty((0, self.client.d), dtype=np.float32) + try: + vectors = np.asarray( + [node.get_embedding() for node in unique.values()], dtype=np.float32 + ) + except (TypeError, ValueError) as error: + raise ValueError("FAISS embeddings must be equally sized numeric vectors") from error + if vectors.shape != (len(unique), self.client.d): + raise ValueError(f"FAISS embeddings must have dimension {self.client.d}") + if not np.isfinite(vectors).all(): + raise ValueError("FAISS embeddings must contain only finite numbers") + return list(unique), np.ascontiguousarray(vectors) + + def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]: + """Atomically insert a batch, replacing duplicate logical node IDs.""" + node_ids, vectors = self._prepare_batch(nodes) + if not node_ids: + return [] + with self.transaction(): + self.delete_nodes(node_ids) + # Also handle maps loaded by the upstream persistence constructor. + if self._next_id == 0 and self._faiss_id_to_node_id_map: + self._next_id = max(self._faiss_id_to_node_id_map) + 1 + numeric_ids = np.arange( + self._next_id, self._next_id + len(node_ids), dtype=np.int64 + ) + self._next_id += len(node_ids) + + def undo_add(): + # Record before add_with_ids: even a partially applied native + # insertion is removable because these IDs were never live. + self.client.remove_ids(numeric_ids) + for node_id, numeric_id in zip(node_ids, numeric_ids): + if self._node_id_to_faiss_id_map.get(node_id) == int(numeric_id): + self._node_id_to_faiss_id_map.pop(node_id, None) + self._faiss_id_to_node_id_map.pop(int(numeric_id), None) + + self._journal.append(undo_add) + self.client.add_with_ids(vectors, numeric_ids) + for node_id, numeric_id in zip(node_ids, numeric_ids): + self._node_id_to_faiss_id_map[node_id] = int(numeric_id) + self._faiss_id_to_node_id_map[int(numeric_id)] = node_id + return node_ids + + def delete_nodes( + self, + node_ids: Optional[List[str]] = None, + filters: Optional[MetadataFilters] = None, + **delete_kwargs: Any, + ) -> None: + """Delete logical IDs while journaling their native vectors for undo.""" + if filters is not None: + raise NotImplementedError("FAISS metadata filters are not supported") + if node_ids is None: + raise ValueError("node_ids must be provided to delete nodes") + with self.transaction(): + existing = { + node_id: self._node_id_to_faiss_id_map[node_id] + for node_id in dict.fromkeys(node_ids) + if node_id in self._node_id_to_faiss_id_map + } + if not existing: + return + numeric_ids = np.asarray(list(existing.values()), dtype=np.int64) + vectors = np.asarray( + [self.client.reconstruct(int(identifier)) for identifier in numeric_ids], + dtype=np.float32, + ) + + def undo_delete(): + # Remove first so rollback is safe if native deletion failed + # after removing only some of the requested IDs. + self.client.remove_ids(numeric_ids) + self.client.add_with_ids(vectors, numeric_ids) + self._node_id_to_faiss_id_map.update(existing) + self._faiss_id_to_node_id_map.update( + {identifier: node_id for node_id, identifier in existing.items()} + ) + + self._journal.append(undo_delete) + self.client.remove_ids(numeric_ids) + for node_id, numeric_id in existing.items(): + self._node_id_to_faiss_id_map.pop(node_id) + self._faiss_id_to_node_id_map.pop(numeric_id) + + def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None: + """Delete a node using the adapter's node-ID contract.""" + self.delete_nodes([ref_doc_id], **delete_kwargs) + + def query(self, query, **kwargs): + """Serialize native search with mutations.""" + with self._mutation_lock: + return super().query(query, **kwargs) class FaissVectorStoreWrapper(VectorStoreBase): - """Wrapper for FAISS vector store.""" - - def __init__(self, dimensions: int = 1536, - metrics: Union[Literal["flat_l2", "ivf_flat"]] = "flat_l2", **kwargs): + """Create independent FAISS stores from a reusable backend configuration.""" + + def __init__( + self, + dimensions: int = 1536, + metrics: Union[Literal["flat_l2", "ivf_flat"]] = "flat_l2", + **kwargs, + ): + if isinstance(dimensions, bool) or not isinstance(dimensions, int) or dimensions <= 0: + raise ValueError("FAISS dimensions must be a positive integer") self.dimensions = dimensions self.metrics = metrics self.faiss_index = self._create_index() - self.vector_store = FaissMapVectorStore(faiss_index=faiss.IndexIDMap2(self.faiss_index)) + native = self.faiss_index if isinstance(self.faiss_index, faiss.IndexIVFFlat) else faiss.IndexIDMap2(self.faiss_index) + self.vector_store = TransactionalFaissMapVectorStore(faiss_index=native) def _create_index(self) -> faiss.Index: + """Build the configured native index.""" if self.metrics == "flat_l2": return faiss.IndexFlatL2(self.dimensions) - elif self.metrics == "ivf_flat": + if self.metrics == "ivf_flat": quantizer = faiss.IndexFlatL2(self.dimensions) return faiss.IndexIVFFlat(quantizer, self.dimensions, 100) - else: - raise ValueError(f"Unsupported FAISS index type: {self.metrics}") - - def get_vector_store(self) -> FaissMapVectorStore: - return self.vector_store - - async def aload(self, node: BaseNode) -> None: - """ - Asynchronously load a single node into the FAISS vector store. - - Checks if a node with the same ID already exists in the FAISS vector store. If it does not exist, - inserts the node with its embedding. Handles both Chunk and BaseNode types. - - Args: - node (Union[Chunk, BaseNode]): The node to load, either a Chunk or a LlamaIndex BaseNode. - """ - try: - if not isinstance(node, BaseNode): - raise ValueError(f"Unsupported node type: {type(node)}. Must be Chunk or BaseNode.") + raise ValueError(f"Unsupported FAISS index type: {self.metrics}") - node_id = node.id if hasattr(node, "id") else node.id_ - existing_ids = self.vector_store._node_id_to_faiss_id_map - if node_id in existing_ids: - logger.info(f"Node with ID {node_id} already exists in FAISS vector store, skipping insertion.") - return - - self.vector_store.add([node]) + def create_empty(self) -> "FaissVectorStoreWrapper": + """Create a corpus-owned store without copying any existing vectors.""" + empty = type(self)(dimensions=self.dimensions, metrics=self.metrics) + if isinstance(self.faiss_index, faiss.IndexIVFFlat) and self.faiss_index.is_trained: + # Retain the trained centroids and query settings, without cloning + # the template's vector data. Only the small quantizer is copied. + source = self.faiss_index + native = faiss.IndexIVFFlat( + faiss.clone_index(source.quantizer), self.dimensions, + source.nlist, source.metric_type, + ) + native.is_trained = True + native.nprobe = source.nprobe + empty.faiss_index = native + empty.vector_store = TransactionalFaissMapVectorStore(faiss_index=native) + return empty - logger.info(f"Inserted node with ID {node_id} into FAISS vector store.") + def get_vector_store(self) -> TransactionalFaissMapVectorStore: + """Return the LlamaIndex-compatible backend.""" + return self.vector_store - except Exception as e: - logger.error(f"Failed to load node with ID {node_id} into FAISS vector store: {str(e)}") - raise \ No newline at end of file + async def aload(self, node: BaseNode) -> None: + """Load a node once without replacing an existing logical ID.""" + if not isinstance(node, BaseNode): + raise ValueError("node must be a LlamaIndex BaseNode") + with self.vector_store.mutation_lock: + if node.node_id not in self.vector_store._node_id_to_faiss_id_map: + self.vector_store.add([node]) diff --git a/tests/src/rag/test_corpus_lifecycle.py b/tests/src/rag/test_corpus_lifecycle.py new file mode 100644 index 00000000..df68f2a2 --- /dev/null +++ b/tests/src/rag/test_corpus_lifecycle.py @@ -0,0 +1,550 @@ +"""Offline integration regressions for the vector corpus lifecycle.""" +import asyncio +from unittest.mock import patch + +import pytest +from llama_index.core.embeddings import BaseEmbedding +from llama_index.core.schema import TextNode + +from evoagentx.rag.rag import RAGEngine +from evoagentx.rag.rag_config import RAGConfig, EmbeddingConfig, RetrievalConfig +from evoagentx.rag.schema import Corpus, Query, TextChunk +from evoagentx.storages.base import StorageHandler +from evoagentx.storages.storages_config import DBConfig, StoreConfig, VectorStoreConfig +from evoagentx.storages.vectore_stores.faiss import FaissVectorStoreWrapper + + +class LocalEmbedding(BaseEmbedding): + """Deterministic embedding with an explicit failure trigger.""" + def _get_query_embedding(self, query): + return [0.0, 0.0] + + async def _aget_query_embedding(self, query): + await asyncio.sleep(0) + return self._get_query_embedding(query) + + def _get_text_embedding(self, text): + if "FAIL_EMBED" in text: + raise RuntimeError("embedding unavailable") + return [5.0, 0.0] + + +class LocalEmbeddingWrapper: + dimensions = 2 + + def __init__(self): + self.model = LocalEmbedding(model_name="text-embedding-ada-002") + + def get_embedding_model(self): + return self.model + + def validate_model(self, provider, model_name): + return model_name == "text-embedding-ada-002" + + +@pytest.fixture +def engine(tmp_path): + handler = StorageHandler(storageConfig=StoreConfig( + path=str(tmp_path), + dbConfig=DBConfig(path=str(tmp_path / "corpora.sqlite")), + vectorConfig=VectorStoreConfig(dimensions=2), + )) + config = RAGConfig( + embedding=EmbeddingConfig(api_key="offline", dimensions=2), + retrieval=RetrievalConfig(top_k=3, similarity_cutoff=None), + ) + with patch("evoagentx.rag.rag.EmbeddingFactory.create", return_value=LocalEmbeddingWrapper()): + rag = RAGEngine(config=config, storage_handler=handler) + yield rag + handler.storageDB.connection.close() + + +def node(identifier, text, distance=1.0, **metadata): + return TextNode(id_=identifier, text=text, embedding=[distance, 0.0], metadata=metadata) + + +def contents(engine, corpus, top_k=10): + result = engine.query(Query(query_str="lookup", top_k=top_k), corpus_id=corpus) + return [chunk.text for chunk in result.corpus.chunks] + + +def test_top_k_is_applied_within_corpus(engine): + engine.add("vector", [node("far", "target", 10)], corpus_id="target") + engine.add("vector", [node("near", "unrelated", 0)], corpus_id="other") + assert contents(engine, "target", 1) == ["target"] + + +def test_same_chunk_id_in_different_corpora_has_independent_lifecycle(engine): + engine.add("vector", [node("shared", "alpha", 1)], corpus_id="a") + engine.add("vector", [node("shared", "beta", 2)], corpus_id="b") + engine.delete("a", "vector", node_ids="shared") + assert contents(engine, "b") == ["beta"] + assert contents(engine, "a") == [] + + +def test_failed_embedding_preserves_previous_node(engine): + engine.add("vector", [node("shared", "original")], corpus_id="a") + replacement = TextNode(id_="shared", text="FAIL_EMBED") + assert engine.add("vector", [replacement], corpus_id="a") == [] + assert contents(engine, "a") == ["original"] + chunks = asyncio.run(engine.aget("a", "vector", ["shared"])) + assert [chunk.text for chunk in chunks] == ["original"] + + +def test_delete_then_add_does_not_reuse_live_faiss_id(engine): + engine.add("vector", [node("a", "first", 1), node("b", "second", 2)], corpus_id="a") + engine.delete("a", "vector", node_ids="a") + engine.add("vector", [node("c", "third", 3)], corpus_id="a") + assert contents(engine, "a") == ["second", "third"] + + +def test_duplicate_ids_in_one_batch_have_one_last_value(engine): + ids = engine.add("vector", [node("a", "old", 0), node("a", "new", 2)], corpus_id="a") + assert ids == ["a"] + assert contents(engine, "a") == ["new"] + + +def test_add_preserves_caller_nodes_and_uses_corpus_identity(engine): + original = node("a", "text", 1, corpus_id="original") + engine.add("vector", [original], corpus_id="new") + assert original.metadata["corpus_id"] == "original" + corpus = Corpus(chunks=[TextChunk(chunk_id="b", text="corpus text")], corpus_id="chosen") + assert engine.add("vector", corpus) == ["b"] + assert contents(engine, "chosen") == ["corpus text"] + + +@pytest.mark.parametrize("database", [False, True]) +def test_repeated_load_replaces_snapshot_without_duplicate_vectors(engine, tmp_path, database): + engine.add("vector", [node("same", "alpha", 1)], corpus_id="a") + engine.add("vector", [node("same", "beta", 2)], corpus_id="b") + destination = None if database else str(tmp_path / "snapshots") + engine.save(output_path=destination) + engine.add("vector", [node("stale", "not in snapshot", 3)], corpus_id="a") + for _ in range(2): + assert sorted(engine.load(source=destination)) == ["same", "same"] + assert contents(engine, "a") == ["alpha"] + assert contents(engine, "b") == ["beta"] + + +def test_snapshot_identity_does_not_come_from_sanitized_filename(engine, tmp_path): + for corpus, text in [("a/b", "slash"), ("a_b", "underscore")]: + engine.add("vector", [node("id", text)], corpus_id=corpus) + engine.save(output_path=str(tmp_path / "snapshots")) + engine.clear() + engine.load(source=str(tmp_path / "snapshots")) + assert contents(engine, "a/b") == ["slash"] + assert contents(engine, "a_b") == ["underscore"] + + +def test_clear_one_corpus_leaves_other_corpus_retrievable(engine): + engine.add("vector", [node("same", "alpha")], corpus_id="a") + engine.add("vector", [node("same", "beta")], corpus_id="b") + engine.clear("a") + assert contents(engine, "b") == ["beta"] + + +def test_vector_backend_failed_batch_has_no_partial_native_vectors(): + store = FaissVectorStoreWrapper(dimensions=2).get_vector_store() + store.add([node("old", "old")]) + with pytest.raises(ValueError): + store.add([node("new", "new"), TextNode(id_="bad", text="bad", embedding=[0.0])]) + from llama_index.core.vector_stores.types import VectorStoreQuery + result = store.query(VectorStoreQuery(query_embedding=[0.0, 0.0], similarity_top_k=10)) + assert result.ids == ["old"] + + +def test_failed_new_corpus_is_not_registered(engine): + assert engine.add("vector", [TextNode(id_="bad", text="FAIL_EMBED")], corpus_id="failed") == [] + assert "failed" not in engine.indices + assert "failed" not in engine.retrievers + + +def test_backend_failure_rolls_back_vectors_docstore_and_cache(engine): + engine.add("vector", [node("a", "original", 1), node("b", "untouched", 2)], corpus_id="a") + index = engine.indices["a"]["vector"] + original_insert = index.index.insert_nodes + + def fail_after_insert(nodes): + original_insert(nodes) + raise RuntimeError("write failed after native insertion") + + with patch.object(index.index, "insert_nodes", side_effect=fail_after_insert): + assert engine.add("vector", [node("a", "replacement", 0), node("c", "new", 3)], corpus_id="a") == [] + assert contents(engine, "a") == ["original", "untouched"] + assert [chunk.text for chunk in asyncio.run(index.get(["a", "b", "c"]))] == ["original", "untouched"] + engine.add("vector", [node("c", "after rollback", 3)], corpus_id="a") + assert contents(engine, "a") == ["original", "untouched", "after rollback"] + + +def test_invalid_file_snapshot_does_not_change_live_corpus(engine, tmp_path): + import json + engine.add("vector", [node("a", "saved")], corpus_id="a") + directory = tmp_path / "snapshot" + engine.save(output_path=str(directory)) + engine.add("vector", [node("b", "live")], corpus_id="a") + metadata_path = next(directory.glob("*_metadata.json")) + metadata = json.loads(metadata_path.read_text()) + metadata["dimension"] = 3 + metadata_path.write_text(json.dumps(metadata)) + with pytest.raises(ValueError, match="dimension"): + engine.load(source=str(directory)) + assert contents(engine, "a") == ["saved", "live"] + + +def test_wrong_saved_model_is_rejected_before_mutation(engine, tmp_path): + import json + engine.add("vector", [node("a", "live")], corpus_id="a") + directory = tmp_path / "snapshot" + engine.save(output_path=str(directory)) + metadata_path = next(directory.glob("*_metadata.json")) + metadata = json.loads(metadata_path.read_text()) + metadata["embedding_model_name"] = "other-model" + metadata_path.write_text(json.dumps(metadata)) + with pytest.raises(ValueError, match="model"): + engine.load(source=str(directory)) + assert contents(engine, "a") == ["live"] + + +def test_unknown_save_index_selector_does_not_save_other_types(engine, tmp_path): + engine.add("vector", [node("a", "live")], corpus_id="a") + directory = tmp_path / "snapshot" + engine.save(output_path=str(directory), index_type="graph") + assert not directory.exists() or not list(directory.iterdir()) + + +def test_database_preserves_multiple_index_snapshots(engine): + # Exercise real storage with graph payloads, without starting external Neo4j. + handler = engine.storage_handler + handler.save_index({"corpus_id": "a", "content": {"chunks": [{"text": "vector"}]}, + "metadata": {"index_type": "vector"}}) + handler.save_index({"corpus_id": "a", "content": {"chunks": [{"text": "graph"}]}, + "metadata": {"index_type": "graph"}}) + vector = handler.load_index("a", index_type="vector") + graph = handler.load_index("a", index_type="graph") + assert vector["content"]["chunks"] == [{"text": "vector"}] + assert graph["content"]["chunks"] == [{"text": "graph"}] + + +def test_reranking_duplicate_ids_keeps_both_corpus_contents(engine): + engine.config.retrieval.similarity_cutoff = 0.1 + engine.add("vector", [node("shared", "alpha", 1)], corpus_id="a") + engine.add("vector", [node("shared", "beta", 2)], corpus_id="b") + assert contents(engine, None) == ["alpha", "beta"] + + +def test_concurrent_top_k_requests_are_independent(engine): + engine.add("vector", [node(str(i), str(i), i) for i in range(5)], corpus_id="a") + retriever = engine.retrievers["a"]["vector"] + + async def run(): + return await asyncio.gather(*[ + retriever.aretrieve(Query(query_str="lookup", top_k=k)) for k in [1, 4, 2, 5] + ]) + + results = asyncio.run(run()) + assert [len(result.corpus.chunks) for result in results] == [1, 4, 2, 5] + + +def test_query_started_before_failed_write_sees_restored_catalog(engine): + engine.add("vector", [node("a", "original")], corpus_id="a") + index = engine.indices["a"]["vector"] + original_insert = index.index.insert_nodes + model = engine.embed_model.model + + def fail_after_insert(nodes): + original_insert(nodes) + raise RuntimeError("write failed") + + async def run(): + started, resume = asyncio.Event(), asyncio.Event() + + async def delayed_embedding(query): + started.set() + await resume.wait() + return [0.0, 0.0] + + with patch.object(model, "_aget_query_embedding", side_effect=delayed_embedding): + task = asyncio.create_task(engine.query_async(Query(query_str="lookup", top_k=1), "a")) + await started.wait() + with patch.object(index.index, "insert_nodes", side_effect=fail_after_insert): + assert engine.add("vector", [node("a", "uncommitted")], corpus_id="a") == [] + resume.set() + return await task + + result = asyncio.run(run()) + assert [chunk.text for chunk in result.corpus.chunks] == ["original"] + + +def test_native_add_failure_after_mutation_is_undone(engine): + engine.add("vector", [node("a", "original")], corpus_id="a") + backend = engine.indices["a"]["vector"].vector_store.get_vector_store() + native = backend.client + original = native.add_with_ids + attempted = False + + def fail_once(vectors, ids): + nonlocal attempted + result = original(vectors, ids) + if not attempted: + attempted = True + raise RuntimeError("native add failed after mutation") + return result + + with patch.object(native, "add_with_ids", side_effect=fail_once): + assert engine.add("vector", [node("a", "replacement"), node("b", "new")], corpus_id="a") == [] + assert contents(engine, "a") == ["original"] + + +def test_native_delete_failure_after_mutation_is_undone(engine): + engine.add("vector", [node("a", "original"), node("b", "untouched", 2)], corpus_id="a") + native = engine.indices["a"]["vector"].vector_store.get_vector_store().client + original = native.remove_ids + attempted = False + + def fail_once(ids): + nonlocal attempted + result = original(ids) + if not attempted: + attempted = True + raise RuntimeError("native deletion failed after mutation") + return result + + with patch.object(native, "remove_ids", side_effect=fail_once): + with pytest.raises(RuntimeError, match="native deletion"): + engine.delete("a", "vector", node_ids="a") + assert contents(engine, "a") == ["original", "untouched"] + + +@pytest.mark.parametrize("database", [False, True]) +def test_image_snapshot_preserves_path_embedding_and_relationships(engine, tmp_path, database): + from evoagentx.rag.schema import ImageChunk + from llama_index.core.schema import NodeRelationship, RelatedNodeInfo + engine.config.modality = "multimodal" + engine.chunk_class = ImageChunk + image = ImageChunk( + chunk_id="image", image_path=str(tmp_path / "image.png"), + image_mimetype="image/png", embedding=[1.0, 0.0], + relationships={NodeRelationship.SOURCE: RelatedNodeInfo(node_id="source")}, + text_template="{content}", + ) + assert engine.add("vector", [image], corpus_id="images") == ["image"] + destination = None if database else str(tmp_path / "images") + engine.save(output_path=destination) + engine.clear() + assert engine.load(source=destination) == ["image"] + loaded = asyncio.run(engine.aget("images", "vector", ["image"]))[0] + assert isinstance(loaded, ImageChunk) + assert loaded.image_path == str(tmp_path / "image.png") + assert loaded.embedding == [1.0, 0.0] + assert loaded.relationships[NodeRelationship.SOURCE].node_id == "source" + assert loaded.text_template == "{content}" + + +def test_legacy_file_snapshot_uses_metadata_identity(engine, tmp_path): + import json + directory = tmp_path / "legacy" + directory.mkdir() + chunk = TextChunk(chunk_id="old", text="legacy", embedding=[1.0, 0.0], text_template="{content}") + (directory / "sanitized_vector_nodes.jsonl").write_text(chunk.to_json(indent=None) + "\n") + (directory / "sanitized_vector_metadata.json").write_text(json.dumps({ + "corpus_id": "original/identity", "index_type": "vector", "dimension": 2, + "embedding_model_name": "text-embedding-ada-002", "vector_db_type": "faiss", + })) + assert engine.load(source=str(directory), corpus_id="original/identity") == ["old"] + assert contents(engine, "original/identity") == ["legacy"] + loaded = asyncio.run(engine.aget("original/identity", "vector", ["old"]))[0] + assert loaded.text_template == "{content}" + + +def test_failed_docstore_update_restores_reference_document_membership(engine): + from llama_index.core.schema import NodeRelationship, RelatedNodeInfo + first, second = node("a", "first"), node("b", "second", 2) + for value in (first, second): + value.relationships = {NodeRelationship.SOURCE: RelatedNodeInfo(node_id="source")} + engine.add("vector", [first, second], corpus_id="a") + index = engine.indices["a"]["vector"] + original = index.index.insert_nodes + + def fail_after_insert(nodes): + original(nodes) + raise RuntimeError("catalog failed") + + with patch.object(index.index, "insert_nodes", side_effect=fail_after_insert): + assert engine.add("vector", [node("a", "replacement")], corpus_id="a") == [] + assert contents(engine, "a") == ["first", "second"] + assert sorted(index.index.docstore.get_ref_doc_info("source").node_ids) == ["a", "b"] + + +def test_trained_ivf_template_isolated_corpora_keep_training_and_stable_ids(engine): + import numpy as np + template = FaissVectorStoreWrapper(dimensions=2, metrics="ivf_flat") + template.get_vector_store().client.train( + np.random.default_rng(123).normal(size=(4000, 2)).astype("float32") + ) + engine.storage_handler.vector_store = template + assert engine.add("vector", [node("a", "first", 1), node("b", "second", 2)], corpus_id="a") == ["a", "b"] + assert engine.add("vector", [node("a", "other", 0)], corpus_id="b") == ["a"] + for corpus in ["a", "b"]: + backend = engine.indices[corpus]["vector"].vector_store.get_vector_store() + import faiss + faiss.extract_index_ivf(backend.client).nprobe = 100 + engine.delete("a", "vector", node_ids="a") + engine.add("vector", [node("c", "third", 3)], corpus_id="a") + assert contents(engine, "a") == ["second", "third"] + assert contents(engine, "b") == ["other"] + + +@pytest.mark.parametrize("selection", [{"node_ids": []}, {"metadata_filters": {}}, {"index_type": ""}]) +def test_empty_delete_selection_does_not_clear_the_corpus(engine, selection): + engine.add("vector", [node("a", "keep")], corpus_id="a") + engine.delete("a", **selection) + assert contents(engine, "a") == ["keep"] + + +def test_empty_corpus_selector_does_not_clear_every_corpus(engine): + engine.add("vector", [node("a", "keep")], corpus_id="a") + engine.clear("") + assert contents(engine, "a") == ["keep"] + + +def test_saving_loaded_legacy_directory_can_be_loaded_again(engine, tmp_path): + import json + directory = tmp_path / "legacy" + directory.mkdir() + chunk = TextChunk(chunk_id="a", text="legacy", embedding=[1.0, 0.0]) + (directory / "a_vector_nodes.jsonl").write_text(chunk.to_json(indent=None) + "\n") + (directory / "a_vector_metadata.json").write_text(json.dumps({ + "corpus_id": "a", "index_type": "vector", "dimension": 2, + "embedding_model_name": "text-embedding-ada-002", "vector_db_type": "faiss", + })) + engine.load(source=str(directory)) + engine.add("vector", [node("b", "new", 2)], corpus_id="a") + engine.save(output_path=str(directory)) + engine.clear() + assert engine.load(source=str(directory)) == ["a", "b"] + assert contents(engine, "a") == ["legacy", "new"] + + +def test_failed_file_publication_keeps_previous_snapshot(engine, tmp_path): + from evoagentx.rag import snapshots + directory = tmp_path / "snapshot" + engine.add("vector", [node("a", "saved")], corpus_id="a") + engine.save(output_path=str(directory)) + engine.add("vector", [node("b", "unpublished", 2)], corpus_id="a") + original_write = snapshots._atomic_write + + def fail_metadata(path, payload): + if path.name.endswith("_metadata.json"): + raise OSError("metadata publication failed") + original_write(path, payload) + + with patch.object(snapshots, "_atomic_write", side_effect=fail_metadata): + with pytest.raises(OSError, match="publication failed"): + engine.save(output_path=str(directory)) + assert engine.load(source=str(directory)) == ["a"] + assert contents(engine, "a") == ["saved"] + + +def test_unrelated_async_query_and_heartbeat_finish_before_ingestion_is_released(engine): + from threading import Event, Thread, Timer + engine.add("vector", [node("old", "query me")], corpus_id="existing") + started, release = Event(), Event() + original_embedding = engine.embed_model.model._get_text_embedding + inserted = [] + + def delayed_embedding(text): + started.set() + if not release.wait(5): + raise RuntimeError("embedding watchdog expired") + return original_embedding(text) + + def ingest(): + inserted.extend(engine.add("vector", [TextNode(id_="new", text="slow embedding")], corpus_id="other")) + + async def proof(): + async def heartbeat(): + await asyncio.sleep(0.01) + return not release.is_set() + + heartbeat_task = asyncio.create_task(heartbeat()) + await asyncio.sleep(0) + result = await engine.query_async("lookup", corpus_id="existing") + query_finished_before_release = not release.is_set() + heartbeat_finished_before_release = await heartbeat_task + return result, query_finished_before_release, heartbeat_finished_before_release + + with patch.object(engine.embed_model.model, "_get_text_embedding", side_effect=delayed_embedding): + worker = Thread(target=ingest) + worker.start() + watchdog = Timer(3, release.set) + watchdog.start() + try: + assert started.wait(2) + result, query_progressed, heartbeat_progressed = asyncio.run(proof()) + finally: + release.set() + watchdog.cancel() + worker.join(5) + watchdog.join(5) + assert not worker.is_alive() + assert [chunk.text for chunk in result.corpus.chunks] == ["query me"] + assert query_progressed, "Query could finish only after the blocked embedding was released" + assert heartbeat_progressed, "The query blocked an independent event-loop heartbeat" + assert inserted == ["new"] + + +@pytest.mark.parametrize("operation", ["add", "delete", "clear", "load"]) +def test_lifecycle_writers_serialize_with_an_inflight_add(engine, operation): + from threading import Event, Thread + engine.add("vector", [node("old", "saved", 1)], corpus_id="a") + engine.save() + started, release, following_started = Event(), Event(), Event() + original_embedding = engine.embed_model.model._get_text_embedding + errors = [] + + def delayed_embedding(text): + started.set() + if not release.wait(5): + raise RuntimeError("embedding watchdog expired") + return original_embedding(text) + + def ingest(): + try: + engine.add("vector", [TextNode(id_="pending", text="slow embedding")], corpus_id="a") + except BaseException as error: + errors.append(error) + + def following(): + following_started.set() + try: + if operation == "add": + engine.add("vector", [node("second", "second", 2)], corpus_id="a") + elif operation == "delete": + engine.delete("a", "vector", node_ids="pending") + elif operation == "clear": + engine.clear() + else: + engine.load() + except BaseException as error: + errors.append(error) + + with patch.object(engine.embed_model.model, "_get_text_embedding", side_effect=delayed_embedding): + first, second = Thread(target=ingest), Thread(target=following) + first.start() + try: + assert started.wait(2) + second.start() + assert following_started.wait(2) + finally: + release.set() + first.join(5) + if second.ident is not None: + second.join(5) + assert not first.is_alive() and not second.is_alive() + assert errors == [] + if operation == "add": + assert contents(engine, "a") == ["saved", "second", "slow embedding"] + elif operation in ("delete", "load"): + assert contents(engine, "a") == ["saved"] + else: + assert engine.indices == {} and engine.retrievers == {}