From a77defc1d55473da8c4893ba278fbcde3caea37c Mon Sep 17 00:00:00 2001 From: sofiachavezb Date: Tue, 24 Nov 2026 15:16:42 -0300 Subject: [PATCH 1/8] feat(rag): declare the query-time parameters of each retriever Add NON_PERSISTENT_PARAMS to the retriever classes and a persistence signature that drops them, recursively, from a configuration. Query-time knobs such as top_k, the similarity metric, the retrieve-then-expand options or a composite's merge strategy no longer take part in the identity of a fitted retriever. --- .../models/RAG/retrievers/base_retriever.py | 7 + .../composite/agentic_reranker_retriever.py | 10 + .../retrievers/composite/agentic_retriever.py | 10 + .../composite/mmr_reranker_retriever.py | 14 +- .../composite/parallel_retriever.py | 11 +- .../cross_encoder/cross_encoder_retriever.py | 5 + .../sentence_transformer_cross_encoder.py | 11 +- .../dense/dense_embedding_retriever.py | 13 +- .../RAG/retrievers/persistence_signature.py | 242 ++++++++++++++++++ .../back/models/RAG/retrievers/ref_utils.py | 17 +- .../RAG/retrievers/retrieval_expansion.py | 3 + .../RAG/retrievers/sparse/bm25_retriever.py | 13 +- .../RAG/retrievers/sparse/sparse_retriever.py | 5 +- .../RAG/retrievers/sparse/tfidf_retriever.py | 13 +- 14 files changed, 363 insertions(+), 11 deletions(-) create mode 100644 DashAI/back/models/RAG/retrievers/persistence_signature.py diff --git a/DashAI/back/models/RAG/retrievers/base_retriever.py b/DashAI/back/models/RAG/retrievers/base_retriever.py index 38b3228ec..82797dd34 100644 --- a/DashAI/back/models/RAG/retrievers/base_retriever.py +++ b/DashAI/back/models/RAG/retrievers/base_retriever.py @@ -109,6 +109,13 @@ class BaseRetriever(ConfigObject, ABC): #: template and never renders it. REPRESENTATION: ClassVar[MultilingualString | None] = None + #: Parameters that act only at query time and never change what is stored + #: for this retriever. They are left out of its persistence signature (see + #: :mod:`DashAI.back.models.RAG.retrievers.persistence_signature`), so + #: changing them reuses the fitted state instead of re-indexing. Subclasses + #: extend the tuple with their own query-time parameters. + NON_PERSISTENT_PARAMS: ClassVar[Tuple[str, ...]] = (ENABLE_FIELD, WINDOW_FIELD) + env_RAG_path: str | os.PathLike | None # noqa: N815 chunks: Dict[int, Dict[int, Chunk]] documents: Dict[int, SourceDocument] diff --git a/DashAI/back/models/RAG/retrievers/composite/agentic_reranker_retriever.py b/DashAI/back/models/RAG/retrievers/composite/agentic_reranker_retriever.py index f0ea18d30..6cfb6eda5 100644 --- a/DashAI/back/models/RAG/retrievers/composite/agentic_reranker_retriever.py +++ b/DashAI/back/models/RAG/retrievers/composite/agentic_reranker_retriever.py @@ -316,6 +316,16 @@ class AgenticRerankerRetriever(CompositeRetriever): "required": [SELECTED_CHUNKS_KEY], } + #: The candidate size, the selection size, prompt, language model and retry + #: budget act at query time; the child is the only persisted state. + NON_PERSISTENT_PARAMS = CompositeRetriever.NON_PERSISTENT_PARAMS + ( + _PARAM_K1, + _PARAM_TOP_K, + _PARAM_PROMPT, + _PARAM_LLM_MODEL, + _PARAM_FUNCTION_CALL_MAX_TRIALS, + ) + @classmethod def _get_main_parameters(cls) -> Dict[str, str]: """Return the candidate and final budget paths.""" diff --git a/DashAI/back/models/RAG/retrievers/composite/agentic_retriever.py b/DashAI/back/models/RAG/retrievers/composite/agentic_retriever.py index 0e0e5c84c..b25274f80 100644 --- a/DashAI/back/models/RAG/retrievers/composite/agentic_retriever.py +++ b/DashAI/back/models/RAG/retrievers/composite/agentic_retriever.py @@ -328,6 +328,16 @@ def __init__(self, **kwargs: Any) -> None: zh="最大迭代 {max_iters} · 最大片段 {max_chunks} · {prompt}", ) + #: The agentic loop, its pool cap, prompt, language model and retry budget + #: act at query time; the children are the only persisted state. + NON_PERSISTENT_PARAMS = CompositeRetriever.NON_PERSISTENT_PARAMS + ( + _PARAM_MAX_ITERS, + _PARAM_MAX_CHUNKS, + _PARAM_PROMPT, + _PARAM_LLM_MODEL, + _PARAM_FUNCTION_CALL_MAX_TRIALS, + ) + @classmethod def _get_main_parameters(cls) -> Dict[str, str]: """Return the round and pool budget paths.""" diff --git a/DashAI/back/models/RAG/retrievers/composite/mmr_reranker_retriever.py b/DashAI/back/models/RAG/retrievers/composite/mmr_reranker_retriever.py index 27633bedf..6d820a979 100644 --- a/DashAI/back/models/RAG/retrievers/composite/mmr_reranker_retriever.py +++ b/DashAI/back/models/RAG/retrievers/composite/mmr_reranker_retriever.py @@ -1,5 +1,5 @@ import logging -from typing import Any, Dict, List, Tuple +from typing import Any, Dict, Final, List, Tuple import numpy as np from sklearn.metrics.pairwise import cosine_similarity @@ -21,6 +21,7 @@ unpack_retrieval_result, ) from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( + TOP_K_FIELD, RetrievalExpansionSchema, ) from DashAI.back.models.RAG.retrievers.trace_utils import retriever_trace @@ -28,6 +29,10 @@ log = logging.getLogger(__name__) +#: Schema param name of the trade-off between relevance and diversity. +MMR_LAMBDA_FIELD: Final[str] = "mmr_lambda" + + class MMRRerankerRetrieverSchema(RetrievalExpansionSchema): """Schema for :class:`MMRRerankerRetriever`. @@ -116,6 +121,13 @@ class MMRRerankerRetriever(CompositeRetriever): zh="MMR λ {mmr_lambda} · top-k {top_k}", ) + #: The final selection size and the MMR trade-off act on the candidates the + #: child returns at query time; only the child is persisted. + NON_PERSISTENT_PARAMS = CompositeRetriever.NON_PERSISTENT_PARAMS + ( + MMR_LAMBDA_FIELD, + TOP_K_FIELD, + ) + @classmethod def _get_main_parameters(cls) -> Dict[str, str]: """Return the MMR trade-off and final top-k paths.""" diff --git a/DashAI/back/models/RAG/retrievers/composite/parallel_retriever.py b/DashAI/back/models/RAG/retrievers/composite/parallel_retriever.py index 19fce953d..6cce3a4e9 100644 --- a/DashAI/back/models/RAG/retrievers/composite/parallel_retriever.py +++ b/DashAI/back/models/RAG/retrievers/composite/parallel_retriever.py @@ -1,4 +1,4 @@ -from typing import Any, Dict, List, Tuple +from typing import Any, Dict, Final, List, Tuple from DashAI.back.core.schema_fields import ( component_field, @@ -21,6 +21,9 @@ ) from DashAI.back.models.RAG.retrievers.trace_utils import retriever_trace +#: Schema param name of the strategy used to merge the children's results. +MERGE_STRATEGY_FIELD: Final[str] = "merge_strategy" + class ParallelRetrieverSchema(RetrievalExpansionSchema): """Schema for :class:`ParallelRetriever`. @@ -93,6 +96,12 @@ class ParallelRetriever(CompositeRetriever): zh="合并 {merge_strategy}", ) + #: Merging combines the children's results at query time; only the children + #: are persisted. + NON_PERSISTENT_PARAMS = CompositeRetriever.NON_PERSISTENT_PARAMS + ( + MERGE_STRATEGY_FIELD, + ) + @classmethod def _get_main_parameters(cls) -> Dict[str, str]: """Return the merge-strategy path.""" diff --git a/DashAI/back/models/RAG/retrievers/cross_encoder/cross_encoder_retriever.py b/DashAI/back/models/RAG/retrievers/cross_encoder/cross_encoder_retriever.py index 0cb21558e..af753cf06 100644 --- a/DashAI/back/models/RAG/retrievers/cross_encoder/cross_encoder_retriever.py +++ b/DashAI/back/models/RAG/retrievers/cross_encoder/cross_encoder_retriever.py @@ -15,6 +15,7 @@ from DashAI.back.models.RAG.retrievers.retrieval_contracts import ( unpack_retrieval_result, ) +from DashAI.back.models.RAG.retrievers.retrieval_expansion import TOP_K_FIELD from DashAI.back.models.RAG.retrievers.trace_utils import chunk_ref, retriever_trace @@ -46,6 +47,10 @@ class CrossEncoderRetriever(CompositeRetriever, ABC): "candidates retrieved by a child retriever." ) + #: Re-ranking selects the final ``top_k`` at query time; the cross-encoder + #: model has no persisted state, so only the child is persisted. + NON_PERSISTENT_PARAMS = CompositeRetriever.NON_PERSISTENT_PARAMS + (TOP_K_FIELD,) + @classmethod def _get_main_parameters(cls) -> Dict[str, str]: """Return the final top-k path.""" diff --git a/DashAI/back/models/RAG/retrievers/cross_encoder/sentence_transformer_cross_encoder.py b/DashAI/back/models/RAG/retrievers/cross_encoder/sentence_transformer_cross_encoder.py index 83f68720b..8d8081646 100644 --- a/DashAI/back/models/RAG/retrievers/cross_encoder/sentence_transformer_cross_encoder.py +++ b/DashAI/back/models/RAG/retrievers/cross_encoder/sentence_transformer_cross_encoder.py @@ -1,5 +1,5 @@ import logging -from typing import TYPE_CHECKING, Any, Dict, List +from typing import TYPE_CHECKING, Any, Dict, Final, List import numpy as np @@ -156,6 +156,10 @@ # ── Schema ──────────────────────────────────────────────────────────────────── +#: Schema param name of the cross-encoder model used for re-ranking. +MODEL_NAME_FIELD: Final[str] = "model_name" + + class SentenceTransformerCrossEncoderRetrieverSchema(RetrievalExpansionSchema): """Schema for :class:`SentenceTransformerCrossEncoderRetriever`. @@ -276,6 +280,11 @@ class SentenceTransformerCrossEncoderRetriever(CrossEncoderRetriever): zh="模型 {model_name} · top-k {top_k}", ) + #: The cross-encoder only scores chunks at query time and persists nothing. + NON_PERSISTENT_PARAMS = CrossEncoderRetriever.NON_PERSISTENT_PARAMS + ( + MODEL_NAME_FIELD, + ) + @classmethod def _get_main_parameters(cls) -> Dict[str, str]: """Return the cross-encoder model name and final top-k paths.""" diff --git a/DashAI/back/models/RAG/retrievers/dense/dense_embedding_retriever.py b/DashAI/back/models/RAG/retrievers/dense/dense_embedding_retriever.py index 031ec5f6c..0cf179e23 100644 --- a/DashAI/back/models/RAG/retrievers/dense/dense_embedding_retriever.py +++ b/DashAI/back/models/RAG/retrievers/dense/dense_embedding_retriever.py @@ -1,5 +1,5 @@ import os -from typing import Any, Dict, List, Tuple +from typing import Any, Dict, Final, List, Tuple import numpy as np @@ -16,6 +16,7 @@ from DashAI.back.core.utils import MultilingualString from DashAI.back.models.RAG.documents import Chunk from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( + TOP_K_FIELD, RetrievalExpansionSchema, ) from DashAI.back.models.RAG.retrievers.similarity import ( @@ -26,6 +27,9 @@ from DashAI.back.models.RAG.retrievers.trace_utils import retriever_trace from DashAI.back.models.RAG.retrievers.unit_retriever import UnitRetriever +#: Schema param name of the distance metric compared against stored embeddings. +SIMILARITY_METRIC_FIELD: Final[str] = "similarity_metric" + class DenseEmbeddingRetrieverSchema(RetrievalExpansionSchema): """Schema for :class:`DenseEmbeddingRetriever`. @@ -88,6 +92,13 @@ class DenseEmbeddingRetriever(UnitRetriever): SCHEMA = DenseEmbeddingRetrieverSchema + #: The distance metric and ``top_k`` are applied to the stored embeddings at + #: query time; only the embedding model shapes what is persisted. + NON_PERSISTENT_PARAMS = UnitRetriever.NON_PERSISTENT_PARAMS + ( + SIMILARITY_METRIC_FIELD, + TOP_K_FIELD, + ) + DISPLAY_NAME: str = MultilingualString( en="Dense Embedding Retriever", es="Recuperador por Embeddings Densos", diff --git a/DashAI/back/models/RAG/retrievers/persistence_signature.py b/DashAI/back/models/RAG/retrievers/persistence_signature.py new file mode 100644 index 000000000..f08cd288a --- /dev/null +++ b/DashAI/back/models/RAG/retrievers/persistence_signature.py @@ -0,0 +1,242 @@ +"""Persistence signature of a retriever configuration. + +A retriever's configuration mixes two kinds of parameters. Some shape what is +stored on disk and in the database (the embedding model, the vectorizer, the +BM25 weights); others only act at query time (``top_k``, the distance metric, +the retrieve-then-expand options, a composite's merge strategy). Only the first +kind may take part in the identity under which a fitted retriever is looked up, +stored and cleaned up, or tuning a query-time knob would force a re-index. + +Each retriever class declares its query-time parameters in +``NON_PERSISTENT_PARAMS``. The signature of a configuration is the +configuration without those parameters, resolved recursively: a parameter +holding a ``{component, params}`` reference is replaced by the signature of +that component, using the nested component class's own declaration, and a +``children`` list is resolved the same way. A class without a declaration +(converters, similarity functions, language models) keeps all of its +parameters, because nothing is known to be query-time only. + +Mappings are returned with their keys sorted at every level, while lists keep +their order. The signature is compared as JSON text by the database natural-key +lookups, so two configurations that differ only in key order must serialise +identically. +""" + +from typing import Any, Dict, Final, List, Tuple + +from DashAI.back.dependencies.registry.component_registry import ComponentRegistry +from DashAI.back.models.RAG.exceptions import RAGComponentNotFoundError +from DashAI.back.models.RAG.retrievers.ref_utils import ( + COMPONENT_KEY, + PARAMS_KEY, + is_component_ref, +) + +#: Name of the class attribute listing a class's query-time parameters. +NON_PERSISTENT_ATTRIBUTE: Final[str] = "NON_PERSISTENT_PARAMS" + + +def _non_persistent_params(model_class: type) -> Tuple[str, ...]: + """Return the query-time parameter names declared by *model_class*. + + A class without a ``NON_PERSISTENT_PARAMS`` declaration contributes no + exclusions, so all of its parameters count toward the identity. + + Parameters + ---------- + model_class : type + Component class to inspect. + + Returns + ------- + Tuple[str, ...] + The declared names, or an empty tuple when the class declares none. + """ + if hasattr(model_class, NON_PERSISTENT_ATTRIBUTE): + return tuple(getattr(model_class, NON_PERSISTENT_ATTRIBUTE)) + return () + + +def _resolve_class(component: str, registry: ComponentRegistry) -> type: + """Return the class registered under *component*. + + Parameters + ---------- + component : str + Registered name of the component, as stored in a reference. + registry : ComponentRegistry + Registry the name is looked up in. + + Returns + ------- + type + The component class registered under *component*. + + Raises + ------ + RAGComponentNotFoundError + If *component* is not registered. + """ + if component not in registry: + raise RAGComponentNotFoundError( + f"Component '{component}' not found in registry" + ) + return registry[component]["class"] + + +def _mapping_signature( + mapping: Dict[str, Any], ignored: Tuple[str, ...], registry: ComponentRegistry +) -> Dict[str, Any]: + """Return *mapping* without the *ignored* keys, sorted, with values resolved. + + Parameters + ---------- + mapping : Dict[str, Any] + Parameters to reduce. + ignored : Tuple[str, ...] + Keys to drop at this level only. + registry : ComponentRegistry + Registry used to resolve nested components. + + Returns + ------- + Dict[str, Any] + A new mapping whose keys are sorted and whose values are signatures. + """ + signature: Dict[str, Any] = {} + for key in sorted(mapping): + if key in ignored: + continue + signature[key] = _value_signature(mapping[key], registry) + return signature + + +def _reference_signature_value( + reference: Dict[str, Any], registry: ComponentRegistry +) -> Dict[str, Any]: + """Return the signature of a ``{component, params}`` reference. + + Raises + ------ + ValueError + If the reference's ``params`` is not a dict. The message names the + component. + RAGComponentNotFoundError + If the component is not registered. + """ + component = reference[COMPONENT_KEY] + params = reference[PARAMS_KEY] + if not isinstance(params, dict): + raise ValueError( + f"The parameters of component '{component}' must be a dict, " + f"got {type(params).__name__}." + ) + nested_class = _resolve_class(component, registry) + signature: Dict[str, Any] = {} + for key in sorted(reference): + if key == PARAMS_KEY: + signature[key] = persistence_signature(nested_class, params, registry) + else: + signature[key] = _value_signature(reference[key], registry) + return signature + + +def _value_signature(value: Any, registry: ComponentRegistry) -> Any: + """Return the signature of a parameter value. + + References are resolved through the registry, plain mappings are searched + for references and canonically ordered, lists keep their order, and every + other value is returned unchanged. + + Parameters + ---------- + value : Any + A parameter value, possibly a reference, mapping, list or scalar. + registry : ComponentRegistry + Registry used to resolve nested components. + + Returns + ------- + Any + The signature of *value*, in the same shape it was given. + + Raises + ------ + ValueError + If a nested reference's ``params`` is not a dict. + RAGComponentNotFoundError + If a nested component is not registered. + """ + if is_component_ref(value): + return _reference_signature_value(value, registry) + if isinstance(value, dict): + return _mapping_signature(value, (), registry) + if isinstance(value, list): + items: List[Any] = [] + for item in value: + items.append(_value_signature(item, registry)) + return items + return value + + +def reference_signature( + reference: Dict[str, Any], registry: ComponentRegistry +) -> Dict[str, Any]: + """Return the persistence signature of a ``{component, params}`` reference. + + Parameters + ---------- + reference : Dict[str, Any] + Component reference, as stored in a session's parameters. + registry : ComponentRegistry + Registry used to resolve the component and its nested components. + + Returns + ------- + Dict[str, Any] + The reference with ``params`` replaced by its persistence signature. + + Raises + ------ + ValueError + If *reference* is not a ``{component, params}`` reference, or its + ``params`` is not a dict. + RAGComponentNotFoundError + If a component is not registered. + """ + if not is_component_ref(reference): + raise ValueError( + f"Expected a {{component, params}} reference, got {reference!r}." + ) + return _reference_signature_value(reference, registry) + + +def persistence_signature( + model_class: type, params: Dict[str, Any], registry: ComponentRegistry +) -> Dict[str, Any]: + """Return the parameters of a configuration that shape what is persisted. + + Parameters + ---------- + model_class : type + Class the configuration belongs to. Its ``NON_PERSISTENT_PARAMS`` are + dropped from *params*. + params : Dict[str, Any] + Configuration parameters, possibly holding nested component references. + registry : ComponentRegistry + Registry used to resolve the classes of nested components. + + Returns + ------- + Dict[str, Any] + A new mapping without the query-time parameters, at every level, with + keys sorted at every level. The input is never mutated. + + Raises + ------ + ValueError + If a nested reference's ``params`` is not a dict. + RAGComponentNotFoundError + If a nested component is not registered. + """ + return _mapping_signature(params, _non_persistent_params(model_class), registry) diff --git a/DashAI/back/models/RAG/retrievers/ref_utils.py b/DashAI/back/models/RAG/retrievers/ref_utils.py index 4ecb0092d..72f4376f2 100644 --- a/DashAI/back/models/RAG/retrievers/ref_utils.py +++ b/DashAI/back/models/RAG/retrievers/ref_utils.py @@ -2,7 +2,16 @@ from __future__ import annotations -from typing import Any +from typing import Any, Final + +#: Key naming the registered component of a ``{component, params}`` reference. +COMPONENT_KEY: Final[str] = "component" + +#: Key holding the parameters of a ``{component, params}`` reference. +PARAMS_KEY: Final[str] = "params" + +#: Parameter holding the child retrievers of a composite retriever. +CHILDREN_KEY: Final[str] = "children" def is_component_ref(value: Any) -> bool: @@ -21,7 +30,7 @@ def is_component_ref(value: Any) -> bool: """ return ( isinstance(value, dict) - and "component" in value - and "params" in value - and isinstance(value.get("component"), str) + and COMPONENT_KEY in value + and PARAMS_KEY in value + and isinstance(value.get(COMPONENT_KEY), str) ) diff --git a/DashAI/back/models/RAG/retrievers/retrieval_expansion.py b/DashAI/back/models/RAG/retrievers/retrieval_expansion.py index 5902570e5..67e7bcaec 100644 --- a/DashAI/back/models/RAG/retrievers/retrieval_expansion.py +++ b/DashAI/back/models/RAG/retrievers/retrieval_expansion.py @@ -30,6 +30,9 @@ #: Schema param name of the expansion window size. WINDOW_FIELD: Final[str] = "expand_window" +#: Schema param name of the number of chunks a retriever returns. +TOP_K_FIELD: Final[str] = "top_k" + #: Whether retrievers expand their final output by default. DEFAULT_ENABLE_RETRIEVE_THEN_EXPAND: Final[bool] = False diff --git a/DashAI/back/models/RAG/retrievers/sparse/bm25_retriever.py b/DashAI/back/models/RAG/retrievers/sparse/bm25_retriever.py index 4d6b62ce5..879272d46 100644 --- a/DashAI/back/models/RAG/retrievers/sparse/bm25_retriever.py +++ b/DashAI/back/models/RAG/retrievers/sparse/bm25_retriever.py @@ -16,6 +16,7 @@ from DashAI.back.core.utils import MultilingualString from DashAI.back.models.RAG.documents import Chunk from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( + TOP_K_FIELD, RetrievalExpansionSchema, ) from DashAI.back.models.RAG.retrievers.similarity import ( @@ -23,7 +24,10 @@ CosineSimilarity, require_similarity_metric, ) -from DashAI.back.models.RAG.retrievers.sparse.sparse_retriever import SparseRetriever +from DashAI.back.models.RAG.retrievers.sparse.sparse_retriever import ( + SIMILARITY_FUNCTION_FIELD, + SparseRetriever, +) from DashAI.back.models.RAG.retrievers.trace_utils import retriever_trace log = logging.getLogger(__name__) @@ -152,6 +156,13 @@ class BM25Retriever(SparseRetriever): SCHEMA = BM25RetrieverSchema + #: The distance metric and ``top_k`` are applied at query time; the + #: vectorizer and the BM25 weights shape the fitted matrix. + NON_PERSISTENT_PARAMS = SparseRetriever.NON_PERSISTENT_PARAMS + ( + SIMILARITY_FUNCTION_FIELD, + TOP_K_FIELD, + ) + @classmethod def _get_main_parameters(cls) -> Dict[str, str]: """Return the BM25 weighting, similarity function and top-k paths.""" diff --git a/DashAI/back/models/RAG/retrievers/sparse/sparse_retriever.py b/DashAI/back/models/RAG/retrievers/sparse/sparse_retriever.py index 5a3ac3aaf..e9a7cf45e 100644 --- a/DashAI/back/models/RAG/retrievers/sparse/sparse_retriever.py +++ b/DashAI/back/models/RAG/retrievers/sparse/sparse_retriever.py @@ -1,9 +1,12 @@ -from typing import Dict, List +from typing import Dict, Final, List from DashAI.back.core.utils import MultilingualString from DashAI.back.models.RAG.documents import Chunk from DashAI.back.models.RAG.retrievers.unit_retriever import UnitRetriever +#: Schema param name of the distance function applied to the fitted matrix. +SIMILARITY_FUNCTION_FIELD: Final[str] = "similarity_function" + class SparseRetriever(UnitRetriever): """Abstract base for sparse (keyword-based) retrievers. diff --git a/DashAI/back/models/RAG/retrievers/sparse/tfidf_retriever.py b/DashAI/back/models/RAG/retrievers/sparse/tfidf_retriever.py index d1d7e1367..6c1fafe2c 100644 --- a/DashAI/back/models/RAG/retrievers/sparse/tfidf_retriever.py +++ b/DashAI/back/models/RAG/retrievers/sparse/tfidf_retriever.py @@ -14,6 +14,7 @@ from DashAI.back.core.utils import MultilingualString from DashAI.back.models.RAG.documents import Chunk from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( + TOP_K_FIELD, RetrievalExpansionSchema, ) from DashAI.back.models.RAG.retrievers.similarity import ( @@ -21,7 +22,10 @@ CosineSimilarity, require_similarity_metric, ) -from DashAI.back.models.RAG.retrievers.sparse.sparse_retriever import SparseRetriever +from DashAI.back.models.RAG.retrievers.sparse.sparse_retriever import ( + SIMILARITY_FUNCTION_FIELD, + SparseRetriever, +) from DashAI.back.models.RAG.retrievers.trace_utils import retriever_trace log = logging.getLogger(__name__) @@ -80,6 +84,13 @@ class TFIDFRetriever(SparseRetriever): the injected chunks and retrieves via pairwise distance. """ + #: The distance metric and ``top_k`` are applied at query time; only the + #: vectorizer shapes the fitted matrix. + NON_PERSISTENT_PARAMS = SparseRetriever.NON_PERSISTENT_PARAMS + ( + SIMILARITY_FUNCTION_FIELD, + TOP_K_FIELD, + ) + DISPLAY_NAME: str = MultilingualString( en="TF-IDF Retriever", es="Recuperador TF-IDF", From 9ff99b3a02bb5071a3378fc7f26d6746274eeb08 Mon Sep 17 00:00:00 2001 From: sofiachavezb Date: Tue, 24 Nov 2026 15:16:46 -0300 Subject: [PATCH 2/8] fix(rag): key retriever storage, cleanup and status on the persistence signature Setup, cleanup and index status now compare retrievers by their persistence signature instead of ad-hoc stripping of top_k and the similarity function. Tuning a query-time parameter, at any nesting level, keeps the fitted state instead of deleting or re-indexing it. CleanupService receives the component registry to resolve nested component classes. --- DashAI/back/services/RAG/cleanup_service.py | 202 +++++-- .../back/services/RAG/index_status_service.py | 109 +++- .../services/RAG/retriever_setup_service.py | 20 +- .../workflows/RAG_workflow_session_service.py | 2 +- tests/back/RAG/test_retriever_identity.py | 546 +++++++++++++++++- .../test_workflow_session_services.py | 7 +- 6 files changed, 797 insertions(+), 89 deletions(-) diff --git a/DashAI/back/services/RAG/cleanup_service.py b/DashAI/back/services/RAG/cleanup_service.py index ab5c48ef2..04a8d5d81 100644 --- a/DashAI/back/services/RAG/cleanup_service.py +++ b/DashAI/back/services/RAG/cleanup_service.py @@ -4,6 +4,7 @@ from sqlalchemy.orm import Session +from DashAI.back.core.schema_fields.utils import normalize_payload from DashAI.back.dependencies.database.models import ( RAGChunkingModel, RAGChunkSet, @@ -16,46 +17,58 @@ RAGRetrieverChild, RAGSparseRetriever, ) +from DashAI.back.dependencies.registry.component_registry import ComponentRegistry +from DashAI.back.models.RAG.exceptions import RAGComponentNotFoundError from DashAI.back.models.RAG.RAG_constants import ( COMPOSITE_RETRIEVER_NAMES, RAG_PARAM_RETRIEVER_MODEL, ) -from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( - strip_expansion_options, +from DashAI.back.models.RAG.retrievers.persistence_signature import ( + reference_signature, ) +from DashAI.back.models.RAG.retrievers.ref_utils import is_component_ref from DashAI.back.services.RAG.deferred_fs import remove_after_commit from DashAI.back.services.RAG.retriever_db_service import RetrieverDBService log = logging.getLogger(__name__) -def _retriever_identity(reference: Any) -> Any: - """Return a retriever reference without its expansion options. +def _retriever_identity(reference: Any, registry: ComponentRegistry | None) -> Any: + """Return a retriever reference reduced to its persistence signature. - The retrieve-then-expand options are post-processing knobs: they change - nothing about what is indexed, so a session that only toggled them must not - have its fitted retriever deleted. Stripping is recursive, so a composite's - children are compared without their options too. + Query-time parameters (``top_k``, the distance metric, the + retrieve-then-expand options) change nothing about what is indexed, so a + session that only changed them must not have its fitted retriever deleted. + The reduction is recursive, so a composite's children and nested components + are compared by their own signatures too. Parameters ---------- reference : Any A ``{"component", "params"}`` retriever reference, or any other value. + registry : ComponentRegistry | None + Registry used to resolve the retriever classes. Returns ------- Any - The reference with ``params`` stripped of the two options, or the value - unchanged when it is not a retriever reference. + The reference with ``params`` reduced to its persistence signature, or + the value unchanged when it is not a retriever reference. + + Raises + ------ + ValueError + If *reference* is a retriever reference and no registry was given. """ - if not isinstance(reference, dict): - return reference - params = reference.get("params") - if not isinstance(params, dict): - return reference - identity = dict(reference) - identity["params"] = strip_expansion_options(params) - return identity + canonical = normalize_payload(reference) + if not is_component_ref(canonical): + return canonical + if registry is None: + raise ValueError( + "CleanupService needs a component registry to compare retriever " + "configurations." + ) + return reference_signature(canonical, registry) class CleanupService: @@ -65,10 +78,19 @@ class CleanupService: embedding matrices, and storage folders when a generative session is deleted or its parameters are updated. Order of operations is critical: retrievers must be cleaned up BEFORE chunking models. + + Parameters + ---------- + db : Session + SQLAlchemy session. + registry : ComponentRegistry | None + Registry used to compare retriever configurations when a session's + parameters are updated. Not needed for deletion-only use. """ - def __init__(self, db: Session): + def __init__(self, db: Session, registry: ComponentRegistry | None = None): self.db = db + self._registry = registry self._retriever_db = RetrieverDBService(db) def cleanup_orphaned_resources( @@ -99,13 +121,31 @@ def cleanup_orphaned_resources( return def _component_changed(key: str) -> bool: + """Whether one parameter of the session really changed. + + Parameters + ---------- + key : str + Session parameter name, such as ``retriever_model``. + + Returns + ------- + bool + ``True`` on full session deletion, when the raw value differs + for a non-retriever parameter, or when a retriever's identity + differs. Identical raw values are never a change. + """ if new_parameters is None: return True old_value = old_parameters.get(key) new_value = new_parameters.get(key) + # Identical raw values cannot differ in identity, so the registry + # is only needed when the configuration really changed. + if old_value == new_value: + return False if key != RAG_PARAM_RETRIEVER_MODEL: - return old_value != new_value - return _retriever_identity(old_value) != _retriever_identity(new_value) + return True + return self._retriever_changed(old_value, new_value) documents_ids = sorted(old_parameters.get("documents") or []) @@ -156,6 +196,39 @@ def _component_changed(key: str) -> bool: # ── Private helpers ── + def _retriever_changed(self, old_value: Any, new_value: Any) -> bool: + """Whether a retriever reference changed in a way that affects its fit. + + An old reference whose component is no longer registered, typically + because its plugin was uninstalled, cannot be reduced to a signature and + so cannot be shown to match the new one. It is taken as changed, which + lets the session move off it; the orphaned fitted state is then released. + + Parameters + ---------- + old_value : Any + The retriever reference before the update. + new_value : Any + The retriever reference after the update. + + Returns + ------- + bool + ``True`` when the identities differ, or when the old reference's + component cannot be resolved. + + Raises + ------ + ValueError + If a retriever reference must be compared and no registry was given. + """ + try: + old_identity = _retriever_identity(old_value, self._registry) + except RAGComponentNotFoundError as error: + log.warning("%s; treating the retriever as changed.", error) + return True + return old_identity != _retriever_identity(new_value, self._registry) + def _drop_chunking_model_if_unused(self, session_id: int) -> None: """Release the chunking model a session's pipeline points at. @@ -326,26 +399,53 @@ def _cleanup_composite_retriever( ) for bridge in composite_bridges: - child_links = ( - self.db.query(RAGRetrieverChild) - .filter_by(parent_id=bridge.id) - .order_by(RAGRetrieverChild.child_order) - .all() - ) - for link in child_links: - child_bridge = self.db.query(RAGRetriever).get(link.child_id) - if child_bridge is None: - continue - if child_bridge.sparse_detail: - detail = child_bridge.sparse_detail - if not self._sparse_folder_in_use( - detail.storage_folder, exclude_ids=[detail.id] - ): - remove_after_commit(self.db, detail.storage_folder) - self.db.delete(detail) - elif child_bridge.dense_detail: - self.db.delete(child_bridge.dense_detail) - self.db.delete(bridge) + self._release_bridge_tree(bridge) + + def _release_bridge_tree(self, bridge: RAGRetriever) -> None: + """Delete a composite bridge together with every child bridge beneath it. + + Children are released first, recursively, so a composite nested in + another composite leaves no orphaned bridge row. A leaf's fitted detail + goes with its bridge; a sparse storage folder is removed only once no + other row still uses it. + + Parameters + ---------- + bridge : RAGRetriever + The composite or leaf bridge to delete. + """ + child_links = ( + self.db.query(RAGRetrieverChild) + .filter_by(parent_id=bridge.id) + .order_by(RAGRetrieverChild.child_order) + .all() + ) + for link in child_links: + child_bridge = self.db.get(RAGRetriever, link.child_id) + if child_bridge is not None: + self._release_bridge_tree(child_bridge) + if bridge.sparse_detail is not None: + self._cleanup_sparse_retriever(bridge) + elif bridge.dense_detail is not None: + self.db.delete(bridge.dense_detail) + self._delete_bridge_row(bridge) + + def _delete_bridge_row(self, bridge: RAGRetriever) -> None: + """Delete a bridge row and every child link that points at it. + + The links where the bridge is the parent are removed with it through + the ORM cascade. The links where it is a child are removed explicitly, + because nothing else would remove them and they would dangle. + + Parameters + ---------- + bridge : RAGRetriever + The bridge row to delete. + """ + self.db.query(RAGRetrieverChild).filter( + RAGRetrieverChild.child_id == bridge.id + ).delete(synchronize_session="fetch") + self.db.delete(bridge) def _cleanup_unit_retriever( self, @@ -369,22 +469,22 @@ def _cleanup_unit_retriever( if pipeline_id is None: return - bridge = ( + # Every bridge of the class in this pipeline belongs to the configuration + # being replaced, so all of them go, not only the first one found. + bridges = ( self.db.query(RAGRetriever) .filter( RAGRetriever.pipeline_id == pipeline_id, RAGRetriever.class_name == retriever_model_params.get("component"), ) - .first() + .all() ) - if bridge is None: - return - - if bridge.dense_detail is not None: - self._cleanup_dense_retriever(bridge, documents_ids) - elif bridge.sparse_detail is not None: - self._cleanup_sparse_retriever(bridge) - self.db.delete(bridge) + for bridge in bridges: + if bridge.dense_detail is not None: + self._cleanup_dense_retriever(bridge, documents_ids) + elif bridge.sparse_detail is not None: + self._cleanup_sparse_retriever(bridge) + self._delete_bridge_row(bridge) def _cleanup_dense_retriever( self, diff --git a/DashAI/back/services/RAG/index_status_service.py b/DashAI/back/services/RAG/index_status_service.py index 45a14792b..ab1306c8e 100644 --- a/DashAI/back/services/RAG/index_status_service.py +++ b/DashAI/back/services/RAG/index_status_service.py @@ -18,6 +18,7 @@ from sqlalchemy.orm import Session +from DashAI.back.core.schema_fields.utils import normalize_payload from DashAI.back.core.utils import MultilingualString from DashAI.back.dependencies.database.models import ( DataDocument, @@ -28,7 +29,9 @@ ) from DashAI.back.dependencies.job_queues.base_job_queue import BaseJobQueue from DashAI.back.dependencies.registry.component_registry import ComponentRegistry +from DashAI.back.models.RAG.exceptions import RAGComponentNotFoundError from DashAI.back.models.RAG.RAG_constants import ( + COMPOSITE_RETRIEVER_NAMES, RAG_PARAM_CHUNKING_MODEL, RAG_PARAM_DOCUMENTS, RAG_PARAM_RETRIEVER_MODEL, @@ -36,8 +39,13 @@ from DashAI.back.models.RAG.retrievers.dense.dense_embedding_retriever import ( DenseEmbeddingRetriever, ) -from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( - strip_expansion_options, +from DashAI.back.models.RAG.retrievers.persistence_signature import ( + persistence_signature, +) +from DashAI.back.models.RAG.retrievers.ref_utils import ( + CHILDREN_KEY, + COMPONENT_KEY, + PARAMS_KEY, ) from DashAI.back.models.RAG.retrievers.sparse.sparse_retriever import SparseRetriever from DashAI.back.services.RAG.chunking_service import ChunkingService @@ -366,36 +374,101 @@ def _retriever_ready( Composite retrievers are never cached by the pipeline — only their children are — so a composite is ready exactly when all of its leaves - are. The retrieve-then-expand options are stripped before the lookup: - they are post-processing knobs, so toggling them must not report a - stale index. + are. A composite without children has no leaves to check, so it is not + ready. + + Parameters + ---------- + retriever : Optional[Dict[str, Any]] + A stored ``{component, params}`` retriever reference, possibly + wrapped in the frontend's ``properties`` form. + chunk_set_id : int + The chunk set the retriever was fitted on. + + Returns + ------- + bool + ``True`` when the retriever and all of its children are fitted. """ - if not isinstance(retriever, dict) or not retriever.get("component"): + if not isinstance(retriever, dict): + return False + # A stored session may still hold the frontend's ``properties`` wrapper; + # reading the canonical form keeps the lookup key the same as setup's. + canonical = normalize_payload(retriever) + component = canonical.get(COMPONENT_KEY) + if not isinstance(component, str) or not component: return False - params = retriever.get("params") or {} - - children = params.get("children") - if isinstance(children, list) and children: - return all( - self._retriever_ready(child, chunk_set_id) - for child in children - if isinstance(child, dict) + params = canonical.get(PARAMS_KEY) + if not isinstance(params, dict): + return False + if component in COMPOSITE_RETRIEVER_NAMES or CHILDREN_KEY in params: + return self._composite_children_ready( + params.get(CHILDREN_KEY), chunk_set_id ) + return self._unit_ready(component, params, chunk_set_id) + + def _composite_children_ready(self, children: Any, chunk_set_id: int) -> bool: + """Whether a composite's child list is non-empty and every child is fitted. - component = retriever["component"] + Parameters + ---------- + children : Any + The ``children`` parameter of a composite. Anything other than a + non-empty list is not ready. + chunk_set_id : int + The chunk set the children were fitted on. + + Returns + ------- + bool + ``True`` when every child is a fitted retriever. + """ + if not isinstance(children, list) or not children: + return False + return all(self._retriever_ready(child, chunk_set_id) for child in children) + + def _unit_ready( + self, component: str, params: Dict[str, Any], chunk_set_id: int + ) -> bool: + """Whether a unit retriever has a fitted row matching its signature. + + The lookup uses the retriever's persistence signature, so query-time + knobs (``top_k``, the distance metric, retrieve-then-expand) never report + a stale index. + + Parameters + ---------- + component : str + Registered name of the retriever. + params : Dict[str, Any] + The retriever's configuration parameters. + chunk_set_id : int + The chunk set the retriever was fitted on. + + Returns + ------- + bool + ``False`` when the component is unregistered, its configuration is + unresolvable, or no matching dense or sparse row exists. + """ if component not in self._registry: return False model_class = self._registry[component]["class"] - sorted_params = dict(sorted(strip_expansion_options(params).items())) + try: + signature = persistence_signature(model_class, params, self._registry) + except (RAGComponentNotFoundError, ValueError): + # An unresolvable nested component means nothing fitted can match it. + log.warning("Retriever %s has an unresolvable configuration.", component) + return False try: if issubclass(model_class, DenseEmbeddingRetriever): return ( - self._retrievers.find_dense(component, sorted_params, chunk_set_id) + self._retrievers.find_dense(component, signature, chunk_set_id) is not None ) if issubclass(model_class, SparseRetriever): return ( - self._retrievers.find_sparse(component, sorted_params, chunk_set_id) + self._retrievers.find_sparse(component, signature, chunk_set_id) is not None ) except Exception: # pragma: no cover - defensive, status must not 500 diff --git a/DashAI/back/services/RAG/retriever_setup_service.py b/DashAI/back/services/RAG/retriever_setup_service.py index d252d6a04..795c5e320 100644 --- a/DashAI/back/services/RAG/retriever_setup_service.py +++ b/DashAI/back/services/RAG/retriever_setup_service.py @@ -40,8 +40,8 @@ DensePersistence, SparsePersistence, ) -from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( - strip_expansion_options, +from DashAI.back.models.RAG.retrievers.persistence_signature import ( + persistence_signature, ) from DashAI.back.models.RAG.retrievers.retriever_factory import ( RetrieverFactory, @@ -183,7 +183,7 @@ def setup( if issubclass(model_class, CompositeRetriever): return self._setup_composite(model_class, params) - identity_params = dict(sorted(strip_expansion_options(params).items())) + identity_params = persistence_signature(model_class, params, self._registry) loaded = self._load_unit_from_db( model_class, model_class.__name__, identity_params, params ) @@ -463,11 +463,11 @@ def _build_sparse_persistence_for( sessions over the same corpus with the same configuration share one fitted state, while a different corpus produces a different folder. - Parameters excluded from the identity: the retrieve-then-expand options - (post-processing), ``top_k`` (how many rows are returned, not how they - are scored) and ``similarity_function`` (the distance used at query - time). Vectorizer, ``k1``/``b``/``delta`` and the TF-IDF settings all - stay, because changing them changes the fitted matrix. + The identity is the retriever's persistence signature: the query-time + parameters the class declares in ``NON_PERSISTENT_PARAMS`` (the + retrieve-then-expand options, ``top_k``, the distance metric) are + left out, while everything that changes the fitted matrix stays, + including the parameters of nested components such as the vectorizer. Args: model_class: Retriever model class. @@ -476,9 +476,7 @@ def _build_sparse_persistence_for( Returns: A SparsePersistence instance pointing to the computed folder. """ - artifact_params = strip_expansion_options(params) - artifact_params.pop("top_k", None) - artifact_params.pop("similarity_function", None) + artifact_params = persistence_signature(model_class, params, self._registry) identity = hash_function( json.dumps( { diff --git a/DashAI/back/services/workflows/RAG_workflow_session_service.py b/DashAI/back/services/workflows/RAG_workflow_session_service.py index 0f74b2e90..7a11280fa 100644 --- a/DashAI/back/services/workflows/RAG_workflow_session_service.py +++ b/DashAI/back/services/workflows/RAG_workflow_session_service.py @@ -492,7 +492,7 @@ def apply_update( """ changes = changes or {} cancel_live_index_job(session, self.job_queue) - CleanupService(self.db).cleanup_orphaned_resources( + CleanupService(self.db, self.component_registry).cleanup_orphaned_resources( session.id, old_parameters, updated_parameters, commit=False ) with self._write_errors(): diff --git a/tests/back/RAG/test_retriever_identity.py b/tests/back/RAG/test_retriever_identity.py index 68e2c1f77..07dd2f91d 100644 --- a/tests/back/RAG/test_retriever_identity.py +++ b/tests/back/RAG/test_retriever_identity.py @@ -8,6 +8,9 @@ the cache key ignores them. """ +import copy +import json +import logging import uuid from pathlib import Path from typing import Any, Dict @@ -15,6 +18,7 @@ import pytest from fastapi.testclient import TestClient +from DashAI.back.converters.scikit_learn.bag_of_words import BagOfWordsConverter from DashAI.back.dependencies.database.models import ( RAGChunkSet, RAGPipeline, @@ -23,14 +27,26 @@ RAGSparseRetriever, ) from DashAI.back.models.RAG.documents import Chunk +from DashAI.back.models.RAG.exceptions import RAGComponentNotFoundError +from DashAI.back.models.RAG.retrievers.composite.mmr_reranker_retriever import ( + MMRRerankerRetriever, +) +from DashAI.back.models.RAG.retrievers.composite.parallel_retriever import ( + ParallelRetriever, +) +from DashAI.back.models.RAG.retrievers.persistence_signature import ( + persistence_signature, +) from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( ENABLE_FIELD, WINDOW_FIELD, strip_expansion_options, ) +from DashAI.back.models.RAG.retrievers.similarity import CosineSimilarity from DashAI.back.models.RAG.retrievers.sparse.bm25_retriever import BM25Retriever from DashAI.back.services.RAG import retriever_presets from DashAI.back.services.RAG.cleanup_service import CleanupService +from DashAI.back.services.RAG.index_status_service import IndexStatusService from DashAI.back.services.RAG.retriever_setup_service import RetrieverSetupService from DashAI.back.services.RAG.session_configuration_service import ( SessionConfigurationService, @@ -54,6 +70,14 @@ def _preset(client: TestClient, key: str) -> Dict[str, Any]: raise AssertionError(f"preset {key} is missing") +#: Just the classes the artifact-identity tests nest inside BM25 parameters. +_REGISTRY = { + "BagOfWordsConverter": {"class": BagOfWordsConverter}, + "CosineSimilarity": {"class": CosineSimilarity}, + "BM25Retriever": {"class": BM25Retriever}, +} + + def _setup_service( db, chunks: Dict[int, Dict[int, Chunk]] | None = None, @@ -64,7 +88,7 @@ def _setup_service( """Return a setup service with the minimal wiring the artifact hash needs.""" return RetrieverSetupService( db=db, - registry={}, + registry=_REGISTRY, env_RAG_path=env_rag_path, chunks=chunks or {}, chunk_set_id=chunk_set_id, @@ -301,7 +325,13 @@ def _sparse_retriever_state(db, session_id: int, tmp_path, params: Dict[str, Any return bridge, detail, folder -def _composite_retriever_state(db, session_id: int, tmp_path, params: Dict[str, Any]): +def _composite_retriever_state( + db, + session_id: int, + tmp_path, + params: Dict[str, Any], + parent_class: str = "ParallelRetriever", +): """Insert a session pipeline with a composite retriever and one child.""" chunk_set = RAGChunkSet( signature=uuid.uuid4().hex, parameters={}, session_id=session_id @@ -324,7 +354,7 @@ def _composite_retriever_state(db, session_id: int, tmp_path, params: Dict[str, storage_folder=str(folder), ) db.add(child_detail) - parent = RAGRetriever(class_name="ParallelRetriever", pipeline_id=pipeline.id) + parent = RAGRetriever(class_name=parent_class, pipeline_id=pipeline.id) db.add(parent) db.flush() db.add( @@ -357,7 +387,7 @@ def test_toggling_expansion_options_does_not_delete_a_unit_retriever( }, } - CleanupService(db).cleanup_orphaned_resources( + CleanupService(db, _registry(client)).cleanup_orphaned_resources( session_id, old_parameters, new_parameters ) @@ -389,7 +419,7 @@ def test_changing_a_fitted_parameter_does_delete_the_unit_retriever( }, } - CleanupService(db).cleanup_orphaned_resources( + CleanupService(db, _registry(client)).cleanup_orphaned_resources( session_id, old_parameters, new_parameters ) @@ -436,7 +466,7 @@ def test_toggling_expansion_options_does_not_delete_a_composite_retriever( }, } - CleanupService(db).cleanup_orphaned_resources( + CleanupService(db, _registry(client)).cleanup_orphaned_resources( session_id, old_parameters, new_parameters ) @@ -735,3 +765,507 @@ def test_cache_hit_keeps_the_expansion_options_on_the_live_model( assert retrieved[0].document_position == 2 assert retrieved[0].source_positions == (2, 3, 4) assert trace["chunks"] == ["1_2"] + + +# ── Persistence signature ──────────────────────────────────────────────────── + + +def test_changing_the_distance_metric_keeps_the_sparse_storage_folder(orm_db): + """The distance metric acts at query time, so it never moves the folder.""" + service = _setup_service(orm_db, chunks=_artifact_corpus()) + params = bm25_retriever_params() + other_metric = { + **params, + "similarity_function": {"component": "CosineSimilarity", "params": {"x": 1}}, + } + + assert ( + service._build_sparse_persistence_for(BM25Retriever, params).model_dir + == service._build_sparse_persistence_for(BM25Retriever, other_metric).model_dir + ) + + +def test_signature_drops_query_time_params_and_keeps_nested_fitted_ones(): + """``top_k`` and the metric go; the vectorizer's parameters stay.""" + params = bm25_retriever_params() + changed_vectorizer = { + **params, + "vectorizer": {"component": "BagOfWordsConverter", "params": {"lowercase": 0}}, + } + + base = persistence_signature(BM25Retriever, params, _REGISTRY) + + assert "top_k" not in base + assert "similarity_function" not in base + assert base == persistence_signature( + BM25Retriever, {**params, "top_k": 9, **ENABLED_PARAMS}, _REGISTRY + ) + assert base != persistence_signature(BM25Retriever, changed_vectorizer, _REGISTRY) + + +def test_signature_uses_the_declaration_of_nested_components(): + """A nested class's own ``NON_PERSISTENT_PARAMS`` applies inside the ref.""" + + class Inner: + NON_PERSISTENT_PARAMS = ("cache_size",) + + registry = {"Inner": {"class": Inner}} + reference = {"component": "Inner", "params": {"cache_size": 1, "model": "m"}} + + class Outer: + NON_PERSISTENT_PARAMS = ("top_k",) + + signature = persistence_signature( + Outer, {"top_k": 3, "child": reference, "items": [reference]}, registry + ) + + expected = {"component": "Inner", "params": {"model": "m"}} + assert signature == {"child": expected, "items": [expected]} + + +def test_signature_rejects_an_unregistered_nested_component(): + """A component the registry does not know is an error, not a default.""" + reference = {"component": "Missing", "params": {}} + + with pytest.raises(RAGComponentNotFoundError): + persistence_signature(BM25Retriever, {"child": reference}, {}) + + +def test_changing_the_distance_metric_does_not_delete_a_unit_retriever( + client: TestClient, tmp_path +): + """Only the metric and ``top_k`` changed, so the fitted retriever stays.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session_id = _insert_rag_session( + db, f"identity_metric_{uuid.uuid4().hex[:6]}" + ).id + params = bm25_retriever_params() + bridge, detail, folder = _sparse_retriever_state( + db, session_id, tmp_path, params + ) + old_parameters = { + "documents": [], + "retriever_model": {"component": "BM25Retriever", "params": params}, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": "BM25Retriever", + "params": { + **params, + "top_k": 9, + "similarity_function": { + "component": "EuclideanSimilarity", + "params": {}, + }, + }, + }, + } + + CleanupService(db, _registry(client)).cleanup_orphaned_resources( + session_id, old_parameters, new_parameters + ) + + assert db.get(RAGRetriever, bridge.id) is not None + assert db.get(RAGSparseRetriever, detail.id) is not None + assert folder.exists() + + +# ── Composite and nested signatures ────────────────────────────────────────── + +_COMPOSITE_REGISTRY = { + **_REGISTRY, + "MMRRerankerRetriever": {"class": MMRRerankerRetriever}, + "ParallelRetriever": {"class": ParallelRetriever}, +} + + +def _mmr_params(top_k: int, mmr_lambda: float) -> Dict[str, Any]: + """Return MMR reranker parameters over one BM25 child.""" + return { + "children": [{"component": "BM25Retriever", "params": bm25_retriever_params()}], + "mmr_lambda": mmr_lambda, + "top_k": top_k, + } + + +def test_mmr_top_k_and_lambda_do_not_change_the_signature(): + """MMR's selection knobs act at query time; only its child is persisted.""" + base = persistence_signature( + MMRRerankerRetriever, _mmr_params(3, 0.5), _COMPOSITE_REGISTRY + ) + retuned = persistence_signature( + MMRRerankerRetriever, _mmr_params(7, 0.9), _COMPOSITE_REGISTRY + ) + + assert base == retuned + assert list(base) == ["children"] + + +def test_parallel_merge_strategy_does_not_change_the_signature(): + """The merge strategy only combines child results at query time.""" + children = [{"component": "BM25Retriever", "params": bm25_retriever_params()}] + round_robin = persistence_signature( + ParallelRetriever, + {"merge_strategy": "round_robin", "children": children}, + _COMPOSITE_REGISTRY, + ) + interleave = persistence_signature( + ParallelRetriever, + {"merge_strategy": "interleave", "children": children}, + _COMPOSITE_REGISTRY, + ) + + assert round_robin == interleave + + +def test_nested_key_order_does_not_change_the_serialised_signature(): + """Natural-key lookups compare JSON text, so nested key order is canonical.""" + params = bm25_retriever_params() + forward_vectorizer = { + "component": "BagOfWordsConverter", + "params": {"alpha": 1, "beta": 2}, + } + backward_vectorizer = { + "component": "BagOfWordsConverter", + "params": {"beta": 2, "alpha": 1}, + } + forward = persistence_signature( + BM25Retriever, {**params, "vectorizer": forward_vectorizer}, _REGISTRY + ) + backward = persistence_signature( + BM25Retriever, {**params, "vectorizer": backward_vectorizer}, _REGISTRY + ) + + assert json.dumps(forward) == json.dumps(backward) + + +class _Holder: + """A nested component class without a ``NON_PERSISTENT_PARAMS`` declaration.""" + + +class _Inner: + """A nested component class that declares one query-time parameter.""" + + NON_PERSISTENT_PARAMS = ("cache_size",) + + +def test_refs_inside_a_plain_dict_value_are_resolved(): + """Plain dicts are searched for refs; undeclared classes keep all params.""" + registry = {"_Holder": {"class": _Holder}, "_Inner": {"class": _Inner}} + params = { + "kept": 1, + "settings": { + "child": {"component": "_Inner", "params": {"cache_size": 4, "model": "m"}} + }, + } + + signature = persistence_signature(_Holder, params, registry) + + assert signature == { + "kept": 1, + "settings": {"child": {"component": "_Inner", "params": {"model": "m"}}}, + } + + +def test_a_component_ref_with_non_dict_params_names_the_component(): + """Malformed nested params raise a clear error instead of an AttributeError.""" + reference = {"component": "BagOfWordsConverter", "params": "lowercase"} + + with pytest.raises(ValueError, match="BagOfWordsConverter"): + persistence_signature(BM25Retriever, {"vectorizer": reference}, _REGISTRY) + + +# ── Cleanup needs the registry only when it must compare ───────────────────── + + +def test_cleanup_without_a_registry_works_when_the_retriever_is_unchanged(orm_db): + """An unchanged retriever is compared raw, so no registry is needed.""" + parameters = { + "documents": [], + "retriever_model": { + "component": "BM25Retriever", + "params": bm25_retriever_params(), + }, + } + + CleanupService(orm_db).cleanup_orphaned_resources( + 999, parameters, copy.deepcopy(parameters) + ) + + +def test_unchanged_retriever_with_a_missing_plugin_does_not_raise(orm_db): + """A retriever whose plugin is gone is left alone while it is unchanged.""" + parameters = { + "documents": [], + "retriever_model": {"component": "PluginOnlyRetriever", "params": {"x": 1}}, + } + + CleanupService(orm_db).cleanup_orphaned_resources( + 999, parameters, copy.deepcopy(parameters) + ) + CleanupService(orm_db, {}).cleanup_orphaned_resources( + 999, parameters, copy.deepcopy(parameters) + ) + + +def test_changed_retriever_without_a_registry_raises_a_clear_error(orm_db): + """A real change must be compared, which needs a registry.""" + old_parameters = { + "documents": [], + "retriever_model": { + "component": "BM25Retriever", + "params": bm25_retriever_params(), + }, + } + new_parameters = copy.deepcopy(old_parameters) + new_parameters["retriever_model"]["params"]["k1"] = 2.0 + + with pytest.raises(ValueError, match="registry"): + CleanupService(orm_db).cleanup_orphaned_resources( + 999, old_parameters, new_parameters + ) + + +def test_changed_retriever_whose_old_plugin_is_gone_is_treated_as_changed( + orm_db, caplog +): + """An uninstalled plugin cannot be compared, so the switch must still go through. + + The old reference cannot be reduced to a signature, so it is taken as a real + change: the session is updated and the user can move to another retriever. + """ + old_parameters = { + "documents": [], + "retriever_model": {"component": "PluginOnlyRetriever", "params": {"x": 1}}, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": "BM25Retriever", + "params": bm25_retriever_params(), + }, + } + + with caplog.at_level(logging.WARNING, logger=CleanupService.__module__): + CleanupService(orm_db, _REGISTRY).cleanup_orphaned_resources( + 999, old_parameters, new_parameters + ) + + assert "PluginOnlyRetriever" in caplog.text + + +_COMPOSITE_KNOB_CASES = [ + ( + "MMRRerankerRetriever", + {"top_k": 3, "mmr_lambda": 0.5}, + {"top_k": 9, "mmr_lambda": 0.5}, + ), + ( + "MMRRerankerRetriever", + {"top_k": 3, "mmr_lambda": 0.5}, + {"top_k": 3, "mmr_lambda": 0.1}, + ), + ( + "ParallelRetriever", + {"merge_strategy": "round_robin"}, + {"merge_strategy": "interleave"}, + ), +] + + +@pytest.mark.parametrize( + ("parent_class", "old_knobs", "new_knobs"), _COMPOSITE_KNOB_CASES +) +def test_changing_a_composite_knob_keeps_its_child_state( + client: TestClient, tmp_path, parent_class, old_knobs, new_knobs +): + """Composite knobs are query-time: the child's sparse row and folder stay.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session_id = _insert_rag_session(db, f"identity_knob_{uuid.uuid4().hex[:6]}").id + child_params = bm25_retriever_params() + parent, child_bridge, folder = _composite_retriever_state( + db, session_id, tmp_path, child_params, parent_class=parent_class + ) + children = [{"component": "BM25Retriever", "params": child_params}] + old_parameters = { + "documents": [], + "retriever_model": { + "component": parent_class, + "params": {**old_knobs, "children": children}, + }, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": parent_class, + "params": {**new_knobs, "children": children}, + }, + } + + CleanupService(db, _registry(client)).cleanup_orphaned_resources( + session_id, old_parameters, new_parameters + ) + + assert db.get(RAGRetriever, parent.id) is not None + assert db.get(RAGRetriever, child_bridge.id) is not None + assert ( + db.query(RAGSparseRetriever).filter_by(bridge_id=child_bridge.id).count() + == 1 + ) + assert folder.exists() + + +# ── Index status readiness ─────────────────────────────────────────────────── + + +def test_a_composite_with_a_non_dict_child_is_not_ready(orm_db): + """A junk child cannot be verified, so the composite is not ready.""" + retriever = { + "component": "ParallelRetriever", + "params": {"merge_strategy": "round_robin", "children": ["junk"]}, + } + service = IndexStatusService(orm_db, _COMPOSITE_REGISTRY) + + assert service._retriever_ready(retriever, 7) is False + + +def test_a_composite_without_children_is_not_ready(orm_db): + """A composite with no ``children`` key has nothing to verify, so not ready.""" + retriever = { + "component": "ParallelRetriever", + "params": {"merge_strategy": "round_robin"}, + } + service = IndexStatusService(orm_db, _COMPOSITE_REGISTRY) + + assert service._retriever_ready(retriever, 7) is False + + +def test_an_unregistered_nested_component_is_not_ready(orm_db): + """An unknown nested component reports not-ready instead of raising.""" + params = { + **bm25_retriever_params(), + "vectorizer": {"component": "MissingConverter", "params": {}}, + } + service = IndexStatusService(orm_db, _REGISTRY) + + assert ( + service._retriever_ready({"component": "BM25Retriever", "params": params}, 7) + is False + ) + + +def test_a_wrapped_stored_retriever_is_matched_like_setup_matches_it(orm_db, tmp_path): + """A ``properties``-wrapped stored retriever resolves to its fitted row.""" + session_id = _insert_rag_session(orm_db, f"identity_wrap_{uuid.uuid4().hex[:6]}").id + params = bm25_retriever_params() + signature = persistence_signature(BM25Retriever, params, _REGISTRY) + _, detail, _ = _sparse_retriever_state(orm_db, session_id, tmp_path, signature) + wrapped = { + "properties": { + "component": "BM25Retriever", + "params": {"comp": {"component": "BM25Retriever", "params": params}}, + }, + } + service = IndexStatusService(orm_db, _REGISTRY) + + assert service._retriever_ready(wrapped, detail.chunk_set_id) is True + + +# ── Bridge rows ────────────────────────────────────────────────────────────── + + +def test_unit_cleanup_removes_every_bridge_of_the_class(client: TestClient, tmp_path): + """A stray bridge of the same class in the pipeline is removed too.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session_id = _insert_rag_session( + db, f"identity_stray_{uuid.uuid4().hex[:6]}" + ).id + params = bm25_retriever_params() + bridge, detail, _ = _sparse_retriever_state(db, session_id, tmp_path, params) + stray_bridge = RAGRetriever( + class_name="BM25Retriever", pipeline_id=bridge.pipeline_id + ) + db.add(stray_bridge) + db.flush() + db.add( + RAGSparseRetriever( + bridge_id=stray_bridge.id, + chunk_set_id=detail.chunk_set_id, + class_name="BM25Retriever", + parameters={"k1": 9.0}, + storage_folder=str(tmp_path / "stray_folder"), + ) + ) + db.commit() + bridge_id = bridge.id + stray_id = stray_bridge.id + old_parameters = { + "documents": [], + "retriever_model": {"component": "BM25Retriever", "params": params}, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": "BM25Retriever", + "params": {**params, "k1": 2.0}, + }, + } + + CleanupService(db, _registry(client)).cleanup_orphaned_resources( + session_id, old_parameters, new_parameters + ) + + assert db.get(RAGRetriever, bridge_id) is None + assert db.get(RAGRetriever, stray_id) is None + + +def test_composite_cleanup_removes_its_child_bridges(client: TestClient, tmp_path): + """A composite change deletes its child bridges and their links too.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session_id = _insert_rag_session( + db, f"identity_childbr_{uuid.uuid4().hex[:6]}" + ).id + child_params = bm25_retriever_params() + parent, child_bridge, _ = _composite_retriever_state( + db, session_id, tmp_path, child_params + ) + parent_id = parent.id + child_bridge_id = child_bridge.id + children = [{"component": "BM25Retriever", "params": child_params}] + old_parameters = { + "documents": [], + "retriever_model": { + "component": "ParallelRetriever", + "params": {"merge_strategy": "round_robin", "children": children}, + }, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "children": [ + { + "component": "BM25Retriever", + "params": {**child_params, "k1": 2.0}, + } + ], + }, + }, + } + + CleanupService(db, _registry(client)).cleanup_orphaned_resources( + session_id, old_parameters, new_parameters + ) + + assert db.get(RAGRetriever, parent_id) is None + assert db.get(RAGRetriever, child_bridge_id) is None + assert ( + db.query(RAGRetrieverChild).filter_by(child_id=child_bridge_id).count() == 0 + ) diff --git a/tests/back/services/test_workflow_session_services.py b/tests/back/services/test_workflow_session_services.py index 6780b42e7..11423fff0 100644 --- a/tests/back/services/test_workflow_session_services.py +++ b/tests/back/services/test_workflow_session_services.py @@ -95,15 +95,18 @@ def validate_update_payload(self, new_params: Dict[str, Any]) -> Dict[str, Any]: class FakeCleanup: """Stands in for ``CleanupService``, recording every call.""" - def __init__(self, db: Any) -> None: - """Keep the database session. + def __init__(self, db: Any, registry: Any = None) -> None: + """Keep the database session and registry. Parameters ---------- db : Any Database session. + registry : Any + Component registry, as passed by the real ``CleanupService``. """ self.db = db + self.registry = registry def cleanup_orphaned_resources( self, From 60b1e5bdbaa0698b6df590c030034eff59ce4441 Mon Sep 17 00:00:00 2001 From: sofiachavezb Date: Wed, 25 Nov 2026 18:32:49 -0300 Subject: [PATCH 3/8] fix(rag): treat any change but top-k as an advanced retriever configuration Preset matching now ignores only top_k, at every level of the config, so changing the similarity metric, the expansion options or batch_size shows the session as an advanced configuration. Legacy sessions without the expansion fields are compared strictly and may become advanced. batch_size is declared as a non-persistent parameter of the text embedding converters, and the embedding model row is keyed by its persistence signature, so changing it no longer creates a new embedding model and re-embeds every document. --- .../hugging_face/text_embedding/base.py | 6 + .../RAG/retrievers/retrieval_expansion.py | 21 +- DashAI/back/services/RAG/retriever_presets.py | 137 +++++- .../services/RAG/retriever_setup_service.py | 7 +- tests/back/RAG/test_retriever_identity.py | 390 ++++++++++++++++-- 5 files changed, 504 insertions(+), 57 deletions(-) diff --git a/DashAI/back/converters/hugging_face/text_embedding/base.py b/DashAI/back/converters/hugging_face/text_embedding/base.py index d4b231a5a..2a409c42c 100644 --- a/DashAI/back/converters/hugging_face/text_embedding/base.py +++ b/DashAI/back/converters/hugging_face/text_embedding/base.py @@ -35,6 +35,8 @@ TRUNCATE = "truncate" AGGREGATE = "aggregate" +#: Schema param name of the number of texts encoded together. +BATCH_SIZE_FIELD = "batch_size" SPECIAL_TOKENS = 2 #: Keeps a vector of zeros from dividing by zero while normalizing. NORMALIZATION_EPSILON = 1e-12 @@ -244,6 +246,10 @@ class TextEmbeddingConverter(AdvancedPreprocessingConverter, PretrainedTool): HF_IGNORE_PATTERNS = [*HFDownloadableMixin.HF_IGNORE_PATTERNS, "pytorch_model.bin"] QUERY_PROMPT: Optional[str] = None PASSAGE_PROMPT: Optional[str] = None + #: The batch size only trades memory for speed and never changes the vectors, + #: so it stays out of the persistence signature of any retriever that embeds + #: with this converter. + NON_PERSISTENT_PARAMS = (BATCH_SIZE_FIELD,) def close(self) -> None: """Release the loaded checkpoint so the next ``encode`` reloads it. diff --git a/DashAI/back/models/RAG/retrievers/retrieval_expansion.py b/DashAI/back/models/RAG/retrievers/retrieval_expansion.py index 67e7bcaec..3c9ad9b5f 100644 --- a/DashAI/back/models/RAG/retrievers/retrieval_expansion.py +++ b/DashAI/back/models/RAG/retrievers/retrieval_expansion.py @@ -77,35 +77,28 @@ def _strip_ignored_keys(value: Any, ignored_keys: Tuple[str, ...]) -> Any: return value -def strip_expansion_options( - params: Dict[str, Any], extra_keys: Tuple[str, ...] = () -) -> Dict[str, Any]: +def strip_expansion_options(params: Dict[str, Any]) -> Dict[str, Any]: """Return a copy of *params* without the retrieve-then-expand options. The two options are post-processing knobs: they never change what is indexed nor which stored model a configuration resolves to. They must therefore be excluded wherever a configuration acts as an *identity* — the - sparse persistence hash, the retriever table's natural key, the preset - match and the cleanup decision — or toggling them would force a re-index. - Removal is recursive so a composite's children are stripped too. + sparse persistence hash, the retriever table's natural key and the cleanup + decision — or toggling them would force a re-index. Removal is recursive so + a composite's children are stripped too. Parameters ---------- params : Dict[str, Any] Retriever parameters, possibly holding nested ``children`` refs. - extra_keys : Tuple[str, ...], optional - Additional parameter names to drop at every level, for callers whose - identity ignores more than the expansion options (for example - ``top_k`` in the preset match). Returns ------- Dict[str, Any] - A copy with ``ENABLE_FIELD`` and ``WINDOW_FIELD`` (and any - ``extra_keys``) removed at every level. The input mapping is never - mutated. + A copy with ``ENABLE_FIELD`` and ``WINDOW_FIELD`` removed at every + level. The input mapping is never mutated. """ - return _strip_ignored_keys(params, (ENABLE_FIELD, WINDOW_FIELD) + extra_keys) + return _strip_ignored_keys(params, (ENABLE_FIELD, WINDOW_FIELD)) def expansion_span(chunk: Chunk) -> int: diff --git a/DashAI/back/services/RAG/retriever_presets.py b/DashAI/back/services/RAG/retriever_presets.py index bbfff39ce..70e702f20 100644 --- a/DashAI/back/services/RAG/retriever_presets.py +++ b/DashAI/back/services/RAG/retriever_presets.py @@ -1,4 +1,11 @@ -"""Retriever preset recipes resolved from the component registry.""" +"""Retriever preset recipes resolved from the component registry. + +A stored retriever configuration belongs to a preset when it equals the preset +recipe, except for ``top_k``, which is ignored at every level because it is a +slider. Every other parameter, including the retrieve-then-expand options, must +match exactly. A legacy session stored without those options therefore counts +as a custom configuration; this is deliberate. +""" from typing import Any, Dict, Final, List, Optional, Tuple @@ -11,10 +18,11 @@ default_keyword_retriever, default_semantic_retriever, ) +from DashAI.back.models.RAG.retrievers.ref_utils import CHILDREN_KEY, PARAMS_KEY from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( ENABLE_FIELD, + TOP_K_FIELD, WINDOW_FIELD, - strip_expansion_options, ) _SEMANTIC_MODEL_SHORT = DEFAULT_SEMANTIC_MODEL_NAME.rsplit("/", 1)[-1] @@ -23,10 +31,11 @@ SEMANTIC_PRESET_KEY = "semantic" HYBRID_PRESET_KEY = "hybrid" -#: Keys that never decide which preset a configuration belongs to. ``top_k`` is -#: a slider, and the retrieve-then-expand options are post-processing knobs, so -#: a legacy session (without them) and one that set them still match a preset. -_IGNORED_MATCH_KEYS: Final[Tuple[str, ...]] = ("top_k", ENABLE_FIELD, WINDOW_FIELD) +#: Parameter names that never decide which preset a configuration belongs to. +#: ``top_k`` is a slider: a composite splits it across its children, so it is +#: dropped at every level. Every other parameter, including the expansion +#: options, takes part in the match. +_MATCH_IGNORED_KEYS: Final[Tuple[str, ...]] = (TOP_K_FIELD,) #: Preset a session gets when it does not choose one. Keyword retrieval is the #: only paradigm that needs no model download, so it is the one default that can @@ -181,24 +190,109 @@ def get_default_retriever(registry, top_k: int = DEFAULT_TOP_K) -> Dict[str, Any return {"component": recipe["component"], "params": recipe["params"]} -def _strip_match_ignored_keys(value: Dict[str, Any]) -> Dict[str, Any]: - """Drop the keys that never decide a preset match, at every level. +def _without_match_ignored_keys(value: Any) -> Any: + """Copy *value* with the match-ignored keys dropped at every level. - A preset keeps its shape when the user only moves the Top-K slider or - toggles retrieve-then-expand, so matching a stored config against a recipe - has to ignore those keys at every level (composite presets split ``top_k`` - across their children, and expansion options may sit on the parent, on a - child, or on neither in a legacy session). + Parameters + ---------- + value : Any + A parameters mapping, a list, or a leaf. + + Returns + ------- + Any + A copy in which every key of ``_MATCH_IGNORED_KEYS`` is removed from each + mapping, recursively. The input is never mutated. """ - return strip_expansion_options(value, _IGNORED_MATCH_KEYS) + if isinstance(value, dict): + kept: Dict[str, Any] = {} + for key, item in value.items(): + if key in _MATCH_IGNORED_KEYS: + continue + kept[key] = _without_match_ignored_keys(item) + return kept + if isinstance(value, list): + return [_without_match_ignored_keys(item) for item in value] + return value + + +def _normalize_children(children: Any) -> List[Dict[str, Any]]: + """Normalize every child ref of a composite for the preset match. + + Parameters + ---------- + children : Any + The ``children`` value of a composite's parameters. + + Returns + ------- + List[Dict[str, Any]] + New child refs whose ``params`` are normalized like the parent's. + + Raises + ------ + ValueError + If ``children`` is not a list, or a child is not a dict holding a + ``params`` dict. + """ + if not isinstance(children, list): + raise ValueError( + f"'{CHILDREN_KEY}' must be a list of component refs, " + f"got {type(children).__name__}" + ) + normalized: List[Dict[str, Any]] = [] + for child in children: + if not isinstance(child, dict) or not isinstance(child.get(PARAMS_KEY), dict): + raise ValueError( + f"each entry of '{CHILDREN_KEY}' must be a dict with a " + f"'{PARAMS_KEY}' dict, got {child!r}" + ) + child_params = _normalize_match_params(child[PARAMS_KEY]) + normalized.append({**child, PARAMS_KEY: child_params}) + return normalized + + +def _normalize_match_params(params: Dict[str, Any]) -> Dict[str, Any]: + """Return a copy of the configuration, normalized for the match. + + ``top_k`` is dropped at every level and each composite child is checked to + be a well-formed ref. Nothing else is filled in or rewritten, so a missing + parameter stays missing and only an exact equal value counts as a match. + + Parameters + ---------- + params : Dict[str, Any] + Retriever parameters, possibly holding ``children``. + + Returns + ------- + Dict[str, Any] + A normalized copy; the input is never mutated. + + Raises + ------ + ValueError + If ``children`` is present but is not a list of well-formed refs. + """ + normalized: Dict[str, Any] = _without_match_ignored_keys(params) + if CHILDREN_KEY in normalized: + normalized[CHILDREN_KEY] = _normalize_children(normalized[CHILDREN_KEY]) + return normalized def match_preset_key(component: str, params: Dict[str, Any], registry) -> Optional[str]: """Return the preset key a retriever config corresponds to, if any. - ``top_k`` and the retrieve-then-expand options are ignored at every level, - so a session created before those options existed still matches its preset, - and so does the same recipe with them set to any value. + Both the stored configuration and each candidate recipe are normalized by + ``_normalize_match_params``, and the normalized mappings must be equal. Only + ``top_k`` is ignored, so moving the slider keeps a preset, while any other + difference (expansion enabled or its window changed, a different similarity + metric, a different batch size) makes the configuration custom. + + This is deliberate for the expansion options: a legacy session stored before + they existed has no ``enable_retrieve_then_expand`` or ``expand_window`` key, + so it no longer equals a preset recipe and counts as a custom configuration. + Explicitly stating the default values does match. Parameters ---------- @@ -213,12 +307,17 @@ def match_preset_key(component: str, params: Dict[str, Any], registry) -> Option ------- str | None The matching preset key, or ``None`` for a custom configuration. + + Raises + ------ + ValueError + If the configuration's ``children`` are not well-formed component refs. """ - stripped = _strip_match_ignored_keys(params) + stored = _normalize_match_params(params) for preset in get_retriever_presets(DEFAULT_TOP_K, registry): if preset["component"] != component: continue - if _strip_match_ignored_keys(preset["params"]) == stripped: + if _normalize_match_params(preset["params"]) == stored: return preset["key"] return None diff --git a/DashAI/back/services/RAG/retriever_setup_service.py b/DashAI/back/services/RAG/retriever_setup_service.py index 795c5e320..9f188c65e 100644 --- a/DashAI/back/services/RAG/retriever_setup_service.py +++ b/DashAI/back/services/RAG/retriever_setup_service.py @@ -42,7 +42,9 @@ ) from DashAI.back.models.RAG.retrievers.persistence_signature import ( persistence_signature, + reference_signature, ) +from DashAI.back.models.RAG.retrievers.ref_utils import PARAMS_KEY from DashAI.back.models.RAG.retrievers.retriever_factory import ( RetrieverFactory, resolve_component_params, @@ -441,10 +443,13 @@ def _build_dense_persistence_for(self, params: dict) -> DensePersistence: if not class_name or not isinstance(parameters, dict): return DensePersistence(matrix_dirs={}, embedding_model_id=0) + # Query-time/speed knobs (e.g. batch_size) must not key the embedding + # row, or changing them would re-embed every document. + identity_parameters = reference_signature(emb_ref, self._registry)[PARAMS_KEY] try: emb_record = self._db_service.find_or_create_embedding_model( class_name, - dict(sorted(parameters.items())), + identity_parameters, commit=False, ) except SQLAlchemyError: diff --git a/tests/back/RAG/test_retriever_identity.py b/tests/back/RAG/test_retriever_identity.py index 07dd2f91d..44e7e8e00 100644 --- a/tests/back/RAG/test_retriever_identity.py +++ b/tests/back/RAG/test_retriever_identity.py @@ -2,10 +2,11 @@ The two options never change what is indexed nor which stored model a configuration resolves to. These tests pin the consequences: the sparse storage -hash, the cleanup decision, the preset match and the context budget all treat -them as such, while the budget still pays for the extra chunk text they add. -A cached retriever is loaded with the options the caller asked for even though -the cache key ignores them. +hash, the cleanup decision and the context budget all treat them as such, while +the budget still pays for the extra chunk text they add. The preset match is the +one deliberate exception: it compares the options strictly, so a configuration +that sets or omits them differently is custom. A cached retriever is loaded with +the options the caller asked for even though the cache key ignores them. """ import copy @@ -18,9 +19,20 @@ import pytest from fastapi.testclient import TestClient +from DashAI.back.converters.hugging_face.text_embedding.e5_mistral_gguf import ( + E5MistralGGUFEmbedding, +) +from DashAI.back.converters.hugging_face.text_embedding.sentence_transformer import ( + AllMiniLML6V2Embedding, +) +from DashAI.back.converters.hugging_face.text_embedding.transformer import ( + DistilBERTEmbedding, +) from DashAI.back.converters.scikit_learn.bag_of_words import BagOfWordsConverter from DashAI.back.dependencies.database.models import ( RAGChunkSet, + RAGDenseRetriever, + RAGEmbeddingModel, RAGPipeline, RAGRetriever, RAGRetrieverChild, @@ -34,11 +46,17 @@ from DashAI.back.models.RAG.retrievers.composite.parallel_retriever import ( ParallelRetriever, ) +from DashAI.back.models.RAG.retrievers.dense.dense_embedding_retriever import ( + DenseEmbeddingRetriever, +) from DashAI.back.models.RAG.retrievers.persistence_signature import ( persistence_signature, ) from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( + DEFAULT_ENABLE_RETRIEVE_THEN_EXPAND, + DEFAULT_EXPAND_WINDOW, ENABLE_FIELD, + TOP_K_FIELD, WINDOW_FIELD, strip_expansion_options, ) @@ -478,9 +496,13 @@ def test_toggling_expansion_options_does_not_delete_a_composite_retriever( # ── Preset matching ────────────────────────────────────────────────────────── -def test_legacy_recipe_without_the_options_matches_its_preset(client: TestClient): - """A session stored before the options existed still matches its preset.""" - preset = _preset(client, retriever_presets.KEYWORD_PRESET_KEY) +@pytest.mark.parametrize( + "key", + [retriever_presets.KEYWORD_PRESET_KEY, retriever_presets.HYBRID_PRESET_KEY], +) +def test_legacy_recipe_without_the_options_is_custom(client: TestClient, key: str): + """A session stored before the options existed counts as custom, by design.""" + preset = _preset(client, key) legacy = strip_expansion_options(preset["params"]) assert ENABLE_FIELD not in legacy @@ -489,14 +511,52 @@ def test_legacy_recipe_without_the_options_matches_its_preset(client: TestClient retriever_presets.match_preset_key( preset["component"], legacy, _registry(client) ) - == retriever_presets.KEYWORD_PRESET_KEY + is None ) -def test_recipe_with_the_options_set_matches_its_preset(client: TestClient): - """Explicit (even non-default) options do not make a preset look custom.""" +def _with_top_k(params: Dict[str, Any], top_k: int) -> Dict[str, Any]: + """Return *params* with ``top_k`` set at the parent and on every child.""" + retuned = {**params, TOP_K_FIELD: top_k} + if "children" in params: + retuned["children"] = [ + {**child, "params": _with_top_k(child["params"], top_k)} + for child in params["children"] + ] + return retuned + + +def test_recipe_with_the_options_set_to_other_values_is_custom(client: TestClient): + """Enabling expansion or changing its window makes the configuration custom.""" preset = _preset(client, retriever_presets.KEYWORD_PRESET_KEY) - configured = {**preset["params"], ENABLE_FIELD: True, WINDOW_FIELD: 7} + + enabled = {**preset["params"], ENABLE_FIELD: True} + widened = {**preset["params"], WINDOW_FIELD: 7} + + assert ( + retriever_presets.match_preset_key( + preset["component"], enabled, _registry(client) + ) + is None + ) + assert ( + retriever_presets.match_preset_key( + preset["component"], widened, _registry(client) + ) + is None + ) + + +def test_recipe_with_the_options_set_to_their_defaults_matches_its_preset( + client: TestClient, +): + """Explicitly stating the default options still matches the preset.""" + preset = _preset(client, retriever_presets.KEYWORD_PRESET_KEY) + configured = { + **preset["params"], + ENABLE_FIELD: DEFAULT_ENABLE_RETRIEVE_THEN_EXPAND, + WINDOW_FIELD: DEFAULT_EXPAND_WINDOW, + } assert ( retriever_presets.match_preset_key( @@ -506,26 +566,106 @@ def test_recipe_with_the_options_set_matches_its_preset(client: TestClient): ) -def test_nested_options_do_not_break_a_composite_preset_match(client: TestClient): - """Options at the parent and on a child leave the hybrid preset matching.""" +def test_options_on_the_parent_or_a_child_make_a_composite_custom(client: TestClient): + """Expansion on the composite or on one child is a custom configuration.""" preset = _preset(client, retriever_presets.HYBRID_PRESET_KEY) - legacy = strip_expansion_options(preset["params"]) - children = [] - for index, child in enumerate(legacy["children"]): - child_params = dict(child["params"]) - if index == 0: - child_params.update(ENABLED_PARAMS) - children.append({"component": child["component"], "params": child_params}) - configured = {**legacy, "children": children, **ENABLED_PARAMS} + first, *rest = preset["params"]["children"] + on_parent = {**preset["params"], **ENABLED_PARAMS} + on_child = { + **preset["params"], + "children": [ + {**first, "params": {**first["params"], **ENABLED_PARAMS}}, + *rest, + ], + } + + for configured in (on_parent, on_child): + assert ( + retriever_presets.match_preset_key( + preset["component"], configured, _registry(client) + ) + is None + ) + + +@pytest.mark.parametrize( + "key", + [retriever_presets.KEYWORD_PRESET_KEY, retriever_presets.HYBRID_PRESET_KEY], +) +def test_a_different_top_k_alone_keeps_the_preset(client: TestClient, key: str): + """Moving the Top-K slider never turns a preset into a custom configuration.""" + preset = _preset(client, key) assert ( retriever_presets.match_preset_key( - preset["component"], configured, _registry(client) + preset["component"], _with_top_k(preset["params"], 3), _registry(client) ) - == retriever_presets.HYBRID_PRESET_KEY + == key ) +def test_a_different_similarity_metric_makes_the_semantic_config_custom( + client: TestClient, +): + """The similarity metric decides the preset, so a change is a custom config.""" + preset = _preset(client, retriever_presets.SEMANTIC_PRESET_KEY) + euclidean = { + **preset["params"], + "similarity_metric": {"component": "EuclideanSimilarity", "params": {}}, + } + + assert ( + retriever_presets.match_preset_key( + preset["component"], euclidean, _registry(client) + ) + is None + ) + + +def test_a_different_batch_size_makes_the_semantic_config_custom(client: TestClient): + """The preset match is strict: a batch size other than the recipe's is custom.""" + preset = _preset(client, retriever_presets.SEMANTIC_PRESET_KEY) + + assert ( + retriever_presets.match_preset_key( + preset["component"], + _with_batch_size(preset["params"], 8), + _registry(client), + ) + is None + ) + + +@pytest.mark.parametrize( + "children", + [ + "junk", + ["junk"], + [{"component": "BM25Retriever", "params": "lowercase"}], + ], +) +def test_malformed_children_raise_a_value_error(client: TestClient, children): + """Children that are not well-formed refs raise instead of being tolerated.""" + preset = _preset(client, retriever_presets.HYBRID_PRESET_KEY) + malformed = {**preset["params"], "children": children} + + with pytest.raises(ValueError, match="children"): + retriever_presets.match_preset_key( + preset["component"], malformed, _registry(client) + ) + + +def test_matching_does_not_mutate_the_stored_params(client: TestClient): + """Normalizing for the match works on copies of the stored configuration.""" + preset = _preset(client, retriever_presets.HYBRID_PRESET_KEY) + stored = _with_top_k(preset["params"], 2) + snapshot = copy.deepcopy(stored) + + retriever_presets.match_preset_key(preset["component"], stored, _registry(client)) + + assert stored == snapshot + + # ── Effective chunk count ──────────────────────────────────────────────────── @@ -872,6 +1012,210 @@ def test_changing_the_distance_metric_does_not_delete_a_unit_retriever( assert folder.exists() +# ── Embedding batch size ───────────────────────────────────────────────────── + +_EMBEDDING_PARAMS: Dict[str, Any] = { + "device": "cpu", + "batch_size": 32, + "normalize": True, + "overflow_strategy": "truncate", +} +_EMBEDDING_REGISTRY = {"AllMiniLML6V2Embedding": {"class": AllMiniLML6V2Embedding}} + + +def _dense_params(embedding_params: Dict[str, Any]) -> Dict[str, Any]: + """Return dense retriever parameters around an embedding model's params.""" + return { + "embedding_model": { + "component": "AllMiniLML6V2Embedding", + "params": embedding_params, + }, + "similarity_metric": {"component": "CosineSimilarity", "params": {}}, + "top_k": 5, + } + + +def _with_batch_size(params: Dict[str, Any], batch_size: int) -> Dict[str, Any]: + """Return a configuration whose embedding model uses *batch_size*.""" + embedding = params["embedding_model"] + return { + **params, + "embedding_model": { + **embedding, + "params": {**embedding["params"], "batch_size": batch_size}, + }, + } + + +@pytest.mark.parametrize( + "embedding_class", + [AllMiniLML6V2Embedding, DistilBERTEmbedding, E5MistralGGUFEmbedding], +) +def test_batch_size_is_left_out_of_every_embedding_signature(embedding_class): + """Sentence-transformer, transformer and GGUF converters all inherit the rule.""" + small = persistence_signature(embedding_class, {"batch_size": 8}, {}) + large = persistence_signature(embedding_class, {"batch_size": 64}, {}) + + assert small == large == {} + + +def test_batch_size_does_not_change_the_dense_signature(): + """A memory-only knob inside the embedding ref keeps the identity.""" + small = _dense_params({**_EMBEDDING_PARAMS, "batch_size": 8}) + large = _dense_params({**_EMBEDDING_PARAMS, "batch_size": 64}) + + signature = persistence_signature( + DenseEmbeddingRetriever, large, _EMBEDDING_REGISTRY + ) + + assert "batch_size" not in signature["embedding_model"]["params"] + assert signature == persistence_signature( + DenseEmbeddingRetriever, small, _EMBEDDING_REGISTRY + ) + + +def test_normalization_still_changes_the_dense_signature(): + """The control: an embedding parameter that shapes the vectors still counts.""" + base = _dense_params(_EMBEDDING_PARAMS) + unnormalized = _dense_params({**_EMBEDDING_PARAMS, "normalize": False}) + + assert persistence_signature( + DenseEmbeddingRetriever, base, _EMBEDDING_REGISTRY + ) != persistence_signature( + DenseEmbeddingRetriever, unnormalized, _EMBEDDING_REGISTRY + ) + + +def test_batch_size_resolves_to_the_same_embedding_model_row(orm_db): + """Only a vector-shaping change resolves to a new embedding model id. + + A batch size change keeps the stored embedding row, so the documents are not + embedded again; normalization shapes the vectors and gets its own row. + """ + service = RetrieverSetupService( + db=orm_db, + registry=_EMBEDDING_REGISTRY, + env_RAG_path="rag-root", + chunks={}, + chunk_set_id=7, + pipeline_id=1, + chunking_key="test-chunking", + ) + small = service._build_dense_persistence_for( + _dense_params({**_EMBEDDING_PARAMS, "batch_size": 8}) + ) + large = service._build_dense_persistence_for( + _dense_params({**_EMBEDDING_PARAMS, "batch_size": 64}) + ) + unnormalized = service._build_dense_persistence_for( + _dense_params({**_EMBEDDING_PARAMS, "normalize": False}) + ) + + assert small.embedding_model_id == large.embedding_model_id + assert unnormalized.embedding_model_id != small.embedding_model_id + + +def _dense_retriever_state(db, session_id: int, params: Dict[str, Any]): + """Insert a session pipeline with one fitted dense retriever. + + The embedding row carries a unique marker instead of the converter params, + because the table is unique on (class, parameters) and is shared by every + test in the database. Cleanup never reads that row's parameters. + """ + chunk_set = RAGChunkSet( + signature=uuid.uuid4().hex, parameters={}, session_id=session_id + ) + db.add(chunk_set) + db.flush() + pipeline = RAGPipeline(session_id=session_id, name="") + db.add(pipeline) + db.flush() + embedding_model = RAGEmbeddingModel( + class_name="AllMiniLML6V2Embedding", + parameters={"marker": uuid.uuid4().hex}, + ) + db.add(embedding_model) + db.flush() + bridge = RAGRetriever(class_name="DenseEmbeddingRetriever", pipeline_id=pipeline.id) + db.add(bridge) + db.flush() + detail = RAGDenseRetriever( + bridge_id=bridge.id, + chunk_set_id=chunk_set.id, + class_name="DenseEmbeddingRetriever", + parameters=params, + embedding_model_id=embedding_model.id, + ) + db.add(detail) + db.commit() + return bridge, detail + + +def test_changing_the_batch_size_does_not_delete_a_dense_retriever( + client: TestClient, +): + """A batch size change keeps the fitted dense retriever and its embeddings.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session_id = _insert_rag_session( + db, f"identity_batch_{uuid.uuid4().hex[:6]}" + ).id + params = _dense_params(_EMBEDDING_PARAMS) + bridge, detail = _dense_retriever_state(db, session_id, params) + old_parameters = { + "documents": [], + "retriever_model": { + "component": "DenseEmbeddingRetriever", + "params": params, + }, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": "DenseEmbeddingRetriever", + "params": _with_batch_size(params, 8), + }, + } + + CleanupService(db, _registry(client)).cleanup_orphaned_resources( + session_id, old_parameters, new_parameters + ) + + assert db.get(RAGRetriever, bridge.id) is not None + assert db.get(RAGDenseRetriever, detail.id) is not None + + +def test_changing_the_normalization_does_delete_a_dense_retriever(client: TestClient): + """The control: a change to a vector-shaping parameter still triggers cleanup.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session_id = _insert_rag_session( + db, f"identity_norm_ctl_{uuid.uuid4().hex[:6]}" + ).id + params = _dense_params(_EMBEDDING_PARAMS) + bridge, _ = _dense_retriever_state(db, session_id, params) + old_parameters = { + "documents": [], + "retriever_model": { + "component": "DenseEmbeddingRetriever", + "params": params, + }, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": "DenseEmbeddingRetriever", + "params": _dense_params({**_EMBEDDING_PARAMS, "normalize": False}), + }, + } + + CleanupService(db, _registry(client)).cleanup_orphaned_resources( + session_id, old_parameters, new_parameters + ) + + assert db.get(RAGRetriever, bridge.id) is None + + # ── Composite and nested signatures ────────────────────────────────────────── _COMPOSITE_REGISTRY = { From 1047e78fe84d0a453d49a548b0a325ee967c5ce0 Mon Sep 17 00:00:00 2001 From: sofiachavezb Date: Thu, 26 Nov 2026 14:08:05 -0300 Subject: [PATCH 4/8] feat(rag): compare configurations with one strict structural equality Add configs_equal: deep, key-order independent, type strict (a boolean never equals a number, null is not absent), no subsets, explicit ignored keys. Preset matching, the index status and the session parameter history use it. Chunking presets now match exactly. --- .../api_v1/endpoints/generative_session.py | 3 +- DashAI/back/services/RAG/chunking_presets.py | 46 +- DashAI/back/services/RAG/config_equality.py | 379 +++++++++++ .../back/services/RAG/index_status_service.py | 17 +- DashAI/back/services/RAG/retriever_presets.py | 93 +-- tests/back/RAG/test_chunking_presets.py | 104 +++ tests/back/RAG/test_config_equality.py | 295 +++++++++ tests/shared/config_equality_cases.json | 625 ++++++++++++++++++ 8 files changed, 1474 insertions(+), 88 deletions(-) create mode 100644 DashAI/back/services/RAG/config_equality.py create mode 100644 tests/back/RAG/test_config_equality.py create mode 100644 tests/shared/config_equality_cases.json diff --git a/DashAI/back/api/api_v1/endpoints/generative_session.py b/DashAI/back/api/api_v1/endpoints/generative_session.py index d0cac70bd..002fe2a60 100644 --- a/DashAI/back/api/api_v1/endpoints/generative_session.py +++ b/DashAI/back/api/api_v1/endpoints/generative_session.py @@ -26,6 +26,7 @@ ) from DashAI.back.dependencies.downloads.nested import missing_downloads from DashAI.back.models.base_generative_model import BaseGenerativeModel +from DashAI.back.services.RAG.config_equality import configs_equal from DashAI.back.services.workflows import ( WorkflowConflictError, WorkflowSessionError, @@ -1306,7 +1307,7 @@ async def get_parameter_history_entry( for key in curr_params: old_val = prev_params.get(key) new_val = curr_params[key] - if old_val != new_val: + if not configs_equal(old_val, new_val): changes.append( { "parameter": key, diff --git a/DashAI/back/services/RAG/chunking_presets.py b/DashAI/back/services/RAG/chunking_presets.py index e7a9fced7..49806cd86 100644 --- a/DashAI/back/services/RAG/chunking_presets.py +++ b/DashAI/back/services/RAG/chunking_presets.py @@ -10,6 +10,7 @@ from DashAI.back.core.schema_fields.defaults import resolve_component_defaults from DashAI.back.core.utils import MultilingualString +from DashAI.back.services.RAG.config_equality import configs_equal #: Chunker every preset is built on. Character based so no download is needed. DEFAULT_CHUNKER = "CharacterChunkModel" @@ -113,31 +114,62 @@ def get_chunking_presets(registry) -> List[Dict[str, Any]]: def get_default_chunking(registry) -> Dict[str, Any]: - """Return the ``{component, params}`` ref for the default preset.""" - preset = next(p for p in _PRESETS if p["key"] == DEFAULT_PRESET_KEY) + """Return the ``{component, params}`` ref for the default preset. + + Raises + ------ + ValueError + If no preset carries the default key. + """ + preset = None + for candidate in _PRESETS: + if candidate["key"] == DEFAULT_PRESET_KEY: + preset = candidate + if preset is None: + raise ValueError( + f"No chunking preset has the default key {DEFAULT_PRESET_KEY!r}." + ) recipe = _build(preset, registry) return {"component": recipe["component"], "params": recipe["params"]} -def match_preset_key(component: str, params: Dict[str, Any]) -> str | None: +def match_preset_key(component: str, params: Dict[str, Any], registry) -> str | None: """Return the preset key a chunking config corresponds to, if any. + The configuration must equal a preset's full recipe, as built by + :func:`_build` and resolved against the registry, under + :func:`DashAI.back.services.RAG.config_equality.configs_equal`. A stored + configuration with an extra parameter, or a missing one, is custom. + Parameters ---------- component : str Chunker class name. params : dict Chunker parameters. + registry : ComponentRegistry + Registry used to resolve each preset's full recipe. Returns ------- str | None The matching preset key, or ``None`` for a custom configuration. + + Raises + ------ + TypeError + If the configuration holds a value outside the configuration contract. + ValueError + If the configuration holds a non-finite number, or an integer beyond the + safe integer range. """ + # configs_equal validates both of its arguments before comparing, so checking + # the stored params against themselves enforces the contract for every + # component, not only the one a preset can match. + configs_equal(params, params) if component != DEFAULT_CHUNKER: return None - for preset in _PRESETS: - config = preset["config"] - if all(params.get(key) == value for key, value in config.items()): - return preset["key"] + for recipe in get_chunking_presets(registry): + if configs_equal(recipe["params"], params): + return recipe["key"] return None diff --git a/DashAI/back/services/RAG/config_equality.py b/DashAI/back/services/RAG/config_equality.py new file mode 100644 index 000000000..0699d7a37 --- /dev/null +++ b/DashAI/back/services/RAG/config_equality.py @@ -0,0 +1,379 @@ +"""Structural equality for RAG configurations. + +This is the one comparison standard for RAG configurations. Every place in the +backend that decides whether two parameter sets, component references or +persistence signatures are the same uses :func:`configs_equal`. The frontend +mirrors this contract and reads the same examples from +``tests/shared/config_equality_cases.json``. + +Contract +-------- +Values: null, booleans, finite numbers, strings, arrays, objects with string +keys. Anything else (tuple, set, bytes, non-str dict keys, NaN/Infinity, custom +objects) raises a clear error (TypeError for unsupported types, ValueError for +non-finite numbers); never a silent default. + +Numbers beyond +/-(2**53 - 1) (:data:`MAX_SAFE_INTEGER`) are outside the +contract. An integer whose absolute value exceeds the bound is rejected, and so +is a float whose value is integral and whose absolute value exceeds it (1e20, +2.0**53, 1.5e300), with ValueError: JavaScript cannot represent them exactly and +the frontend would compare them differently. Fractional floats (0.5, 1e-9) and +integral values within the bound are ordinary numbers. + +Objects are equal iff, after dropping the ignored keys, they have exactly the +same keys and equal values; key order is irrelevant. No subsets: an extra or a +missing key makes them differ. + +Arrays are equal iff same length and element-wise equal IN ORDER. + +Strict types: a boolean is never equal to a number (False != 0, True != 1, +False != 0.0). null/None is never equal to an absent key. Numbers compare by +value, and 1 equals 1.0 (JavaScript cannot tell them apart, so the contract does +not either). Strings never equal numbers. + +Ignored keys: an optional, explicit collection of key names, applied recursively +at every object level, including objects nested in arrays and in component +references' ``params``. Default empty. + +Cross-language note: in JavaScript an object property whose value is +``undefined`` is treated as absent (it is what the wire/JSON carries); +``undefined`` anywhere else (top level, array element) is malformed and raises. + +Both inputs are validated completely before anything is compared, so a malformed +value raises even when the comparison would have stopped earlier, and the result +never depends on evaluation order. +""" + +import math +from collections.abc import Collection +from enum import Enum +from typing import Any, Dict, FrozenSet, List + +#: Largest integer magnitude JavaScript represents exactly (``MAX_SAFE_INTEGER``). +MAX_SAFE_INTEGER = 2**53 - 1 + +_ROOT_PATH = "$" + + +class _Kind(Enum): + """The contract's value categories.""" + + NULL = "null" + BOOLEAN = "boolean" + NUMBER = "number" + STRING = "string" + ARRAY = "array" + OBJECT = "object" + + +def _is_unsafe_number(value: int | float) -> bool: + """Whether a number lies beyond the safe range of the contract. + + Only integral values can be unsafe: a fractional float is never beyond the + bound, whatever its magnitude, so it is never rejected. + + Parameters + ---------- + value : int | float + A finite number. + + Returns + ------- + bool + ``True`` when *value* is integral and its absolute value exceeds + :data:`MAX_SAFE_INTEGER`. + """ + if isinstance(value, float) and not value.is_integer(): + return False + return abs(value) > MAX_SAFE_INTEGER + + +def _check_number(value: int | float, path: str) -> None: + """Check that one number is finite and within the safe range. + + Parameters + ---------- + value : int | float + The number to check. + path : str + Location of the value, used in error messages. + + Raises + ------ + ValueError + If the float is not finite, or the number is beyond + :data:`MAX_SAFE_INTEGER`. + """ + if isinstance(value, float) and not math.isfinite(value): + raise ValueError( + f"{path}: non-finite number {value!r} has no configuration equality" + ) + if _is_unsafe_number(value): + raise ValueError( + f"{path}: number {value!r} is outside the safe integer range " + f"+/-{MAX_SAFE_INTEGER}, which JavaScript cannot represent exactly" + ) + + +def _kind_of(value: Any, path: str) -> _Kind: + """Return the contract category of one value. + + Parameters + ---------- + value : Any + The value to classify. + path : str + Location of the value, used in error messages. + + Returns + ------- + _Kind + The category of *value*. + + Raises + ------ + TypeError + If the value is outside the contract. + ValueError + If the value is a non-finite number, or a number beyond + :data:`MAX_SAFE_INTEGER`. + """ + if value is None: + return _Kind.NULL + if isinstance(value, bool): + return _Kind.BOOLEAN + if isinstance(value, (int, float)): + _check_number(value, path) + return _Kind.NUMBER + if isinstance(value, str): + return _Kind.STRING + if isinstance(value, list): + return _Kind.ARRAY + if isinstance(value, dict): + return _Kind.OBJECT + raise TypeError( + f"{path}: unsupported configuration value of type {type(value).__name__}" + ) + + +def _validate(value: Any, path: str) -> None: + """Check that *value* and everything nested in it is within the contract. + + Parameters + ---------- + value : Any + The value to check. + path : str + Location of the value, used in error messages. + + Raises + ------ + TypeError + If the value or a nested value is outside the contract, or an object + key is not a string. + ValueError + If a nested number is not finite or is beyond the safe range. + """ + kind = _kind_of(value, path) + if kind is _Kind.ARRAY: + for index, item in enumerate(value): + _validate(item, f"{path}[{index}]") + elif kind is _Kind.OBJECT: + _validate_object(value, path) + + +def _validate_object(value: Dict[str, Any], path: str) -> None: + """Check the keys and values of one object, recursively. + + Parameters + ---------- + value : Dict[str, Any] + The object to check. + path : str + Location of the object, used in error messages. + + Raises + ------ + TypeError + If a key is not a string, or a nested value is outside the contract. + ValueError + If a nested number is not finite or is beyond the safe range. + """ + for key, item in value.items(): + if not isinstance(key, str): + raise TypeError( + f"{path}: object keys must be strings, got {type(key).__name__}" + ) + _validate(item, f"{path}.{key}") + + +def _ignored_names(ignored_keys: Collection[str]) -> FrozenSet[str]: + """Return the ignored key names as a frozen set, checking each one. + + Parameters + ---------- + ignored_keys : Collection[str] + Key names to drop at every object level. + + Returns + ------- + FrozenSet[str] + The names. + + Raises + ------ + TypeError + If *ignored_keys* is a bare string, or holds a non-string name. + """ + if isinstance(ignored_keys, str): + raise TypeError("ignored_keys must be a collection of key names, not a str") + names: List[str] = [] + for name in ignored_keys: + if not isinstance(name, str): + raise TypeError( + f"ignored key names must be strings, got {type(name).__name__}" + ) + names.append(name) + return frozenset(names) + + +def _kept_items(mapping: Dict[str, Any], ignored: FrozenSet[str]) -> Dict[str, Any]: + """Return the entries of *mapping* whose keys are not ignored. + + Parameters + ---------- + mapping : Dict[str, Any] + An already validated object. + ignored : FrozenSet[str] + Key names to drop at this level. + + Returns + ------- + Dict[str, Any] + A new mapping holding the remaining entries. + """ + kept: Dict[str, Any] = {} + for key, item in mapping.items(): + if key not in ignored: + kept[key] = item + return kept + + +def _same_array(left: List[Any], right: List[Any], ignored: FrozenSet[str]) -> bool: + """Return whether two validated arrays are equal element by element, in order. + + Parameters + ---------- + left : List[Any] + First array. + right : List[Any] + Second array. + ignored : FrozenSet[str] + Key names ignored inside the elements. + + Returns + ------- + bool + ``True`` when the lengths match and every pair of elements is equal. + """ + if len(left) != len(right): + return False + for left_item, right_item in zip(left, right, strict=True): + if not _same_value(left_item, right_item, ignored): + return False + return True + + +def _same_object( + left: Dict[str, Any], right: Dict[str, Any], ignored: FrozenSet[str] +) -> bool: + """Return whether two validated objects hold the same keys and values. + + Parameters + ---------- + left : Dict[str, Any] + First object. + right : Dict[str, Any] + Second object. + ignored : FrozenSet[str] + Key names dropped at this level and every level below it. + + Returns + ------- + bool + ``True`` when the kept keys are identical and every kept value is equal. + """ + left_kept = _kept_items(left, ignored) + right_kept = _kept_items(right, ignored) + if left_kept.keys() != right_kept.keys(): + return False + for key, item in left_kept.items(): + if not _same_value(item, right_kept[key], ignored): + return False + return True + + +def _same_value(left: Any, right: Any, ignored: FrozenSet[str]) -> bool: + """Return whether two validated values are equal under the contract. + + Parameters + ---------- + left : Any + First value, already validated. + right : Any + Second value, already validated. + ignored : FrozenSet[str] + Key names dropped at every object level. + + Returns + ------- + bool + ``True`` when the two values are equal. Values of different categories + are never equal, so a boolean never equals a number and null never + equals an absent key. + """ + # Both values were validated first, so the path is never reported. + kind = _kind_of(left, _ROOT_PATH) + if kind is not _kind_of(right, _ROOT_PATH): + return False + if kind is _Kind.NULL: + return True + if kind is _Kind.ARRAY: + return _same_array(left, right, ignored) + if kind is _Kind.OBJECT: + return _same_object(left, right, ignored) + return bool(left == right) + + +def configs_equal(left: Any, right: Any, ignored_keys: Collection[str] = ()) -> bool: + """Return whether two RAG configuration values are equal under the contract. + + Parameters + ---------- + left : Any + First configuration value: null, boolean, finite number, string, array + or object with string keys. + right : Any + Second configuration value, with the same allowed types. + ignored_keys : Collection[str], optional + Key names dropped at every object level, including objects nested in + arrays and in component references' ``params``. Defaults to none. + + Returns + ------- + bool + ``True`` when the two values are equal. + + Raises + ------ + TypeError + If either value, or *ignored_keys*, holds a value outside the contract, + or *ignored_keys* is a bare string. + ValueError + If either value holds a non-finite number or a number beyond + :data:`MAX_SAFE_INTEGER`. + """ + ignored = _ignored_names(ignored_keys) + _validate(left, _ROOT_PATH) + _validate(right, _ROOT_PATH) + return _same_value(left, right, ignored) diff --git a/DashAI/back/services/RAG/index_status_service.py b/DashAI/back/services/RAG/index_status_service.py index ab1306c8e..c18ec7e3c 100644 --- a/DashAI/back/services/RAG/index_status_service.py +++ b/DashAI/back/services/RAG/index_status_service.py @@ -49,6 +49,7 @@ ) from DashAI.back.models.RAG.retrievers.sparse.sparse_retriever import SparseRetriever from DashAI.back.services.RAG.chunking_service import ChunkingService +from DashAI.back.services.RAG.config_equality import configs_equal from DashAI.back.services.RAG.index_job_service import get_index_job, get_live_index_job from DashAI.back.services.RAG.retriever_db_service import RetrieverDBService @@ -170,9 +171,10 @@ def get_status(self, session_id: int) -> Dict[str, Any]: # Read from the parameters rather than the session's documents # relationship: _was_indexed_before compares against historized # parameters, and both sides have to come from the same source. - document_ids = [ - doc_id for doc_id in parameters.get(RAG_PARAM_DOCUMENTS) or [] if doc_id - ] + document_ids: list[int] = [] + for doc_id in parameters.get(RAG_PARAM_DOCUMENTS) or []: + if doc_id: + document_ids.append(doc_id) chunk_set = self._find_chunk_set(session_id, document_ids, parameters) counts = self._chunk_counts(chunk_set.id, document_ids) if chunk_set else {} @@ -306,11 +308,12 @@ def _was_indexed_before( for entry in history: parameters = dict(entry.parameters or {}) config = self._pipeline_config(parameters) - if config is None or config == current: + if config is None or configs_equal(config, current): continue - document_ids = [ - doc_id for doc_id in parameters.get(RAG_PARAM_DOCUMENTS) or [] if doc_id - ] + document_ids: List[int] = [] + for doc_id in parameters.get(RAG_PARAM_DOCUMENTS) or []: + if doc_id: + document_ids.append(doc_id) chunk_set = self._find_chunk_set(session_id, document_ids, parameters) if chunk_set and self._chunk_counts(chunk_set.id, document_ids): return True diff --git a/DashAI/back/services/RAG/retriever_presets.py b/DashAI/back/services/RAG/retriever_presets.py index 70e702f20..a8aa41411 100644 --- a/DashAI/back/services/RAG/retriever_presets.py +++ b/DashAI/back/services/RAG/retriever_presets.py @@ -24,6 +24,7 @@ TOP_K_FIELD, WINDOW_FIELD, ) +from DashAI.back.services.RAG.config_equality import configs_equal _SEMANTIC_MODEL_SHORT = DEFAULT_SEMANTIC_MODEL_NAME.rsplit("/", 1)[-1] @@ -190,102 +191,45 @@ def get_default_retriever(registry, top_k: int = DEFAULT_TOP_K) -> Dict[str, Any return {"component": recipe["component"], "params": recipe["params"]} -def _without_match_ignored_keys(value: Any) -> Any: - """Copy *value* with the match-ignored keys dropped at every level. - - Parameters - ---------- - value : Any - A parameters mapping, a list, or a leaf. - - Returns - ------- - Any - A copy in which every key of ``_MATCH_IGNORED_KEYS`` is removed from each - mapping, recursively. The input is never mutated. - """ - if isinstance(value, dict): - kept: Dict[str, Any] = {} - for key, item in value.items(): - if key in _MATCH_IGNORED_KEYS: - continue - kept[key] = _without_match_ignored_keys(item) - return kept - if isinstance(value, list): - return [_without_match_ignored_keys(item) for item in value] - return value +def _check_children(params: Dict[str, Any]) -> None: + """Check that every composite ``children`` entry is a well-formed ref. - -def _normalize_children(children: Any) -> List[Dict[str, Any]]: - """Normalize every child ref of a composite for the preset match. + Nested children are checked too, through each child's own ``params``. Parameters ---------- - children : Any - The ``children`` value of a composite's parameters. - - Returns - ------- - List[Dict[str, Any]] - New child refs whose ``params`` are normalized like the parent's. + params : Dict[str, Any] + Retriever parameters, possibly holding ``children``. Raises ------ ValueError - If ``children`` is not a list, or a child is not a dict holding a + If ``children`` is present but is not a list of dicts that each hold a ``params`` dict. """ + if CHILDREN_KEY not in params: + return + children = params[CHILDREN_KEY] if not isinstance(children, list): raise ValueError( f"'{CHILDREN_KEY}' must be a list of component refs, " f"got {type(children).__name__}" ) - normalized: List[Dict[str, Any]] = [] for child in children: if not isinstance(child, dict) or not isinstance(child.get(PARAMS_KEY), dict): raise ValueError( f"each entry of '{CHILDREN_KEY}' must be a dict with a " f"'{PARAMS_KEY}' dict, got {child!r}" ) - child_params = _normalize_match_params(child[PARAMS_KEY]) - normalized.append({**child, PARAMS_KEY: child_params}) - return normalized - - -def _normalize_match_params(params: Dict[str, Any]) -> Dict[str, Any]: - """Return a copy of the configuration, normalized for the match. - - ``top_k`` is dropped at every level and each composite child is checked to - be a well-formed ref. Nothing else is filled in or rewritten, so a missing - parameter stays missing and only an exact equal value counts as a match. - - Parameters - ---------- - params : Dict[str, Any] - Retriever parameters, possibly holding ``children``. - - Returns - ------- - Dict[str, Any] - A normalized copy; the input is never mutated. - - Raises - ------ - ValueError - If ``children`` is present but is not a list of well-formed refs. - """ - normalized: Dict[str, Any] = _without_match_ignored_keys(params) - if CHILDREN_KEY in normalized: - normalized[CHILDREN_KEY] = _normalize_children(normalized[CHILDREN_KEY]) - return normalized + _check_children(child[PARAMS_KEY]) def match_preset_key(component: str, params: Dict[str, Any], registry) -> Optional[str]: """Return the preset key a retriever config corresponds to, if any. - Both the stored configuration and each candidate recipe are normalized by - ``_normalize_match_params``, and the normalized mappings must be equal. Only - ``top_k`` is ignored, so moving the slider keeps a preset, while any other + The stored configuration and each candidate recipe are compared with + :func:`DashAI.back.services.RAG.config_equality.configs_equal`, ignoring + ``top_k`` at every level. Moving the slider keeps a preset, while any other difference (expansion enabled or its window changed, a different similarity metric, a different batch size) makes the configuration custom. @@ -311,13 +255,16 @@ def match_preset_key(component: str, params: Dict[str, Any], registry) -> Option Raises ------ ValueError - If the configuration's ``children`` are not well-formed component refs. + If the configuration's ``children`` are not well-formed component refs, + or it holds a non-finite number or an integer beyond the safe range. + TypeError + If the configuration holds a value outside the configuration contract. """ - stored = _normalize_match_params(params) + _check_children(params) for preset in get_retriever_presets(DEFAULT_TOP_K, registry): if preset["component"] != component: continue - if _normalize_match_params(preset["params"]) == stored: + if configs_equal(preset["params"], params, _MATCH_IGNORED_KEYS): return preset["key"] return None diff --git a/tests/back/RAG/test_chunking_presets.py b/tests/back/RAG/test_chunking_presets.py index 5b5f037c8..e1b19504a 100644 --- a/tests/back/RAG/test_chunking_presets.py +++ b/tests/back/RAG/test_chunking_presets.py @@ -1,7 +1,12 @@ """Tests for the chunking-presets endpoint.""" +from typing import Any + +import pytest from fastapi.testclient import TestClient +from DashAI.back.services.RAG import chunking_presets + def test_chunking_presets_returns_four_presets(client: TestClient): response = client.get("/api/v1/rag/chunking-presets") @@ -97,3 +102,102 @@ def test_session_defaults_follow_the_request_language(client: TestClient): "/api/v1/rag/session-defaults", headers={"Accept-Language": "de"} ).json() assert german["prompt"]["params"]["language"] == "en" + + +# ── Preset matching ────────────────────────────────────────────────────────── + + +def _registry(client: TestClient): + """Return the application's component registry.""" + return client.app.container["component_registry"] + + +def _recipe(client: TestClient, key: str) -> dict[str, Any]: + """Return one chunking preset recipe resolved against the registry.""" + presets = chunking_presets.get_chunking_presets(_registry(client)) + return next(preset for preset in presets if preset["key"] == key) + + +def test_every_exact_recipe_matches_its_own_preset(client: TestClient): + registry = _registry(client) + for recipe in chunking_presets.get_chunking_presets(registry): + assert ( + chunking_presets.match_preset_key( + recipe["component"], recipe["params"], registry + ) + == recipe["key"] + ) + + +def test_extra_parameter_makes_the_chunking_config_custom(client: TestClient): + """A stored chunker with a parameter the recipe lacks no longer matches.""" + recipe = _recipe(client, "paragraph") + with_extra = {**recipe["params"], "unexpected_parameter": 1} + + assert ( + chunking_presets.match_preset_key( + recipe["component"], with_extra, _registry(client) + ) + is None + ) + + +def test_missing_parameter_makes_the_chunking_config_custom(client: TestClient): + recipe = _recipe(client, "paragraph") + missing = {k: v for k, v in recipe["params"].items() if k != "chunk_overlap"} + + assert ( + chunking_presets.match_preset_key( + recipe["component"], missing, _registry(client) + ) + is None + ) + + +def test_changed_chunk_size_is_custom_not_the_neighbouring_preset(client: TestClient): + recipe = _recipe(client, "paragraph") + resized = {**recipe["params"], "chunk_size": 501} + + assert ( + chunking_presets.match_preset_key( + recipe["component"], resized, _registry(client) + ) + is None + ) + + +def test_key_order_does_not_change_the_chunking_match(client: TestClient): + recipe = _recipe(client, "page") + reordered = dict(reversed(list(recipe["params"].items()))) + + assert list(reordered) != list(recipe["params"]) + assert ( + chunking_presets.match_preset_key( + recipe["component"], reordered, _registry(client) + ) + == "page" + ) + + +def test_another_chunker_is_never_a_preset(client: TestClient): + recipe = _recipe(client, "paragraph") + + assert ( + chunking_presets.match_preset_key( + "SomeOtherChunker", recipe["params"], _registry(client) + ) + is None + ) + + +def test_malformed_params_raise_even_for_another_chunker(client: TestClient): + """The contract is checked before a non-default component returns early.""" + registry = _registry(client) + with pytest.raises(TypeError): + chunking_presets.match_preset_key( + "SomeOtherChunker", {"chunk_size": (500,)}, registry + ) + with pytest.raises(ValueError, match="non-finite"): + chunking_presets.match_preset_key( + "SomeOtherChunker", {"chunk_size": float("nan")}, registry + ) diff --git a/tests/back/RAG/test_config_equality.py b/tests/back/RAG/test_config_equality.py new file mode 100644 index 000000000..6533b8fea --- /dev/null +++ b/tests/back/RAG/test_config_equality.py @@ -0,0 +1,295 @@ +"""Tests for the RAG configuration equality contract. + +The cases in ``tests/shared/config_equality_cases.json`` are the contract's +examples; the frontend reads the same file. The tests here add what JSON cannot +express: tuples, sets, bytes, non-string keys, non-finite numbers and custom +objects, which must raise rather than compare. +""" + +import json +import math +from pathlib import Path +from typing import Any + +import pytest + +from DashAI.back.services.RAG.config_equality import configs_equal + +CASES_PATH = ( + Path(__file__).resolve().parents[2] / "shared" / "config_equality_cases.json" +) +CASES_KEY = "cases" +NAME_KEY = "name" +LEFT_KEY = "a" +RIGHT_KEY = "b" +IGNORED_KEY = "ignored_keys" +EQUAL_KEY = "equal" + + +MALFORMED_KEY = "malformed_cases" + + +def _load_document() -> dict[str, Any]: + """Return the shared cases document, read relative to this test file.""" + return json.loads(CASES_PATH.read_text(encoding="utf-8")) + + +_DOCUMENT = _load_document() +_CASES = _DOCUMENT[CASES_KEY] +_MALFORMED_CASES = _DOCUMENT[MALFORMED_KEY] + + +class _CustomValue: + """A value outside the contract.""" + + +@pytest.mark.parametrize("case", _CASES, ids=[case[NAME_KEY] for case in _CASES]) +def test_shared_case_matches_expected_result(case: dict[str, Any]): + left, right = case[LEFT_KEY], case[RIGHT_KEY] + ignored = case[IGNORED_KEY] + + assert configs_equal(left, right, ignored) is case[EQUAL_KEY] + + +@pytest.mark.parametrize("case", _CASES, ids=[case[NAME_KEY] for case in _CASES]) +def test_shared_case_is_symmetric(case: dict[str, Any]): + left, right = case[LEFT_KEY], case[RIGHT_KEY] + ignored = case[IGNORED_KEY] + + assert configs_equal(right, left, ignored) is case[EQUAL_KEY] + + +@pytest.mark.parametrize( + "case", _MALFORMED_CASES, ids=[case[NAME_KEY] for case in _MALFORMED_CASES] +) +def test_shared_malformed_case_raises_on_either_side(case: dict[str, Any]): + left, right = case[LEFT_KEY], case[RIGHT_KEY] + ignored = case[IGNORED_KEY] + + with pytest.raises(ValueError, match="safe integer"): + configs_equal(left, right, ignored) + with pytest.raises(ValueError, match="safe integer"): + configs_equal(right, left, ignored) + + +def test_shared_cases_file_covers_the_required_scenarios(): + names = {case[NAME_KEY] for case in _CASES} + assert len(_CASES) >= 40 + assert any("key order" in name for name in names) + assert any("realistic hybrid" in name for name in names) + assert any("realistic chunking" in name for name in names) + assert any("proto key" in name for name in names) + assert any("e-acute" in name for name in names) + assert any("negative zero" in name for name in names) + + +def test_nothing_is_ignored_by_default(): + assert configs_equal({"top_k": 1}, {"top_k": 2}) is False + + +def test_ignored_keys_accept_any_collection_of_strings(): + assert configs_equal({"top_k": 1}, {"top_k": 2}, ("top_k",)) is True + assert configs_equal({"top_k": 1}, {"top_k": 2}, frozenset({"top_k"})) is True + + +def test_inputs_are_not_mutated(): + left = {"top_k": 1, "children": [{"params": {"top_k": 2}}]} + right = {"children": [{"params": {"top_k": 3}}], "top_k": 1} + left_before = json.dumps(left, sort_keys=True) + right_before = json.dumps(right, sort_keys=True) + + assert configs_equal(left, right, ("top_k",)) is True + + assert json.dumps(left, sort_keys=True) == left_before + assert json.dumps(right, sort_keys=True) == right_before + + +@pytest.mark.parametrize( + "value", + [ + (1, 2), + {1, 2}, + frozenset({1}), + b"bytes", + bytearray(b"bytes"), + 1j, + _CustomValue(), + {"nested": (1, 2)}, + [{"nested": {1, 2}}], + ], + ids=[ + "tuple", + "set", + "frozenset", + "bytes", + "bytearray", + "complex", + "custom-object", + "tuple-in-object", + "set-in-array", + ], +) +def test_unsupported_value_raises_type_error_on_either_side(value: Any): + with pytest.raises(TypeError): + configs_equal(value, {"a": 1}) + with pytest.raises(TypeError): + configs_equal({"a": 1}, value) + + +@pytest.mark.parametrize( + "key", + [1, 2.5, None, True, (1, 2)], + ids=["int", "float", "none", "bool", "tuple"], +) +def test_non_string_object_key_raises_type_error(key: Any): + with pytest.raises(TypeError): + configs_equal({key: 1}, {"a": 1}) + with pytest.raises(TypeError): + configs_equal({"a": 1}, {key: 1}) + + +@pytest.mark.parametrize( + "bad", + [math.nan, math.inf, -math.inf], + ids=["nan", "inf", "negative-inf"], +) +def test_non_finite_number_raises_value_error_on_either_side(bad: float): + with pytest.raises(ValueError, match="non-finite"): + configs_equal(bad, 1) + with pytest.raises(ValueError, match="non-finite"): + configs_equal(1, bad) + with pytest.raises(ValueError, match="non-finite"): + configs_equal({"a": [bad]}, {"a": [1]}) + with pytest.raises(ValueError, match="non-finite"): + configs_equal({"a": [1]}, {"a": {"b": bad}}) + + +def test_malformed_value_raises_even_when_the_comparison_would_differ_early(): + """Validation covers both inputs before any comparison can stop early.""" + left = {"a": 0, "z": (1,)} + right = {"a": 1} + + with pytest.raises(TypeError): + configs_equal(left, right) + with pytest.raises(TypeError): + configs_equal(right, left) + + +def test_non_finite_number_raises_even_when_the_key_would_be_ignored(): + with pytest.raises(ValueError, match="non-finite"): + configs_equal({"top_k": math.nan}, {}, ("top_k",)) + + +def test_malformed_value_under_an_ignored_key_still_raises(): + with pytest.raises(TypeError): + configs_equal({"top_k": (1,)}, {}, ("top_k",)) + + +def test_non_string_ignored_key_raises_type_error(): + with pytest.raises(TypeError): + configs_equal({"a": 1}, {"a": 1}, (1,)) + + +def test_string_as_ignored_keys_is_rejected(): + """A bare string would iterate per character; it must not be accepted.""" + with pytest.raises(TypeError): + configs_equal({"top_k": 1}, {"top_k": 2}, "top_k") + + +def test_top_level_list_versus_tuple_raises_type_error(): + with pytest.raises(TypeError): + configs_equal([1, 2], (1, 2)) + + +@pytest.mark.parametrize( + ("left", "right"), + [ + ({"x": {"y": [{"z": True}]}}, {"x": {"y": [{"z": 1}]}}), + ({"x": {"y": [{"z": False}]}}, {"x": {"y": [{"z": 0.0}]}}), + ([[True, {"k": 1}]], [[1, {"k": True}]]), + ({"a": [0, [False]]}, {"a": [False, [0]]}), + ], +) +def test_booleans_never_equal_numbers_inside_nested_containers(left: Any, right: Any): + assert configs_equal(left, right) is False + assert configs_equal(right, left) is False + + +def test_numbers_inside_nested_containers_compare_by_value(): + assert configs_equal({"x": [{"y": [1]}]}, {"x": [{"y": [1.0]}]}) is True + + +def test_none_inside_nested_containers_is_not_an_absent_key(): + assert configs_equal({"x": {"y": None}}, {"x": {}}) is False + assert configs_equal({"x": {"y": None}}, {"x": {"y": None}}) is True + + +#: JavaScript's largest integer that every double represents exactly. +JS_MAX_SAFE_INTEGER = 2**53 - 1 + + +def test_the_module_exposes_the_javascript_safe_integer_bound(): + from DashAI.back.services.RAG.config_equality import MAX_SAFE_INTEGER + + assert MAX_SAFE_INTEGER == JS_MAX_SAFE_INTEGER + + +@pytest.mark.parametrize( + "value", + [JS_MAX_SAFE_INTEGER + 1, -(JS_MAX_SAFE_INTEGER + 1), 2**64], + ids=["just-above", "just-below", "far-above"], +) +def test_integer_beyond_the_javascript_safe_range_raises_value_error(value: int): + with pytest.raises(ValueError, match="safe integer"): + configs_equal(value, value) + with pytest.raises(ValueError, match="safe integer"): + configs_equal({"a": [value]}, {"a": [1]}) + with pytest.raises(ValueError, match="safe integer"): + configs_equal({"a": 1}, {"a": {"b": value}}) + + +def test_unsafe_integer_under_an_ignored_key_still_raises(): + with pytest.raises(ValueError, match="safe integer"): + configs_equal({"top_k": JS_MAX_SAFE_INTEGER + 1}, {}, ("top_k",)) + + +def test_the_safe_range_bounds_are_accepted_and_compared_exactly(): + assert configs_equal(JS_MAX_SAFE_INTEGER, JS_MAX_SAFE_INTEGER) is True + assert configs_equal(-JS_MAX_SAFE_INTEGER, -JS_MAX_SAFE_INTEGER) is True + assert configs_equal(JS_MAX_SAFE_INTEGER, JS_MAX_SAFE_INTEGER - 1) is False + + +@pytest.mark.parametrize( + "value", + [1e20, -1e20, 2.0**53, -(2.0**53), 1.5e300, 2.0**60], + ids=["1e20", "-1e20", "2-pow-53", "-2-pow-53", "1.5e300", "2-pow-60"], +) +def test_integral_float_beyond_the_safe_range_raises_value_error(value: float): + with pytest.raises(ValueError, match="safe integer"): + configs_equal(value, 1) + with pytest.raises(ValueError, match="safe integer"): + configs_equal(1, value) + with pytest.raises(ValueError, match="safe integer"): + configs_equal({"a": [value]}, {"a": [1]}) + with pytest.raises(ValueError, match="safe integer"): + configs_equal({"a": 1}, {"a": {"b": value}}) + + +def test_unsafe_integral_float_under_an_ignored_key_still_raises(): + with pytest.raises(ValueError, match="safe integer"): + configs_equal({"top_k": 1e20}, {}, ("top_k",)) + + +@pytest.mark.parametrize( + "value", + [2.0**53 - 1, -(2.0**53 - 1), 1e15, 0.5, -0.5, 1e-9], + ids=["2-pow-53-minus-1", "-2-pow-53-minus-1", "1e15", "0.5", "-0.5", "1e-9"], +) +def test_float_within_the_safe_range_or_fractional_is_accepted(value: float): + assert configs_equal(value, value) is True + assert configs_equal(value, 1) is False + + +def test_integral_float_within_the_safe_range_equals_its_integer(): + assert configs_equal(1e15, 10**15) is True + assert configs_equal(2.0**53 - 1, 2**53 - 1) is True diff --git a/tests/shared/config_equality_cases.json b/tests/shared/config_equality_cases.json new file mode 100644 index 000000000..9ce50bc48 --- /dev/null +++ b/tests/shared/config_equality_cases.json @@ -0,0 +1,625 @@ +{ + "description": "Shared cases for the RAG configuration equality contract. Each case gives two values a and b, the ignored_keys collection, and whether configs_equal(a, b, ignored_keys) must be true. The backend (DashAI/back/services/RAG/config_equality.py) and the frontend (DashAI/front, mirrored implementation) both read this file, so the cases use only plain JSON values: null, booleans, numbers, strings, arrays and objects with string keys. Values that JSON cannot express (tuples, sets, bytes, NaN, Infinity, custom objects, non-string keys) are tested in the backend only. Numbers beyond the safe range are outside the contract: any number, integer or float, whose value is integral and whose absolute value exceeds 2**53 - 1 is malformed and both the backend and the frontend raise an error for it. Non-integral floats (for example 0.5 or 1e-9) and integral values within the bound are ordinary numbers. The top-level malformed_cases list holds entries of the form {name, a, b, ignored_keys}; each pair must make the comparison raise an error in both argument orders, and no equality expectation is given for them. Object keys are plain strings, so a key named __proto__ is an ordinary key. Strings compare by Unicode code point with no normalization. Equality rules: objects are equal when, after dropping the ignored keys at every object level, they have exactly the same keys and equal values, in any key order; arrays are equal when they have the same length and equal elements in order; booleans never equal numbers; null never equals an absent key; numbers compare by value (1 equals 1.0); strings never equal numbers.", + "cases": [ + { + "name": "flat objects differing only in key order", + "a": {"a": 1, "b": 2}, + "b": {"b": 2, "a": 1}, + "ignored_keys": [], + "equal": true + }, + { + "name": "escaped surrogate pair equals the literal emoji as a value", + "a": "😀", + "b": "😀", + "ignored_keys": [], + "equal": true + }, + { + "name": "escaped surrogate pair equals the literal emoji as a key", + "a": {"😀": 1}, + "b": {"😀": 1}, + "ignored_keys": [], + "equal": true + }, + { + "name": "nested objects differing only in key order", + "a": {"x": {"p": 1, "q": [1, {"m": 1, "n": 2}]}}, + "b": {"x": {"q": [1, {"n": 2, "m": 1}], "p": 1}}, + "ignored_keys": [], + "equal": true + }, + { + "name": "extra key on one side", + "a": {"a": 1}, + "b": {"a": 1, "b": 2}, + "ignored_keys": [], + "equal": false + }, + { + "name": "missing key on one side", + "a": {"a": 1, "b": 2}, + "b": {"b": 2}, + "ignored_keys": [], + "equal": false + }, + { + "name": "extra key nested inside an object", + "a": {"x": {"a": 1}}, + "b": {"x": {"a": 1, "b": null}}, + "ignored_keys": [], + "equal": false + }, + { + "name": "integer zero versus false", + "a": 0, + "b": false, + "ignored_keys": [], + "equal": false + }, + { + "name": "integer one versus true", + "a": 1, + "b": true, + "ignored_keys": [], + "equal": false + }, + { + "name": "float zero versus false", + "a": 0.0, + "b": false, + "ignored_keys": [], + "equal": false + }, + { + "name": "integer one equals float one", + "a": 1, + "b": 1.0, + "ignored_keys": [], + "equal": true + }, + { + "name": "negative zero equals zero by value", + "a": -0.0, + "b": 0, + "ignored_keys": [], + "equal": true + }, + { + "name": "whole float equals its integer", + "a": 1000.0, + "b": 1000, + "ignored_keys": [], + "equal": true + }, + { + "name": "fractional floats compare by value", + "a": 0.1, + "b": 0.1, + "ignored_keys": [], + "equal": true + }, + { + "name": "different numbers", + "a": 0.1, + "b": 0.2, + "ignored_keys": [], + "equal": false + }, + { + "name": "false versus null", + "a": false, + "b": null, + "ignored_keys": [], + "equal": false + }, + { + "name": "null value versus absent key", + "a": {"a": null}, + "b": {}, + "ignored_keys": [], + "equal": false + }, + { + "name": "null versus null", + "a": null, + "b": null, + "ignored_keys": [], + "equal": true + }, + { + "name": "nested null on both sides", + "a": {"a": {"b": null}}, + "b": {"a": {"b": null}}, + "ignored_keys": [], + "equal": true + }, + { + "name": "nested objects with equal values", + "a": {"a": {"b": {"c": [1, 2, {"d": "e"}]}}}, + "b": {"a": {"b": {"c": [1, 2, {"d": "e"}]}}}, + "ignored_keys": [], + "equal": true + }, + { + "name": "nested objects with one changed leaf", + "a": {"a": {"b": {"c": [1, 2, {"d": "e"}]}}}, + "b": {"a": {"b": {"c": [1, 2, {"d": "f"}]}}}, + "ignored_keys": [], + "equal": false + }, + { + "name": "objects inside arrays with reordered keys", + "a": [{"a": 1, "b": 2}], + "b": [{"b": 2, "a": 1}], + "ignored_keys": [], + "equal": true + }, + { + "name": "objects inside arrays with an extra key", + "a": [{"a": 1}], + "b": [{"a": 1, "b": 2}], + "ignored_keys": [], + "equal": false + }, + { + "name": "arrays with different order", + "a": [1, 2], + "b": [2, 1], + "ignored_keys": [], + "equal": false + }, + { + "name": "arrays with different length", + "a": [1, 2], + "b": [1, 2, 3], + "ignored_keys": [], + "equal": false + }, + { + "name": "empty arrays", + "a": [], + "b": [], + "ignored_keys": [], + "equal": true + }, + { + "name": "empty objects", + "a": {}, + "b": {}, + "ignored_keys": [], + "equal": true + }, + { + "name": "empty object versus empty array", + "a": {}, + "b": [], + "ignored_keys": [], + "equal": false + }, + { + "name": "empty object versus null", + "a": {}, + "b": null, + "ignored_keys": [], + "equal": false + }, + { + "name": "empty string versus null", + "a": "", + "b": null, + "ignored_keys": [], + "equal": false + }, + { + "name": "numeric string versus number", + "a": "1", + "b": 1, + "ignored_keys": [], + "equal": false + }, + { + "name": "string zero versus false", + "a": "0", + "b": false, + "ignored_keys": [], + "equal": false + }, + { + "name": "string true versus boolean true", + "a": "true", + "b": true, + "ignored_keys": [], + "equal": false + }, + { + "name": "equal strings", + "a": "abc", + "b": "abc", + "ignored_keys": [], + "equal": true + }, + { + "name": "strings differing in case", + "a": "Keyword", + "b": "keyword", + "ignored_keys": [], + "equal": false + }, + { + "name": "boolean inside a nested list versus zero", + "a": [false], + "b": [0], + "ignored_keys": [], + "equal": false + }, + { + "name": "boolean inside nested objects versus one", + "a": {"a": {"b": [{"c": true}]}}, + "b": {"a": {"b": [{"c": 1}]}}, + "ignored_keys": [], + "equal": false + }, + { + "name": "arrays of arrays with equal contents", + "a": [[1, 2], [3]], + "b": [[1, 2], [3]], + "ignored_keys": [], + "equal": true + }, + { + "name": "arrays of arrays with regrouped contents", + "a": [[1, 2], [3]], + "b": [[1], [2, 3]], + "ignored_keys": [], + "equal": false + }, + { + "name": "ignored top-level key with different values", + "a": {"top_k": 5, "a": 1}, + "b": {"top_k": 3, "a": 1}, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "ignored nested key with different values", + "a": {"x": {"top_k": 5, "a": 1}}, + "b": {"x": {"top_k": 2, "a": 1}}, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "ignored key inside arrays", + "a": {"children": [{"top_k": 5}, {"top_k": 5}]}, + "b": {"children": [{"top_k": 2}, {"top_k": 2}]}, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "ignored key inside nested component references", + "a": { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "children": [ + {"component": "BM25Retriever", "params": {"top_k": 5, "k1": 1.5}} + ] + } + }, + "b": { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "children": [ + {"component": "BM25Retriever", "params": {"top_k": 2, "k1": 1.5}} + ] + } + }, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "ignored key present on one side only", + "a": {"top_k": 5, "a": 1}, + "b": {"a": 1}, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "ignored nested key present on one side only", + "a": {"x": {"top_k": 1}}, + "b": {"x": {}}, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "ignored key with a null value on one side", + "a": {"top_k": null, "a": 1}, + "b": {"a": 1}, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "ignored key on one side and a non-ignored key on the other", + "a": {"top_k": 5}, + "b": {"other": 5}, + "ignored_keys": ["top_k"], + "equal": false + }, + { + "name": "ignored key equal but another key differs", + "a": {"top_k": 5, "a": 1}, + "b": {"top_k": 5, "a": 2}, + "ignored_keys": ["top_k"], + "equal": false + }, + { + "name": "same key with different values when nothing is ignored", + "a": {"top_k": 5}, + "b": {"top_k": 3}, + "ignored_keys": [], + "equal": false + }, + { + "name": "nested ignored key counts when it is not ignored", + "a": {"x": {"top_k": 1}}, + "b": {"x": {}}, + "ignored_keys": [], + "equal": false + }, + { + "name": "ignored key is matched case sensitively", + "a": {"Top_K": 1}, + "b": {"top_k": 1}, + "ignored_keys": ["top_k"], + "equal": false + }, + { + "name": "ignored name that never occurs changes nothing", + "a": {"a": 1}, + "b": {"a": 1}, + "ignored_keys": ["zzz"], + "equal": true + }, + { + "name": "ignored key whose value has a different shape", + "a": {"top_k": [1]}, + "b": {"top_k": {"a": 1}}, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "realistic hybrid recipe with reordered keys and a different top_k", + "a": { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "top_k": 10, + "children": [ + { + "component": "BM25Retriever", + "params": { + "top_k": 5, + "k1": 1.5, + "b": 0.75, + "enable_retrieve_then_expand": false, + "expand_window": 1 + } + }, + { + "component": "DenseRetriever", + "params": { + "top_k": 5, + "enable_retrieve_then_expand": false, + "expand_window": 1, + "embedding_model": { + "component": "SentenceTransformerEmbeddingModel", + "params": {"model_name": "example/embedding", "device": "cpu", "batch_size": 32} + } + } + } + ] + } + }, + "b": { + "params": { + "children": [ + { + "component": "BM25Retriever", + "params": { + "b": 0.75, + "k1": 1.5, + "top_k": 3, + "expand_window": 1, + "enable_retrieve_then_expand": false + } + }, + { + "params": { + "expand_window": 1, + "enable_retrieve_then_expand": false, + "embedding_model": { + "params": {"batch_size": 32, "device": "cpu", "model_name": "example/embedding"}, + "component": "SentenceTransformerEmbeddingModel" + }, + "top_k": 3 + }, + "component": "DenseRetriever" + } + ], + "merge_strategy": "round_robin", + "top_k": 6 + }, + "component": "ParallelRetriever" + }, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "realistic hybrid recipe with expansion enabled on one child", + "a": { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "children": [ + {"component": "BM25Retriever", "params": {"top_k": 5, "enable_retrieve_then_expand": false, "expand_window": 1}}, + {"component": "DenseRetriever", "params": {"top_k": 5, "enable_retrieve_then_expand": false, "expand_window": 1}} + ] + } + }, + "b": { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "children": [ + {"component": "BM25Retriever", "params": {"top_k": 5, "enable_retrieve_then_expand": true, "expand_window": 1}}, + {"component": "DenseRetriever", "params": {"top_k": 5, "enable_retrieve_then_expand": false, "expand_window": 1}} + ] + } + }, + "ignored_keys": ["top_k"], + "equal": false + }, + { + "name": "realistic hybrid recipe with children in a different order", + "a": { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "children": [ + {"component": "BM25Retriever", "params": {"top_k": 5}}, + {"component": "DenseRetriever", "params": {"top_k": 5}} + ] + } + }, + "b": { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "children": [ + {"component": "DenseRetriever", "params": {"top_k": 5}}, + {"component": "BM25Retriever", "params": {"top_k": 5}} + ] + } + }, + "ignored_keys": ["top_k"], + "equal": false + }, + { + "name": "realistic chunking recipe with reordered keys", + "a": {"component": "CharacterChunkModel", "params": {"chunk_size": 500, "chunk_overlap": 50, "length_function": "characters"}}, + "b": {"component": "CharacterChunkModel", "params": {"length_function": "characters", "chunk_overlap": 50, "chunk_size": 500}}, + "ignored_keys": [], + "equal": true + }, + { + "name": "realistic chunking recipe with one extra parameter", + "a": {"component": "CharacterChunkModel", "params": {"chunk_size": 500, "chunk_overlap": 50}}, + "b": {"component": "CharacterChunkModel", "params": {"chunk_size": 500, "chunk_overlap": 50, "length_function": "characters"}}, + "ignored_keys": [], + "equal": false + }, + { + "name": "realistic chunking recipe with a changed chunk size", + "a": {"component": "CharacterChunkModel", "params": {"chunk_size": 500, "chunk_overlap": 50}}, + "b": {"component": "CharacterChunkModel", "params": {"chunk_size": "500", "chunk_overlap": 50}}, + "ignored_keys": [], + "equal": false + }, + { + "name": "proto key with the same value on both sides", + "a": {"__proto__": {"x": 1}}, + "b": {"__proto__": {"x": 1}}, + "ignored_keys": [], + "equal": true + }, + { + "name": "proto key with different values", + "a": {"__proto__": 1}, + "b": {"__proto__": 2}, + "ignored_keys": [], + "equal": false + }, + { + "name": "proto key is not the same as an empty object", + "a": {"__proto__": {}}, + "b": {}, + "ignored_keys": [], + "equal": false + }, + { + "name": "proto key next to an ignored key", + "a": {"__proto__": 1, "top_k": 1}, + "b": {"__proto__": 1, "top_k": 2}, + "ignored_keys": ["top_k"], + "equal": true + }, + { + "name": "precomposed and decomposed e-acute are not equal", + "a": "\u00e9", + "b": "e\u0301", + "ignored_keys": [], + "equal": false + }, + { + "name": "the same decomposed string is equal", + "a": "e\u0301", + "b": "e\u0301", + "ignored_keys": [], + "equal": true + }, + { + "name": "precomposed and decomposed object keys are not equal", + "a": {"\u00e9": 1}, + "b": {"e\u0301": 1}, + "ignored_keys": [], + "equal": false + }, + { + "name": "astral character compared with itself is equal", + "a": "\ud83d\ude00", + "b": "\ud83d\ude00", + "ignored_keys": [], + "equal": true + }, + { + "name": "negative zero float equals integer zero", + "a": -0.0, + "b": 0, + "ignored_keys": [], + "equal": true + } + ], + "malformed_cases": [ + { + "name": "integral float 1e20 is beyond the safe range", + "a": 1e20, + "b": 1e20, + "ignored_keys": [] + }, + { + "name": "negative integral float -1e20 is beyond the safe range", + "a": {"x": -1e20}, + "b": {"x": -1e20}, + "ignored_keys": [] + }, + { + "name": "float 2 to the power 53 is beyond the safe range", + "a": {"x": [9007199254740992.0]}, + "b": {"x": [1]}, + "ignored_keys": [] + }, + { + "name": "integer 2 to the power 53 is beyond the safe range", + "a": 9007199254740992, + "b": 1, + "ignored_keys": [] + }, + { + "name": "unsafe integral float under an ignored key still raises", + "a": {"top_k": 1e20}, + "b": {}, + "ignored_keys": ["top_k"] + } + ] +} From e7b4423928241fd543413441198bb291d0400410 Mon Sep 17 00:00:00 2001 From: sofiachavezb Date: Thu, 26 Nov 2026 14:08:09 -0300 Subject: [PATCH 5/8] fix(front): match RAG presets and detect changes with the shared equality Replace the JSON.stringify comparisons with deepEqual, ignore only top_k when matching retriever presets, and throw on a missing or malformed reference. Shares its test cases with the backend. --- .../generative/RAG/PromptFieldCard.jsx | 8 +- .../generative/RAG/RAGConfigPanel.jsx | 159 ++++++-- .../generative/RAG/RAGConfigPanel.test.jsx | 279 +++++++++++-- .../generative/RAG/configEquality.js | 260 ++++++++++++ .../generative/RAG/configEquality.test.js | 304 ++++++++++++++ .../generative/RAG/presetMatching.js | 114 ++++++ .../generative/RAG/presetMatching.test.js | 383 ++++++++++++++++++ .../QueryTransformationAdvancedModal.jsx | 3 +- 8 files changed, 1447 insertions(+), 63 deletions(-) create mode 100644 DashAI/front/src/components/generative/RAG/configEquality.js create mode 100644 DashAI/front/src/components/generative/RAG/configEquality.test.js create mode 100644 DashAI/front/src/components/generative/RAG/presetMatching.js create mode 100644 DashAI/front/src/components/generative/RAG/presetMatching.test.js diff --git a/DashAI/front/src/components/generative/RAG/PromptFieldCard.jsx b/DashAI/front/src/components/generative/RAG/PromptFieldCard.jsx index f3148860e..acceb4bff 100644 --- a/DashAI/front/src/components/generative/RAG/PromptFieldCard.jsx +++ b/DashAI/front/src/components/generative/RAG/PromptFieldCard.jsx @@ -21,6 +21,7 @@ import PromptTemplateDialog, { PROMPT_DIALOG_MODES, } from "./PromptTemplateDialog"; import usePromptOptions from "./usePromptOptions"; +import { deepEqual } from "./configEquality"; import { getLibraryPrompts } from "../../../api/rag"; import { DEFAULT_PROMPT_LANGUAGE, @@ -42,12 +43,15 @@ const SELECTOR_MIN_WIDTH = 220; /** * Whether two prompt parameter objects carry the same values. * + * Compared with the configuration contract in `configEquality.js`: key order is + * irrelevant, and a boolean never equals a number. + * * @param {object} left - First parameters object. * @param {object} right - Second parameters object. - * @returns {boolean} True when their serialized values match. + * @returns {boolean} True when the two hold the same values. */ function sameParameters(left, right) { - return JSON.stringify(left ?? {}) === JSON.stringify(right ?? {}); + return deepEqual(left ?? {}, right ?? {}); } /** diff --git a/DashAI/front/src/components/generative/RAG/RAGConfigPanel.jsx b/DashAI/front/src/components/generative/RAG/RAGConfigPanel.jsx index 27d70b78a..44e7e18c6 100644 --- a/DashAI/front/src/components/generative/RAG/RAGConfigPanel.jsx +++ b/DashAI/front/src/components/generative/RAG/RAGConfigPanel.jsx @@ -44,6 +44,12 @@ import { updateGenerativeSession } from "../../../api/session"; import { getRequiredDownloads } from "../../../api/component"; import { subscribeAnyDownloadState } from "../../models/model/ComponentDownloadControl"; import { getApiErrorMessage } from "../../../utils/apiError"; +import { NO_IGNORED_KEYS, deepEqual } from "./configEquality"; +import { + RETRIEVER_MATCH_IGNORED_KEYS, + findMatchingPreset, + isPresetReference, +} from "./presetMatching"; /** * Section keys, matching the RAG parameter keys the backend uses, in the order @@ -58,6 +64,71 @@ const SECTIONS = [ "prompt", ]; +/** + * Parameter keys each preset-matched section ignores when comparing its draft + * with a preset recipe. The retriever ignores `top_k`, a slider, so moving it + * keeps the preset. Chunking ignores no keys, so every parameter must match + * exactly. + */ +const PRESET_MATCH_IGNORED_KEYS = { + chunking_model: NO_IGNORED_KEYS, + retriever_model: RETRIEVER_MATCH_IGNORED_KEYS, +}; + +/** + * Whether a draft section is the unfinished reference an advanced dialog leaves + * when the user clears its selection: an empty component with an object + * `params`. No preset matches it. Any other malformed section is not cleared, + * and the preset matcher rejects it. + * + * @param {unknown} value - One section of the draft. + * @returns {boolean} True for a cleared selection. + */ +function isClearedReference(value) { + return ( + value !== null && + typeof value === "object" && + value.component === "" && + value.params !== null && + typeof value.params === "object" && + !Array.isArray(value.params) + ); +} + +/** + * Whether two draft values hold the same configuration. + * + * A draft value is a property of the draft, so `undefined` is absent: it equals + * only another absent value, as it would on the wire. Anything else is decided + * by the configuration contract in `configEquality.js`. + * + * @param {unknown} left - A draft, or one section of it. + * @param {unknown} right - The value to compare it with. + * @returns {boolean} True when the two hold the same configuration. + */ +function sameDraftValue(left, right) { + if (left === undefined || right === undefined) return left === right; + return deepEqual(left, right); +} + +/** + * Return the earlier object while it stays deep-equal to the current value. + * + * An effect that depends on the result re-runs only when the configuration + * really changes, not when an equal object is rebuilt on each render. + * + * @param {unknown} value - A configuration value within the contract. + * @returns {unknown} The stored object while deep-equal to `value`, else `value`. + */ +function useStableConfig(value) { + const [stable, setStable] = useState(value); + if (!deepEqual(stable, value)) { + setStable(value); + return value; + } + return stable; +} + /** * Merge the parameters a save returned into the draft the panel keeps. * @@ -144,6 +215,13 @@ export default function RAGConfigPanel({ // Which section's help modal is open, if any. const [helpSection, setHelpSection] = useState(null); + /** + * Load the session and its resolved configuration into the panel. + * + * The chunking and retriever references are preset-matched, so a session + * without a named reference in either fails the load: the panel does not + * guess a fallback, and the error names the invalid sections. + */ const load = useCallback(async () => { if (!sessionId) return; // A help modal left open belongs to the section of the session being left. @@ -156,18 +234,19 @@ export default function RAGConfigPanel({ getSessionConfiguration(sessionId), ]); const parameters = session.parameters || {}; + const invalidSections = ["chunking_model", "retriever_model"].filter( + (key) => !isPresetReference(parameters[key]), + ); + if (invalidSections.length > 0) { + const names = invalidSections.join(", "); + throw new Error(`RAG session has no valid reference in: ${names}`); + } const next = { - chunking_model: parameters.chunking_model || { - component: "", - params: {}, - }, + chunking_model: parameters.chunking_model, // Null, not `{component: ""}`: the stage is optional and its absent // form is the null the endpoint expects back. query_transformation: parameters.query_transformation ?? null, - retriever_model: parameters.retriever_model || { - component: "", - params: {}, - }, + retriever_model: parameters.retriever_model, prompt: parameters.prompt || { component: "", params: {} }, generation_model: parameters.generation_model || { component: "", @@ -194,8 +273,6 @@ export default function RAGConfigPanel({ load(); }, [load]); - // Preset recipes come resolved from the backend; the Top-K currently in use - // keeps the retriever recipes comparable with what the session already has. useEffect(() => { getChunkingPresets() .then(setChunkingPresets) @@ -229,12 +306,11 @@ export default function RAGConfigPanel({ if (generatorName !== undefined) onGeneratorChange?.(generatorName); }, [generatorName, onGeneratorChange]); - const retrieverKey = JSON.stringify(draft?.retriever_model ?? null); + const retrieverModel = useStableConfig(draft?.retriever_model ?? null); const [missingRetrieverDownloads, setMissingRetrieverDownloads] = useState( [], ); useEffect(() => { - const retrieverModel = JSON.parse(retrieverKey); if (!retrieverModel?.component) { setMissingRetrieverDownloads([]); return undefined; @@ -255,7 +331,7 @@ export default function RAGConfigPanel({ clearTimeout(timer); unsubscribe(); }; - }, [retrieverKey]); + }, [retrieverModel]); const retrieverDownloadMessage = missingRetrieverDownloads.length > 0 ? t("common:componentDownload.mustDownloadNested", { @@ -266,7 +342,7 @@ export default function RAGConfigPanel({ : null; const dirty = useMemo( - () => JSON.stringify(draft) !== JSON.stringify(savedDraft), + () => !sameDraftValue(draft, savedDraft), [draft, savedDraft], ); @@ -276,7 +352,7 @@ export default function RAGConfigPanel({ const dirtySections = useMemo(() => { if (!draft || !savedDraft) return []; return SECTIONS.filter( - (key) => JSON.stringify(draft[key]) !== JSON.stringify(savedDraft[key]), + (key) => !sameDraftValue(draft[key], savedDraft[key]), ); }, [draft, savedDraft]); @@ -305,8 +381,10 @@ export default function RAGConfigPanel({ setDraft((prev) => { const next = { ...prev }; for (const key of SECTIONS) { - const unchangedWhileSaving = - JSON.stringify(prev?.[key]) === JSON.stringify(requestDraft?.[key]); + const unchangedWhileSaving = sameDraftValue( + prev?.[key], + requestDraft?.[key], + ); if (unchangedWhileSaving) next[key] = saved[key]; } return next; @@ -418,23 +496,26 @@ export default function RAGConfigPanel({ /** * The preset recipe the unsaved draft currently matches, if any. * - * Clicking a chip applies that recipe verbatim, so an exact comparison - * against the recipe is enough to keep the panel in step with the draft — no - * waiting for a save round-trip, and no domain knowledge here. + * Clicking a chip applies that recipe verbatim, so comparing the draft with + * the recipe, after dropping the section's ignored keys, keeps the panel in + * step with the draft without waiting for a save round-trip. + * + * A cleared selection (an empty component left by an advanced dialog) is an + * unfinished draft, not a malformed one: no preset matches it, so it yields + * null. Any other malformed reference reaches the matcher, which throws. * * @param {string} key - The configuration section key. * @param {Array} presets - The preset recipes for that section. * @returns {object|null} The matching recipe, or null for a custom config. + * @throws {Error} When the section has no preset match rule. */ const matchedPreset = (key, presets) => { - const ref = draft[key]; - return ( - presets.find( - (preset) => - preset.component === ref?.component && - JSON.stringify(preset.params) === JSON.stringify(ref?.params), - ) ?? null - ); + const ignoredKeys = PRESET_MATCH_IGNORED_KEYS[key]; + if (!ignoredKeys) { + throw new Error(`No preset match rule for section "${key}"`); + } + if (isClearedReference(draft[key])) return null; + return findMatchingPreset(draft[key], presets, ignoredKeys); }; /** @@ -450,13 +531,9 @@ export default function RAGConfigPanel({ }; /** - * One-line description of a section, shown while it is collapsed. - * - * Prefers the preset the *draft* matches so an unsaved change is reflected - * right away; falls back to the backend's resolved answer otherwise. - * - * @param {string} key - The configuration section key. - * @returns {string} The summary line. + * Translated display name of a retriever component. + * @param {string|undefined} component - The retriever component name. + * @returns {string|null} The display name, the raw name as fallback, or null. */ const retrieverDisplayName = (component) => { if (!component) return null; @@ -470,6 +547,15 @@ export default function RAGConfigPanel({ return displayName[i18n.language] || displayName.en || component; }; + /** + * One-line description of a section, shown while it is collapsed. + * + * Prefers the preset the *draft* matches so an unsaved change is reflected + * right away; falls back to the backend's resolved answer otherwise. + * + * @param {string} key - The configuration section key. + * @returns {string} The summary line. + */ const sectionSummary = (key) => { const section = configuration[key]; if (!section) return ""; @@ -488,8 +574,7 @@ export default function RAGConfigPanel({ if (key === "retriever_model") { const ref = draft.retriever_model; - const unchanged = - JSON.stringify(ref) === JSON.stringify(savedDraft?.retriever_model); + const unchanged = sameDraftValue(ref, savedDraft?.retriever_model); const preset = matchedPreset(key, retrieverPresets); const presetLabel = preset?.display_name || diff --git a/DashAI/front/src/components/generative/RAG/RAGConfigPanel.test.jsx b/DashAI/front/src/components/generative/RAG/RAGConfigPanel.test.jsx index cfc68cb8c..c76e299b1 100644 --- a/DashAI/front/src/components/generative/RAG/RAGConfigPanel.test.jsx +++ b/DashAI/front/src/components/generative/RAG/RAGConfigPanel.test.jsx @@ -1,18 +1,14 @@ import React from "react"; -import { screen, waitFor, within } from "@testing-library/react"; +import { fireEvent, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { renderWithProviders } from "../../../test-utils/renderWithProviders"; import RAGConfigPanel from "./RAGConfigPanel"; -// react-markdown ships ESM only and Create React App's jest does not transform -// it; the panel reaches it through the prompt-aware forms. jest.mock("react-markdown", () => ({ __esModule: true, default: ({ children }) => {children}, })); -// One stable object: the panel's loader depends on `enqueueSnackbar`, so a -// fresh reference per render would restart the load on every render. jest.mock("notistack", () => { const snackbar = { enqueueSnackbar: jest.fn() }; return { useSnackbar: () => snackbar }; @@ -37,8 +33,6 @@ jest.mock("../../../api/session", () => ({ jest.mock("../../../pages/generative/RAGSession/retrieverKinds", () => ({ loadRetrieverKinds: jest.fn(), })); -// The generator picker fetches components and download state of its own; the -// panel only cares about the availability it reports back. jest.mock("./GeneratorPicker", () => { const MockGeneratorPicker = () =>
; return MockGeneratorPicker; @@ -53,7 +47,54 @@ jest.mock( jest.mock( "../../../pages/generative/RAGSession/advanced/RetrieverAdvancedModal", () => { - const MockRetrieverAdvancedModal = () => null; + const MockRetrieverAdvancedModal = ({ + open, + retrieverModel, + setRetrieverModel, + }) => { + if (!open) return null; + const setParams = (changes) => + setRetrieverModel({ + ...retrieverModel, + params: { ...retrieverModel.params, ...changes }, + }); + const setChildrenTopK = (topK) => + setRetrieverModel({ + ...retrieverModel, + params: { + ...retrieverModel.params, + children: retrieverModel.params.children.map((child) => ({ + ...child, + params: { ...child.params, top_k: topK }, + })), + }, + }); + return ( +
+ + + + + +
+ ); + }; return MockRetrieverAdvancedModal; }, ); @@ -119,8 +160,6 @@ const CONFIGURATION = { preset_display_name: "Balanced", summary: "400 characters", }, - // What the backend returns for a session with no query transformation: - // the section is always present, disabled. query_transformation: { section_name: "Query Transformation", component: null, @@ -217,8 +256,6 @@ test("saving is offered only once something changed", async () => { test("an edit in a collapsed section is still reported and still saved", async () => { await renderPanel(); - // Change chunking, then open a different section: the change is now - // collapsed, which is exactly when the panel has to keep saying it exists. await userEvent.click(screen.getByText("Fine")); await userEvent.click(screen.getByRole("button", { name: /Model/ })); @@ -231,8 +268,6 @@ test("an edit in a collapsed section is still reported and still saved", async ( await waitFor(() => expect(save).toBeEnabled()); await userEvent.click(save); - // One request carries the whole draft: the endpoint replaces every - // parameter at once, so a per-tab save would be a lie. await waitFor(() => expect(api.updateGenerativeSessionParams).toHaveBeenCalledTimes(1), ); @@ -259,15 +294,122 @@ test("discarding puts every tab back to the saved configuration", async () => { test("every section is mounted, so one never opened still validates", async () => { await renderPanel(); - // The generator reports whether its model can run through a callback. If it - // only mounted once its section was opened, Save would stay enabled for a - // model that cannot answer. expect(screen.getByTestId("generator-picker")).toBeInTheDocument(); }); -// ─── Indexing notices ────────────────────────────────────────────────── -// Indexing now runs up front rather than on the first message, so the panel -// is where its progress and its failures surface. +test("an unsaved Top K change keeps the retriever preset, another option does not", async () => { + const keywordRef = { + component: "BM25Retriever", + params: { + top_k: 5, + vectorizer: "bag_of_words", + enable_retrieve_then_expand: false, + expand_window: 1, + }, + }; + api.getRetrieverPresets.mockResolvedValue([ + { + key: "keyword", + display_name: "Keyword", + description: "BM25", + ...keywordRef, + }, + ]); + api.getRAGSession.mockResolvedValue({ + ...SESSION, + parameters: { ...SESSION.parameters, retriever_model: keywordRef }, + }); + await renderPanel(); + const keywordChip = () => screen.getByRole("button", { name: /^Keyword/ }); + + await userEvent.click(screen.getByRole("button", { name: /Retrieval/ })); + const retrieval = within( + screen.getByRole("heading", { name: /Retrieval/, level: 3 }).parentElement, + ); + await userEvent.click( + retrieval.getByRole("button", { name: /Advanced configuration/ }), + ); + + await userEvent.click( + screen.getByRole("button", { name: "Set chunk count to 9" }), + ); + await waitFor(() => + expect(screen.getByRole("button", { name: /Save/i })).toBeEnabled(), + ); + expect(keywordChip()).toHaveAttribute("aria-pressed", "true"); + + await userEvent.click( + screen.getByRole("button", { name: "Enable expansion" }), + ); + await waitFor(() => + expect(keywordChip()).toHaveAttribute("aria-pressed", "false"), + ); +}); + +test("an unsaved child Top K change keeps the hybrid preset selected", async () => { + const hybridParams = { + top_k: 10, + children: [ + { + component: "BM25Retriever", + params: { top_k: 5, vectorizer: "bag_of_words" }, + }, + { + component: "SemanticRetriever", + params: { top_k: 5, similarity_metric: "cosine" }, + }, + ], + }; + api.getRetrieverPresets.mockResolvedValue([ + { + key: "hybrid", + display_name: "Hybrid", + description: "Keyword and semantic", + component: "HybridRetriever", + params: hybridParams, + }, + ]); + api.getRAGSession.mockResolvedValue({ + ...SESSION, + parameters: { + ...SESSION.parameters, + retriever_model: { + component: "HybridRetriever", + params: JSON.parse(JSON.stringify(hybridParams)), + }, + }, + }); + api.getSessionConfiguration.mockResolvedValue({ + ...CONFIGURATION, + retriever_model: { + ...CONFIGURATION.retriever_model, + component: "HybridRetriever", + display_name: "Hybrid", + preset_key: "hybrid", + preset_display_name: "Hybrid", + top_k: 10, + }, + }); + await renderPanel(); + const hybridChip = () => screen.getByRole("button", { name: /^Hybrid/ }); + + await userEvent.click(screen.getByRole("button", { name: /Retrieval/ })); + expect(hybridChip()).toHaveAttribute("aria-pressed", "true"); + const retrieval = within( + screen.getByRole("heading", { name: /Retrieval/, level: 3 }).parentElement, + ); + await userEvent.click( + retrieval.getByRole("button", { name: /Advanced configuration/ }), + ); + + await userEvent.click( + screen.getByRole("button", { name: "Set child chunk counts to 2" }), + ); + await waitFor(() => + expect(screen.getByRole("button", { name: /Save/i })).toBeEnabled(), + ); + expect(hybridChip()).toHaveAttribute("aria-pressed", "true"); +}); test("a running index shows its progress, using the backend's wording", async () => { await renderPanel({ @@ -278,8 +420,6 @@ test("a running index shows its progress, using the backend's wording", async () }, }); - // Scoped to the notice: the panel also draws a context-budget bar, and a - // bare progressbar query would not tell the two apart. const notice = screen.getByRole("alert"); expect( within(notice).getByText("Indexing the documents…"), @@ -291,7 +431,6 @@ test("a running index shows its progress, using the backend's wording", async () }); test("an index with no progress yet shows an indeterminate bar", async () => { - // A determinate bar sitting at 0% reads as stalled rather than as starting. await renderPanel({ indexStatus: { status: "indexing", @@ -348,3 +487,97 @@ test("a job that finished cleanly raises no alarm", async () => { expect(screen.queryByRole("alert")).not.toBeInTheDocument(); }); + +test.each([ + ["has no retriever_model", { retriever_model: undefined }, "retriever_model"], + [ + "has a retriever_model with no component", + { retriever_model: { component: "", params: {} } }, + "retriever_model", + ], + [ + "has a chunking_model with no params", + { chunking_model: { component: "CharacterChunkModel" } }, + "chunking_model", + ], +])( + "a session that %s shows the load-failed alert instead of the panel", + async (_label, overrides, invalidSection) => { + const consoleError = jest + .spyOn(console, "error") + .mockImplementation(() => {}); + try { + api.getRAGSession.mockResolvedValue({ + ...SESSION, + parameters: { ...SESSION.parameters, ...overrides }, + }); + renderWithProviders(); + + const alert = await screen.findByRole("alert"); + expect( + within(alert).getByText("Failed to load RAG session"), + ).toBeInTheDocument(); + expect( + within(alert).getByRole("button", { name: /Retry/i }), + ).toBeVisible(); + expect( + screen.queryByRole("button", { name: /Retrieval/ }), + ).not.toBeInTheDocument(); + expect(consoleError).toHaveBeenCalledWith( + "Failed to load RAG configuration:", + expect.objectContaining({ + message: expect.stringContaining(invalidSection), + }), + ); + } finally { + consoleError.mockRestore(); + } + }, +); + +/** Opens the retrieval section's advanced dialog, which the mock renders. */ +async function openRetrievalAdvanced() { + await userEvent.click(screen.getByRole("button", { name: /Retrieval/ })); + const retrieval = within( + screen.getByRole("heading", { name: /Retrieval/, level: 3 }).parentElement, + ); + await userEvent.click( + retrieval.getByRole("button", { name: /Advanced configuration/ }), + ); +} + +test("a cleared retriever selection is a custom config, not an error", async () => { + await renderPanel(); + await openRetrievalAdvanced(); + + await userEvent.click( + screen.getByRole("button", { name: "Clear retriever selection" }), + ); + + await waitFor(() => + expect(screen.getByRole("button", { name: /Save/i })).toBeEnabled(), + ); + expect(screen.getByRole("button", { name: /^Keyword/ })).toHaveAttribute( + "aria-pressed", + "false", + ); +}); + +test("a retriever reference with no params is malformed, not a cleared selection", async () => { + const consoleError = jest + .spyOn(console, "error") + .mockImplementation(() => {}); + try { + await renderPanel(); + await openRetrievalAdvanced(); + + const dropParams = screen.getByRole("button", { + name: "Drop retriever params", + }); + expect(() => fireEvent.click(dropParams)).toThrow( + "ref must be a {component, params} object", + ); + } finally { + consoleError.mockRestore(); + } +}); diff --git a/DashAI/front/src/components/generative/RAG/configEquality.js b/DashAI/front/src/components/generative/RAG/configEquality.js new file mode 100644 index 000000000..66b92bcd0 --- /dev/null +++ b/DashAI/front/src/components/generative/RAG/configEquality.js @@ -0,0 +1,260 @@ +/** + * Structural equality for RAG configurations. + * + * Mirrors the backend contract in `DashAI/back/services/RAG/config_equality.py` + * (`configs_equal`). Both implementations read the same examples from + * `tests/shared/config_equality_cases.json`. + * + * Contract + * -------- + * Values: `null`, booleans, finite numbers, strings, arrays, and plain objects + * with string keys. Anything else (functions, symbols, bigints, Date, Map, Set, + * class instances, NaN, Infinity, and `undefined` outside an object property) + * throws an Error. Nothing is silently defaulted. Integral numbers (including + * floats such as 1e20) beyond +/-(2^53-1) are rejected because JavaScript cannot + * represent them exactly; fractional floats are unaffected. + * + * Objects are equal iff, after dropping the ignored keys, they have exactly the + * same keys and equal values. Key order is irrelevant. There are no subsets: an + * extra or a missing key makes two objects different. + * + * Arrays are equal iff they have the same length and are element-wise equal in + * order. + * + * Strict types: a boolean never equals a number (`false` is not `0`, `true` is + * not `1`). `null` never equals an absent key. Numbers compare by value, and `1` + * equals `1.0`; JavaScript cannot tell the two apart, so the contract does not + * either. Strings never equal numbers. + * + * Ignored keys: an explicit array of key names, applied recursively at every + * object level, including objects inside arrays and inside component references' + * `params`. It defaults to none. + * + * `undefined` in JavaScript: an object property whose value is `undefined` is + * treated as absent, because that is what JSON and the wire carry. `undefined` + * anywhere else (the top-level argument, an array element) is malformed and + * throws. + * + * Both inputs are validated completely before anything is compared. A malformed + * value throws even when the comparison would stop earlier, and the result never + * depends on evaluation order. + */ + +/** + * Ignored-key list that ignores nothing: every parameter is compared. + */ +export const NO_IGNORED_KEYS = Object.freeze([]); + +const ROOT_PATH = "$"; + +/** + * Whether a value is a plain object: its prototype is `Object.prototype` or + * `null`. Dates, Maps, Sets and class instances are not plain objects. + * + * @param {unknown} value - The value to inspect. + * @returns {boolean} True for a plain object. + */ +function isPlainObject(value) { + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +/** + * Classify a value into one of the contract categories. Mirrors the + * backend, which rejects integral numbers beyond +/-(2^53-1). Every float at or + * above 2^53 is integral, so the check covers all of them. + * + * @param {unknown} value - The value to classify. + * @param {string} path - Location of the value, used in error messages. + * @returns {"null"|"boolean"|"number"|"string"|"array"|"object"} The category. + * + * @throws {Error} When the value is outside the contract, including + * `undefined`, a non-finite number, or an integral number (including floats + * such as 1e20) beyond +/-(2^53-1). + */ +function kindOf(value, path) { + if (value === null) return "null"; + if (typeof value === "boolean") return "boolean"; + if (typeof value === "number") { + if (!Number.isFinite(value)) { + throw new Error( + `${path}: non-finite number ${value} has no configuration equality`, + ); + } + if (Number.isInteger(value) && !Number.isSafeInteger(value)) { + throw new Error( + `${path}: integer ${value} is outside +/-(2^53-1) and cannot be compared exactly`, + ); + } + return "number"; + } + if (typeof value === "string") return "string"; + if (Array.isArray(value)) return "array"; + if (typeof value === "object" && isPlainObject(value)) return "object"; + const typeName = value === undefined ? "undefined" : typeof value; + throw new Error( + `${path}: unsupported configuration value of type ${typeName}`, + ); +} + +/** + * Check that a value and everything nested in it is within the contract. + * + * Object properties whose value is `undefined` are absent and are skipped. + * Arrays are walked by index, not with forEach: forEach skips holes, and a hole + * reads as `undefined`, which is malformed here. + * + * @param {unknown} value - The value to check. + * @param {string} path - Location of the value, used in error messages. + * @throws {Error} When the value or a nested value is outside the contract. + */ +function validate(value, path) { + const kind = kindOf(value, path); + if (kind === "array") { + for (let index = 0; index < value.length; index += 1) { + validate(value[index], `${path}[${index}]`); + } + return; + } + if (kind === "object") { + if (Object.getOwnPropertySymbols(value).length > 0) { + throw new Error(`${path}: object keys must be strings, not symbols`); + } + for (const key of Object.keys(value)) { + if (value[key] === undefined) continue; + validate(value[key], `${path}.${key}`); + } + } +} + +/** + * Check that a value is within the configuration contract. + * + * Use this to reject malformed input before a comparison that might stop + * early. `deepEqual` runs the same check on both of its arguments. + * + * @param {unknown} value - The value to check. + * @param {string} [name="value"] - How the value is named in the error message. + * @throws {Error} When the value or a nested value is outside the contract. + */ +export function assertConfigurationValue(value, name = "value") { + validate(value, name); +} + +/** + * Check that ignored keys are an array of key names. + * + * @param {unknown} ignoredKeys - The value to check. + * @returns {Set} The key names. + * @throws {Error} When `ignoredKeys` is not an array or holds a non-string. + */ +function ignoredNames(ignoredKeys) { + if (!Array.isArray(ignoredKeys)) { + throw new Error("ignoredKeys must be an array of key names"); + } + for (const name of ignoredKeys) { + if (typeof name !== "string") { + throw new Error(`ignored key names must be strings, got ${typeof name}`); + } + } + return new Set(ignoredKeys); +} + +/** + * The kept entries of a validated object: defined values whose keys are not + * ignored. A Map is used so keys such as `__proto__` are plain data. + * + * @param {object} object - A validated object. + * @param {Set} ignored - Key names to drop at this level. + * @returns {Map} The kept entries. + */ +function keptEntries(object, ignored) { + const kept = new Map(); + for (const key of Object.keys(object)) { + if (ignored.has(key) || object[key] === undefined) continue; + kept.set(key, object[key]); + } + return kept; +} + +/** + * Compare two validated arrays element by element, in order. Walks by index, + * matching `validate`, since validated arrays have no holes. + * + * @param {Array} left - First array. + * @param {Array} right - Second array. + * @param {Set} ignored - Key names ignored inside the elements. + * @returns {boolean} True when the lengths match and every pair is equal. + */ +function sameArray(left, right, ignored) { + if (left.length !== right.length) return false; + for (let index = 0; index < left.length; index += 1) { + if (!sameValue(left[index], right[index], ignored)) return false; + } + return true; +} + +/** + * Compare two validated objects: same kept keys with equal values. + * + * @param {object} left - First object. + * @param {object} right - Second object. + * @param {Set} ignored - Key names dropped at every level. + * @returns {boolean} True when the kept keys are identical and values equal. + */ +function sameObject(left, right, ignored) { + const leftKept = keptEntries(left, ignored); + const rightKept = keptEntries(right, ignored); + if (leftKept.size !== rightKept.size) return false; + for (const [key, item] of leftKept) { + if (!rightKept.has(key)) return false; + if (!sameValue(item, rightKept.get(key), ignored)) return false; + } + return true; +} + +/** + * Compare two validated values. Values of different categories are never + * equal. Both values must already be validated, so `kindOf` never reports a + * path here. + * + * @param {unknown} left - First value, already validated. + * @param {unknown} right - Second value, already validated. + * @param {Set} ignored - Key names dropped at every object level. + * @returns {boolean} True when the values are equal under the contract. + */ +function sameValue(left, right, ignored) { + const kind = kindOf(left, ROOT_PATH); + if (kind !== kindOf(right, ROOT_PATH)) return false; + if (kind === "null") return true; + if (kind === "array") return sameArray(left, right, ignored); + if (kind === "object") return sameObject(left, right, ignored); + return left === right; +} + +/** + * Return whether two RAG configuration values are equal under the contract. + * + * Both arguments are validated completely before anything is compared, so a + * malformed value throws even when the first difference would be found early. + * + * @param {unknown} left - First configuration value. Must be within the + * contract; `undefined` is malformed here. + * @param {unknown} right - Second configuration value, same rules. + * @param {ReadonlyArray} [ignoredKeys=NO_IGNORED_KEYS] - Key names + * dropped at every object level, including objects inside arrays and nested + * component references' params. Must be an array of strings. + * @returns {boolean} True when the two values are equal. + * @throws {Error} When either value is outside the contract (functions, + * symbols, bigints, Date, Map, Set, class instances, NaN, Infinity, an + * integral number (including floats such as 1e20) beyond +/-(2^53-1), or + * `undefined` outside an object property, + * including an array hole), when `ignoredKeys` is not an + * array of strings, or when an object key is a symbol. + */ +export function deepEqual(left, right, ignoredKeys = NO_IGNORED_KEYS) { + const ignored = ignoredNames(ignoredKeys); + validate(left, "left"); + validate(right, "right"); + return sameValue(left, right, ignored); +} diff --git a/DashAI/front/src/components/generative/RAG/configEquality.test.js b/DashAI/front/src/components/generative/RAG/configEquality.test.js new file mode 100644 index 000000000..e78955779 --- /dev/null +++ b/DashAI/front/src/components/generative/RAG/configEquality.test.js @@ -0,0 +1,304 @@ +import fs from "fs"; +import path from "path"; + +import { + NO_IGNORED_KEYS, + assertConfigurationValue, + deepEqual, +} from "./configEquality"; + +const SHARED_CASES_PATH = path.resolve( + __dirname, + "../../../../../../tests/shared/config_equality_cases.json", +); + +const SHARED_DATA = JSON.parse(fs.readFileSync(SHARED_CASES_PATH, "utf8")); +const SHARED_CASES = SHARED_DATA.cases; +const SHARED_MALFORMED_CASES = SHARED_DATA.malformed_cases ?? []; + +describe("shared configuration equality cases", () => { + test("the shared cases file resolves and is not empty", () => { + expect(SHARED_CASES.length).toBeGreaterThan(0); + }); + + test.each(SHARED_CASES.map((c) => [c.name, c]))( + "%s", + (_name, { a, b, ignored_keys: ignoredKeys, equal }) => { + expect(deepEqual(a, b, ignoredKeys)).toBe(equal); + expect(deepEqual(b, a, ignoredKeys)).toBe(equal); + }, + ); + + test("every shared malformed case throws in both argument orders", () => { + for (const { a, b, ignored_keys: ignoredKeys } of SHARED_MALFORMED_CASES) { + expect(() => deepEqual(a, b, ignoredKeys)).toThrow(); + expect(() => deepEqual(b, a, ignoredKeys)).toThrow(); + } + }); +}); + +describe("deepEqual", () => { + test("ignores object key order", () => { + expect( + deepEqual({ a: 1, b: { c: 2, d: 3 } }, { b: { d: 3, c: 2 }, a: 1 }), + ).toBe(true); + }); + + test("compares arrays in order", () => { + expect(deepEqual([1, 2, 3], [1, 2, 3])).toBe(true); + expect(deepEqual([1, 2, 3], [3, 2, 1])).toBe(false); + expect(deepEqual([1, 2], [1, 2, 3])).toBe(false); + }); + + test("compares nested structures", () => { + expect(deepEqual({ x: [{ y: 1 }] }, { x: [{ y: 1 }] })).toBe(true); + expect(deepEqual({ x: [{ y: 1 }] }, { x: [{ y: 2 }] })).toBe(false); + }); + + test("treats a key missing on one side as a difference", () => { + expect(deepEqual({ a: 1, b: 2 }, { a: 1 })).toBe(false); + expect(deepEqual({ a: 1 }, { a: 1, b: 2 })).toBe(false); + }); + + test("treats a key set to undefined the same as an absent key", () => { + expect(deepEqual({ a: 1 }, { a: 1, b: undefined })).toBe(true); + expect(deepEqual({ a: 1, b: undefined }, { a: 1 })).toBe(true); + expect(deepEqual({ a: 1, b: undefined }, { a: 1, c: undefined })).toBe( + true, + ); + }); + + test("treats a nested key set to undefined the same as an absent key", () => { + expect(deepEqual({ x: { y: 1, z: undefined } }, { x: { y: 1 } })).toBe( + true, + ); + expect( + deepEqual( + { children: [{ component: "A", params: { k: undefined } }] }, + { children: [{ component: "A", params: {} }] }, + ), + ).toBe(true); + }); + + test("does not treat null as an absent key", () => { + expect(deepEqual({ a: 1, b: null }, { a: 1 })).toBe(false); + expect(deepEqual({ a: 1 }, { a: 1, b: null })).toBe(false); + expect(deepEqual({ a: null }, { a: undefined })).toBe(false); + }); + + test("compares null and primitives by strict type", () => { + expect(deepEqual(null, null)).toBe(true); + expect(deepEqual(null, {})).toBe(false); + expect(deepEqual({}, null)).toBe(false); + expect(deepEqual(5, 5)).toBe(true); + expect(deepEqual(1, 1.0)).toBe(true); + expect(deepEqual(-0, 0)).toBe(true); + expect(deepEqual(0, false)).toBe(false); + expect(deepEqual(false, null)).toBe(false); + expect(deepEqual("5", 5)).toBe(false); + expect(deepEqual("true", true)).toBe(false); + }); + + test("does not treat an array as an object with index keys", () => { + expect(deepEqual([1], { 0: 1 })).toBe(false); + expect(deepEqual({ 0: 1 }, [1])).toBe(false); + }); + + test("defaults to ignoring no keys", () => { + expect(deepEqual({ top_k: 5 }, { top_k: 3 })).toBe(false); + expect(deepEqual({ top_k: 5 }, { top_k: 3 }, NO_IGNORED_KEYS)).toBe(false); + }); + + test("ignores the given keys at every level, including inside arrays", () => { + const left = { top_k: 5, children: [{ top_k: 1, x: { top_k: 9 } }] }; + const right = { top_k: 2, children: [{ top_k: 7, x: { top_k: 0 } }] }; + expect(deepEqual(left, right, ["top_k"])).toBe(true); + expect(deepEqual(left, right, [])).toBe(false); + }); + + test("does not mutate its arguments", () => { + const left = { a: 1, b: undefined, c: { d: [1, { e: 2 }] } }; + const right = { c: { d: [1, { e: 2 }] }, a: 1 }; + const ignored = ["zzz"]; + deepEqual(left, right, ignored); + expect(Object.keys(left)).toEqual(["a", "b", "c"]); + expect(ignored).toEqual(["zzz"]); + }); + + test("compares a key named __proto__ as ordinary data", () => { + const left = JSON.parse('{"__proto__": 1}'); + expect(deepEqual(left, JSON.parse('{"__proto__": 1}'))).toBe(true); + expect(deepEqual(left, {})).toBe(false); + }); + + test("accepts null-prototype objects as plain objects", () => { + const left = Object.assign(Object.create(null), { a: 1 }); + expect(deepEqual(left, { a: 1 })).toBe(true); + }); +}); + +describe("deepEqual ignoredKeys validation", () => { + test("throws when ignoredKeys is a bare string", () => { + expect(() => deepEqual({ top_k: 1 }, {}, "top_k")).toThrow( + "ignoredKeys must be an array of key names", + ); + }); + + test("throws when ignoredKeys holds a non-string", () => { + expect(() => deepEqual({}, {}, [1])).toThrow( + "ignored key names must be strings", + ); + }); + + test("throws when ignoredKeys is not an array", () => { + expect(() => deepEqual({}, {}, { top_k: true })).toThrow( + "ignoredKeys must be an array of key names", + ); + }); +}); + +describe("deepEqual malformed values", () => { + test.each([ + ["a function", () => 1], + ["a symbol", Symbol("x")], + ["a bigint", BigInt(1)], + ["a Date", new Date(0)], + ["a Map", new Map([["a", 1]])], + ["a Set", new Set([1])], + ["a class instance", new (class Thing {})()], + ["NaN", NaN], + ["Infinity", Infinity], + ["-Infinity", -Infinity], + ["undefined at the top level", undefined], + ])("throws when the left argument is %s", (_label, value) => { + expect(() => deepEqual(value, 1)).toThrow(Error); + }); + + test.each([ + ["a function", () => 1], + ["a symbol", Symbol("x")], + ["a bigint", BigInt(1)], + ["a Date", new Date(0)], + ["NaN", NaN], + ["undefined at the top level", undefined], + ])("throws when the right argument is %s", (_label, value) => { + expect(() => deepEqual(1, value)).toThrow(Error); + }); + + test.each([ + ["a function", () => 1], + ["a Map", new Map()], + ["NaN", NaN], + ["Infinity", Infinity], + ["undefined", undefined], + ])("throws when an array element is %s", (_label, value) => { + expect(() => deepEqual([1, value], [1, 1])).toThrow(Error); + expect(() => deepEqual([1, 1], [1, value])).toThrow(Error); + }); + + test("throws on a malformed value nested in an object", () => { + expect(() => deepEqual({ a: { b: () => 1 } }, { a: { b: 1 } })).toThrow( + "left.a.b", + ); + expect(() => deepEqual({ a: { b: 1 } }, { a: { b: new Date(0) } })).toThrow( + Error, + ); + }); + + test("throws on a malformed value inside an ignored key", () => { + expect(() => + deepEqual({ top_k: () => 1 }, { top_k: 1 }, ["top_k"]), + ).toThrow(Error); + }); + + test("a malformed value throws even when an earlier key already differs", () => { + expect(() => deepEqual({ a: 1, z: () => 1 }, { a: 2, z: 1 }, [])).toThrow( + Error, + ); + expect(() => deepEqual([1, 2, NaN], [3, 2, 1])).toThrow(Error); + }); + + test("an array hole is malformed, on either side, not a skipped element", () => { + const holed = [0, 1]; + delete holed[0]; + expect(() => deepEqual(holed, [2, 1])).toThrow("left[0]"); + expect(() => deepEqual([2, 1], holed)).toThrow("right[0]"); + expect(() => deepEqual({ items: holed }, { items: [2, 1] })).toThrow( + "left.items[0]", + ); + }); + + test("a malformed value throws even when the arrays differ in length", () => { + expect(() => deepEqual([1], [1, () => 1])).toThrow(Error); + }); + + test("an undefined object property counts as absent, on either side", () => { + expect(deepEqual({ a: undefined }, {})).toBe(true); + expect(deepEqual({}, { a: undefined })).toBe(true); + expect(deepEqual({ a: undefined, b: 1 }, { b: 1 })).toBe(true); + }); + + test("an object property holding a function is malformed, not absent", () => { + expect(() => deepEqual({ a: () => 1 }, {})).toThrow(Error); + expect(() => deepEqual({}, { a: () => 1 })).toThrow(Error); + }); + + test("an object with a symbol key is malformed", () => { + const withSymbol = { a: 1, [Symbol("k")]: 1 }; + expect(() => deepEqual(withSymbol, { a: 1 })).toThrow(Error); + }); + + test("a non-plain object inside an object is malformed", () => { + expect(() => deepEqual({ when: new Date(0) }, { when: null })).toThrow( + Error, + ); + }); +}); + +describe("deepEqual integer range", () => { + test("accepts integers up to the safe bound on both sides", () => { + expect(deepEqual(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)).toBe( + true, + ); + expect(deepEqual(-Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER)).toBe( + true, + ); + }); + + test.each([ + ["just above the safe bound", 2 ** 53], + ["far above the safe bound", 2 ** 60], + ["just below the negative bound", -(2 ** 53)], + ])("throws for an integer %s, on either side", (_label, value) => { + expect(() => deepEqual(value, 1)).toThrow("outside +/-(2^53-1)"); + expect(() => deepEqual(1, value)).toThrow("outside +/-(2^53-1)"); + }); + + test("throws for an out-of-range integer nested in a configuration", () => { + expect(() => deepEqual({ a: [2 ** 53] }, { a: [1] })).toThrow("left.a[0]"); + }); + + test("non-integer floats are unaffected by the integer bound", () => { + expect(deepEqual(0.5, 0.5)).toBe(true); + expect(deepEqual(-1.25, -1.25)).toBe(true); + expect(deepEqual(0.1, 0.2)).toBe(false); + }); +}); + +describe("assertConfigurationValue", () => { + test("accepts a valid nested configuration", () => { + expect(() => + assertConfigurationValue({ a: [1, { b: null, c: false }], d: undefined }), + ).not.toThrow(); + }); + + test("names the value in the error message", () => { + expect(() => + assertConfigurationValue({ a: [() => 1] }, "ref.params"), + ).toThrow("ref.params.a[0]"); + }); + + test("throws on undefined at the top level", () => { + expect(() => assertConfigurationValue(undefined)).toThrow(Error); + }); +}); diff --git a/DashAI/front/src/components/generative/RAG/presetMatching.js b/DashAI/front/src/components/generative/RAG/presetMatching.js new file mode 100644 index 000000000..505a97695 --- /dev/null +++ b/DashAI/front/src/components/generative/RAG/presetMatching.js @@ -0,0 +1,114 @@ +import { assertConfigurationValue, deepEqual } from "./configEquality"; + +/** + * Parameter names a retriever preset match ignores, at every level of the + * configuration (composite parents and each child, recursively). + * + * `top_k` is a slider: a composite splits it across its children, so it never + * decides which preset a configuration belongs to. Mirrors the backend's + * `_MATCH_IGNORED_KEYS` in `services/RAG/retriever_presets.py`. + */ +export const RETRIEVER_MATCH_IGNORED_KEYS = Object.freeze(["top_k"]); + +/** + * Whether a value is a non-null, non-array object. + * + * @param {unknown} value - The value to inspect. + * @returns {boolean} True for a plain object-like value. + */ +function isObjectLike(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +/** + * Throw unless the ignored keys are an array. + * + * @param {unknown} ignoredKeys - The value to check. + */ +function assertIgnoredKeys(ignoredKeys) { + if (!Array.isArray(ignoredKeys)) { + throw new Error("ignoredKeys must be an array"); + } +} + +/** + * Whether a value is a usable `{component, params}` recipe reference. + * + * Usable means: a non-null, non-array object whose `component` is a non-empty + * string and whose `params` is a non-null, non-array object. An absent `params` + * is malformed, not an implicit `{}`. Whitespace is not trimmed, so a + * whitespace-only component counts as a non-empty string. + * + * @param {unknown} value - The value to inspect. + * @returns {boolean} True when the value is a usable reference. + */ +export function isPresetReference(value) { + return ( + isObjectLike(value) && + typeof value.component === "string" && + value.component.length > 0 && + isObjectLike(value.params) + ); +} + +/** + * Throw unless the value is a usable `{component, params}` reference. + * + * @param {unknown} value - The value to check. + * @param {string} name - How the value is named in the error message. + * @throws {Error} When the value is not a usable reference. + */ +function assertPresetReference(value, name) { + if (!isPresetReference(value)) { + throw new Error( + `${name} must be a {component, params} object with a non-empty string component and an object params`, + ); + } +} + +/** + * Find the preset recipe a retriever or chunking reference matches. + * + * A match requires the same component and, after stripping `ignoredKeys` from + * both sides, structurally equal params. Any other difference is a custom + * configuration and yields null. + * + * Malformed input is an error, not a custom configuration: `ref` and every + * entry of `presets` must satisfy `isPresetReference`, and every params value + * must be within the configuration contract (see `configEquality.js`). + * + * @param {object} ref - The `{component, params}` reference to classify. Must + * satisfy `isPresetReference`. + * @param {Array} presets - Preset recipes, each `{component, params}` + * satisfying `isPresetReference`. Must be an array. + * @param {ReadonlyArray} ignoredKeys - Keys that never decide a match. + * Required and must be an array: pass NO_IGNORED_KEYS to compare every + * parameter. + * @returns {object|null} The first matching preset, or null for a custom config. + * @throws {Error} When `ignoredKeys` is not an array, when `presets` is not an + * array, when `ref` is not a usable reference, when any preset is not, or + * when a params value is outside the configuration contract. + */ +export function findMatchingPreset(ref, presets, ignoredKeys) { + assertIgnoredKeys(ignoredKeys); + assertPresetReference(ref, "ref"); + if (!Array.isArray(presets)) { + throw new Error("presets must be an array"); + } + presets.forEach((preset, index) => + assertPresetReference(preset, `presets[${index}]`), + ); + + assertConfigurationValue(ref.params, "ref.params"); + presets.forEach((preset, index) => + assertConfigurationValue(preset.params, `presets[${index}].params`), + ); + + return ( + presets.find( + (preset) => + preset.component === ref.component && + deepEqual(preset.params, ref.params, ignoredKeys), + ) ?? null + ); +} diff --git a/DashAI/front/src/components/generative/RAG/presetMatching.test.js b/DashAI/front/src/components/generative/RAG/presetMatching.test.js new file mode 100644 index 000000000..bb2d570f4 --- /dev/null +++ b/DashAI/front/src/components/generative/RAG/presetMatching.test.js @@ -0,0 +1,383 @@ +import { NO_IGNORED_KEYS } from "./configEquality"; +import { + RETRIEVER_MATCH_IGNORED_KEYS, + findMatchingPreset, +} from "./presetMatching"; + +const KEYWORD_PARAMS = { + top_k: 5, + vectorizer: "bag_of_words", + enable_retrieve_then_expand: false, + expand_window: 1, +}; + +const KEYWORD_PRESET = { + key: "keyword", + component: "BM25Retriever", + params: KEYWORD_PARAMS, +}; + +const SEMANTIC_PRESET = { + key: "semantic", + component: "SemanticRetriever", + params: { top_k: 5, batch_size: 32 }, +}; + +/** A hybrid recipe: parent top_k plus two children, each with its own top_k. */ +function hybridParams({ + parentTopK = 10, + keywordTopK = 5, + semanticTopK = 5, + metric = "cosine", +} = {}) { + return { + top_k: parentTopK, + children: [ + { + component: "BM25Retriever", + params: { top_k: keywordTopK, vectorizer: "bag_of_words" }, + }, + { + component: "SemanticRetriever", + params: { top_k: semanticTopK, similarity_metric: metric }, + }, + ], + }; +} + +const HYBRID_PRESET = { + key: "hybrid", + component: "HybridRetriever", + params: hybridParams(), +}; + +const ALL_PRESETS = [KEYWORD_PRESET, SEMANTIC_PRESET, HYBRID_PRESET]; + +describe("findMatchingPreset", () => { + test("matches the same params in a different key order", () => { + const ref = { + component: "BM25Retriever", + params: { + expand_window: 1, + enable_retrieve_then_expand: false, + vectorizer: "bag_of_words", + top_k: 5, + }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBe(KEYWORD_PRESET); + }); + + test("still matches when only top_k differs on a flat retriever", () => { + const ref = { + component: "BM25Retriever", + params: { ...KEYWORD_PARAMS, top_k: 12 }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBe(KEYWORD_PRESET); + }); + + test("still matches a hybrid whose parent and child top_k differ", () => { + const ref = { + component: "HybridRetriever", + params: hybridParams({ + parentTopK: 20, + keywordTopK: 1, + semanticTopK: 19, + }), + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBe(HYBRID_PRESET); + }); + + test("does not match a hybrid whose children are in a different order", () => { + const params = hybridParams(); + const reordered = { + ...params, + children: [...params.children].reverse(), + }; + expect( + findMatchingPreset( + { component: "HybridRetriever", params: reordered }, + ALL_PRESETS, + RETRIEVER_MATCH_IGNORED_KEYS, + ), + ).toBeNull(); + }); + + test("does not match when a child's similarity metric changes", () => { + const ref = { + component: "HybridRetriever", + params: hybridParams({ metric: "dot" }), + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBeNull(); + }); + + test("does not match when a child's component changes", () => { + const params = hybridParams(); + params.children[1].component = "BM25Retriever"; + expect( + findMatchingPreset( + { component: "HybridRetriever", params }, + ALL_PRESETS, + RETRIEVER_MATCH_IGNORED_KEYS, + ), + ).toBeNull(); + }); + + test("does not match when a child reference has an extra key", () => { + const params = hybridParams(); + params.children[0].extra = true; + expect( + findMatchingPreset( + { component: "HybridRetriever", params }, + ALL_PRESETS, + RETRIEVER_MATCH_IGNORED_KEYS, + ), + ).toBeNull(); + }); + + test("matches when a key is set to undefined in place of being absent", () => { + const ref = { + component: "SemanticRetriever", + params: { top_k: 5, batch_size: 32, extra: undefined }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBe(SEMANTIC_PRESET); + }); + + test("matches a nested child key set to undefined", () => { + const params = hybridParams(); + params.children[0].params.extra = undefined; + expect( + findMatchingPreset( + { component: "HybridRetriever", params }, + ALL_PRESETS, + RETRIEVER_MATCH_IGNORED_KEYS, + ), + ).toBe(HYBRID_PRESET); + }); + + test("does not match when a param is null where the preset omits it", () => { + const ref = { + component: "SemanticRetriever", + params: { top_k: 5, batch_size: 32, extra: null }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBeNull(); + }); + + test("throws a clear error when ignoredKeys is omitted", () => { + expect(() => + findMatchingPreset( + { component: "BM25Retriever", params: {} }, + ALL_PRESETS, + ), + ).toThrow("ignoredKeys must be an array"); + }); + + test("does not match when enable_retrieve_then_expand changes", () => { + const ref = { + component: "BM25Retriever", + params: { ...KEYWORD_PARAMS, enable_retrieve_then_expand: true }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBeNull(); + }); + + test("does not match when expand_window changes", () => { + const ref = { + component: "BM25Retriever", + params: { ...KEYWORD_PARAMS, expand_window: 2 }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBeNull(); + }); + + test("does not match when batch_size changes", () => { + const ref = { + component: "SemanticRetriever", + params: { top_k: 5, batch_size: 64 }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBeNull(); + }); + + test("does not match when a key is missing on one side", () => { + const { expand_window: _dropped, ...withoutWindow } = KEYWORD_PARAMS; + const ref = { component: "BM25Retriever", params: withoutWindow }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBeNull(); + }); + + test("does not match a different component with identical params", () => { + const ref = { + component: "SemanticRetriever", + params: { ...KEYWORD_PARAMS }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBeNull(); + }); + + test("compares every parameter when no keys are ignored", () => { + const ref = { + component: "BM25Retriever", + params: { ...KEYWORD_PARAMS, top_k: 12 }, + }; + expect( + findMatchingPreset(ref, [KEYWORD_PRESET], NO_IGNORED_KEYS), + ).toBeNull(); + }); + + test("does not mutate the reference or the presets", () => { + const ref = { + component: "HybridRetriever", + params: hybridParams({ parentTopK: 20 }), + }; + const refSnapshot = JSON.parse(JSON.stringify(ref)); + const presetsSnapshot = JSON.parse(JSON.stringify(ALL_PRESETS)); + + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS); + + expect(ref).toEqual(refSnapshot); + expect(ALL_PRESETS).toEqual(presetsSnapshot); + }); +}); + +describe("findMatchingPreset params comparison", () => { + test("a boolean parameter does not match a numeric one", () => { + const ref = { + component: "BM25Retriever", + params: { ...KEYWORD_PARAMS, enable_retrieve_then_expand: 0 }, + }; + expect( + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toBeNull(); + }); + + test("a malformed param value throws even when the component is unknown", () => { + const ref = { + component: "Unknown", + params: { top_k: 5, custom: () => 1 }, + }; + expect(() => + findMatchingPreset(ref, ALL_PRESETS, RETRIEVER_MATCH_IGNORED_KEYS), + ).toThrow(Error); + }); + + test("a malformed preset param throws even when its component differs", () => { + const presets = [ + { key: "bad", component: "Other", params: { value: NaN } }, + ]; + expect(() => + findMatchingPreset( + { component: "BM25Retriever", params: { top_k: 5 } }, + presets, + RETRIEVER_MATCH_IGNORED_KEYS, + ), + ).toThrow(Error); + }); +}); + +describe("findMatchingPreset input validation", () => { + const REF_ERROR = "must be a {component, params} object"; + const validRef = { component: "BM25Retriever", params: { top_k: 5 } }; + const match = (ref, presets = ALL_PRESETS) => + findMatchingPreset(ref, presets, RETRIEVER_MATCH_IGNORED_KEYS); + + test.each([ + ["null", null], + ["undefined", undefined], + ["a string", "BM25Retriever"], + ["an array", [validRef]], + ])("throws when ref is %s", (_label, ref) => { + expect(() => match(ref)).toThrow(REF_ERROR); + }); + + test("throws when ref has no component", () => { + expect(() => match({ params: { top_k: 5 } })).toThrow(REF_ERROR); + }); + + test("throws when ref has an empty component", () => { + expect(() => match({ component: "", params: { top_k: 5 } })).toThrow( + REF_ERROR, + ); + }); + + test.each([ + ["a number", 42], + ["null", null], + ["an object", { name: "BM25Retriever" }], + ])("throws when ref component is %s", (_label, component) => { + expect(() => match({ component, params: { top_k: 5 } })).toThrow(REF_ERROR); + }); + + test("throws when ref has no params, rather than treating it as empty", () => { + expect(() => match({ component: "BM25Retriever" })).toThrow(REF_ERROR); + }); + + test.each([ + ["a string", "top_k"], + ["an array", [5]], + ["null", null], + ["a number", 5], + ])("throws when ref params is %s", (_label, params) => { + expect(() => match({ component: "BM25Retriever", params })).toThrow( + REF_ERROR, + ); + }); + + test("throws when the presets are not an array", () => { + expect(() => + findMatchingPreset(validRef, undefined, RETRIEVER_MATCH_IGNORED_KEYS), + ).toThrow("presets must be an array"); + }); + + test("throws when a preset has no component", () => { + const presets = [{ key: "bad", params: { top_k: 5 } }]; + expect(() => match(validRef, presets)).toThrow("presets[0] must be a"); + }); + + test("throws when a preset has an empty component", () => { + const presets = [KEYWORD_PRESET, { key: "bad", component: "", params: {} }]; + expect(() => match(validRef, presets)).toThrow("presets[1] must be a"); + }); + + test("throws when a preset has no params", () => { + const presets = [{ key: "bad", component: "BM25Retriever" }]; + expect(() => match(validRef, presets)).toThrow("presets[0] must be a"); + }); + + test("throws when a preset has non-object params", () => { + const presets = [{ key: "bad", component: "BM25Retriever", params: "x" }]; + expect(() => match(validRef, presets)).toThrow("presets[0] must be a"); + }); + + test("throws when a preset entry is not an object", () => { + expect(() => match(validRef, [null])).toThrow("presets[0] must be a"); + }); + + test("a malformed preset throws even when an earlier preset matches", () => { + const presets = [KEYWORD_PRESET, { key: "bad", component: 7, params: {} }]; + expect(() => + match({ ...validRef, params: KEYWORD_PARAMS }, presets), + ).toThrow("presets[1] must be a"); + }); + + test("a valid reference with no matching preset still returns null", () => { + expect(match({ component: "Unknown", params: {} })).toBeNull(); + expect(match(validRef, [])).toBeNull(); + }); +}); diff --git a/DashAI/front/src/pages/generative/RAGSession/advanced/QueryTransformationAdvancedModal.jsx b/DashAI/front/src/pages/generative/RAGSession/advanced/QueryTransformationAdvancedModal.jsx index 642af152e..f1198e89e 100644 --- a/DashAI/front/src/pages/generative/RAGSession/advanced/QueryTransformationAdvancedModal.jsx +++ b/DashAI/front/src/pages/generative/RAGSession/advanced/QueryTransformationAdvancedModal.jsx @@ -3,6 +3,7 @@ import PropTypes from "prop-types"; import { Button, MenuItem, Stack, TextField, Typography } from "@mui/material"; import { useTranslation } from "react-i18next"; import { resolveLabel } from "../../../../components/generative/RAG/QueryTransformationPicker"; +import { deepEqual } from "../../../../components/generative/RAG/configEquality"; import FormSchema from "../../../../components/shared/FormSchema"; import FormSchemaWithPrompts from "../../../../components/generative/RAG/FormSchemaWithPrompts"; import FormSchemaContainer from "../../../../components/shared/FormSchemaContainer"; @@ -51,7 +52,7 @@ function llmParamsToPersist(carriedParams, seedDefaults, values) { const wasCarried = Object.prototype.hasOwnProperty.call(carried, key); const isUntouchedDefault = - JSON.stringify(value) === JSON.stringify(seed[key]); + seed[key] !== undefined && deepEqual(value, seed[key]); if (!wasCarried && isUntouchedDefault) continue; result[key] = value; From 123612156379cfd24cf01002f73064d920a79dc3 Mon Sep 17 00:00:00 2001 From: sofiachavezb Date: Thu, 26 Nov 2026 14:08:26 -0300 Subject: [PATCH 6/8] fix(rag): ignore the embedding device in the persistence signature device joins batch_size as a non-persistent parameter of text embedding converters, so changing it neither reindexes nor creates another embedding model row. --- .../hugging_face/text_embedding/base.py | 10 +- tests/back/RAG/test_retriever_identity.py | 172 ++++++++++++++++++ 2 files changed, 178 insertions(+), 4 deletions(-) diff --git a/DashAI/back/converters/hugging_face/text_embedding/base.py b/DashAI/back/converters/hugging_face/text_embedding/base.py index 2a409c42c..4429c53f1 100644 --- a/DashAI/back/converters/hugging_face/text_embedding/base.py +++ b/DashAI/back/converters/hugging_face/text_embedding/base.py @@ -37,6 +37,8 @@ AGGREGATE = "aggregate" #: Schema param name of the number of texts encoded together. BATCH_SIZE_FIELD = "batch_size" +#: Schema param name of the device the checkpoint runs on. +DEVICE_FIELD = "device" SPECIAL_TOKENS = 2 #: Keeps a vector of zeros from dividing by zero while normalizing. NORMALIZATION_EPSILON = 1e-12 @@ -246,10 +248,10 @@ class TextEmbeddingConverter(AdvancedPreprocessingConverter, PretrainedTool): HF_IGNORE_PATTERNS = [*HFDownloadableMixin.HF_IGNORE_PATTERNS, "pytorch_model.bin"] QUERY_PROMPT: Optional[str] = None PASSAGE_PROMPT: Optional[str] = None - #: The batch size only trades memory for speed and never changes the vectors, - #: so it stays out of the persistence signature of any retriever that embeds - #: with this converter. - NON_PERSISTENT_PARAMS = (BATCH_SIZE_FIELD,) + #: The batch size and the device only trade memory and speed for hardware + #: and never change the vectors, so they stay out of the persistence + #: signature of any retriever that embeds with this converter. + NON_PERSISTENT_PARAMS = (BATCH_SIZE_FIELD, DEVICE_FIELD) def close(self) -> None: """Release the loaded checkpoint so the next ``encode`` reloads it. diff --git a/tests/back/RAG/test_retriever_identity.py b/tests/back/RAG/test_retriever_identity.py index 44e7e8e00..62b01c85e 100644 --- a/tests/back/RAG/test_retriever_identity.py +++ b/tests/back/RAG/test_retriever_identity.py @@ -19,6 +19,10 @@ import pytest from fastapi.testclient import TestClient +from DashAI.back.converters.hugging_face.text_embedding.base import ( + BATCH_SIZE_FIELD, + DEVICE_FIELD, +) from DashAI.back.converters.hugging_face.text_embedding.e5_mistral_gguf import ( E5MistralGGUFEmbedding, ) @@ -636,6 +640,28 @@ def test_a_different_batch_size_makes_the_semantic_config_custom(client: TestCli ) +def test_a_different_device_makes_the_semantic_config_custom(client: TestClient): + """The preset match is strict on the device: another device is a custom config.""" + preset = _preset(client, retriever_presets.SEMANTIC_PRESET_KEY) + recipe_device = preset["params"]["embedding_model"]["params"][DEVICE_FIELD] + + assert recipe_device != _GPU_DEVICE + assert ( + retriever_presets.match_preset_key( + preset["component"], preset["params"], _registry(client) + ) + == retriever_presets.SEMANTIC_PRESET_KEY + ) + assert ( + retriever_presets.match_preset_key( + preset["component"], + _with_device(preset["params"], _GPU_DEVICE), + _registry(client), + ) + is None + ) + + @pytest.mark.parametrize( "children", [ @@ -1021,6 +1047,8 @@ def test_changing_the_distance_metric_does_not_delete_a_unit_retriever( "overflow_strategy": "truncate", } _EMBEDDING_REGISTRY = {"AllMiniLML6V2Embedding": {"class": AllMiniLML6V2Embedding}} +#: A device other than the CPU label, used to show the device never keys a row. +_GPU_DEVICE = "cuda:0" def _dense_params(embedding_params: Dict[str, Any]) -> Dict[str, Any]: @@ -1216,6 +1244,150 @@ def test_changing_the_normalization_does_delete_a_dense_retriever(client: TestCl assert db.get(RAGRetriever, bridge.id) is None +# ── Embedding device ───────────────────────────────────────────────────────── + + +def _with_device(params: Dict[str, Any], device: str) -> Dict[str, Any]: + """Return a configuration whose embedding model runs on *device*.""" + embedding = params["embedding_model"] + return { + **params, + "embedding_model": { + **embedding, + "params": {**embedding["params"], DEVICE_FIELD: device}, + }, + } + + +def _embedding_service(db) -> RetrieverSetupService: + """Return a setup service whose registry knows the MiniLM embedding class.""" + return RetrieverSetupService( + db=db, + registry=_EMBEDDING_REGISTRY, + env_RAG_path="rag-root", + chunks={}, + chunk_set_id=7, + pipeline_id=1, + chunking_key="test-chunking", + ) + + +@pytest.mark.parametrize( + "embedding_class", + [AllMiniLML6V2Embedding, DistilBERTEmbedding, E5MistralGGUFEmbedding], +) +def test_device_is_left_out_of_every_embedding_signature(embedding_class): + """The device only picks hardware, so every embedding converter ignores it.""" + cpu = persistence_signature(embedding_class, {DEVICE_FIELD: "cpu"}, {}) + gpu = persistence_signature(embedding_class, {DEVICE_FIELD: _GPU_DEVICE}, {}) + + assert cpu == gpu == {} + + +def test_device_does_not_change_the_dense_signature(): + """A device change keeps the dense identity; the normalization control differs.""" + cpu = _dense_params(_EMBEDDING_PARAMS) + gpu = _dense_params({**_EMBEDDING_PARAMS, DEVICE_FIELD: _GPU_DEVICE}) + unnormalized = _dense_params({**_EMBEDDING_PARAMS, "normalize": False}) + + signature = persistence_signature(DenseEmbeddingRetriever, gpu, _EMBEDDING_REGISTRY) + + assert DEVICE_FIELD not in signature["embedding_model"]["params"] + assert signature == persistence_signature( + DenseEmbeddingRetriever, cpu, _EMBEDDING_REGISTRY + ) + assert signature != persistence_signature( + DenseEmbeddingRetriever, unnormalized, _EMBEDDING_REGISTRY + ) + + +def test_device_resolves_to_the_same_embedding_model_row(orm_db): + """A device change keeps the stored row, so documents are not embedded again.""" + service = _embedding_service(orm_db) + cpu = service._build_dense_persistence_for(_dense_params(_EMBEDDING_PARAMS)) + gpu = service._build_dense_persistence_for( + _dense_params({**_EMBEDDING_PARAMS, DEVICE_FIELD: _GPU_DEVICE}) + ) + unnormalized = service._build_dense_persistence_for( + _dense_params({**_EMBEDDING_PARAMS, "normalize": False}) + ) + + assert gpu.embedding_model_id == cpu.embedding_model_id + assert unnormalized.embedding_model_id != cpu.embedding_model_id + + +def test_persisted_embedding_row_leaves_out_the_query_time_params(orm_db): + """The stored row keeps the vector-shaping options and drops batch and device.""" + service = _embedding_service(orm_db) + persistence = service._build_dense_persistence_for( + _dense_params( + {**_EMBEDDING_PARAMS, BATCH_SIZE_FIELD: 8, DEVICE_FIELD: _GPU_DEVICE} + ) + ) + row = orm_db.get(RAGEmbeddingModel, persistence.embedding_model_id) + vector_params = { + name: value + for name, value in _EMBEDDING_PARAMS.items() + if name not in (BATCH_SIZE_FIELD, DEVICE_FIELD) + } + + assert BATCH_SIZE_FIELD not in row.parameters + assert DEVICE_FIELD not in row.parameters + assert row.parameters == vector_params + + +def test_legacy_embedding_row_with_query_time_params_is_not_reused(orm_db): + """A row stored with batch size and device misses the cache and stays in place.""" + legacy = RAGEmbeddingModel( + class_name="AllMiniLML6V2Embedding", parameters=dict(_EMBEDDING_PARAMS) + ) + orm_db.add(legacy) + orm_db.commit() + service = _embedding_service(orm_db) + + first = service._build_dense_persistence_for(_dense_params(_EMBEDDING_PARAMS)) + second = service._build_dense_persistence_for(_dense_params(_EMBEDDING_PARAMS)) + + created = orm_db.get(RAGEmbeddingModel, first.embedding_model_id) + assert first.embedding_model_id != legacy.id + assert BATCH_SIZE_FIELD not in created.parameters + assert DEVICE_FIELD not in created.parameters + assert orm_db.get(RAGEmbeddingModel, legacy.id) is not None + assert second.embedding_model_id == first.embedding_model_id + + +def test_changing_the_device_does_not_delete_a_dense_retriever(client: TestClient): + """A device change keeps the fitted dense retriever and its embeddings.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session_id = _insert_rag_session( + db, f"identity_device_{uuid.uuid4().hex[:6]}" + ).id + params = _dense_params(_EMBEDDING_PARAMS) + bridge, detail = _dense_retriever_state(db, session_id, params) + old_parameters = { + "documents": [], + "retriever_model": { + "component": "DenseEmbeddingRetriever", + "params": params, + }, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": "DenseEmbeddingRetriever", + "params": _with_device(params, _GPU_DEVICE), + }, + } + + CleanupService(db, _registry(client)).cleanup_orphaned_resources( + session_id, old_parameters, new_parameters + ) + + assert db.get(RAGRetriever, bridge.id) is not None + assert db.get(RAGDenseRetriever, detail.id) is not None + + # ── Composite and nested signatures ────────────────────────────────────────── _COMPOSITE_REGISTRY = { From 1aedb063204f0fc19b336f8bbf5f8d00eea5ccb5 Mon Sep 17 00:00:00 2001 From: sofiachavezb Date: Thu, 26 Nov 2026 14:08:28 -0300 Subject: [PATCH 7/8] feat(rag): clean unused index data after a reindex After a successful index job, delete the chunk sets, retriever rows, embedding models, matrices and sparse folders no session uses, walking the retriever tree from parents to children. Chat turns clean only when the index footprint changed. Storage directory names move to storage_layout. --- DashAI/back/api/api_v1/endpoints/rag.py | 10 +- DashAI/back/job/RAG_index_job.py | 25 +- DashAI/back/job/RAG_job.py | 684 +++++-- DashAI/back/services/RAG/chunking_service.py | 3 +- DashAI/back/services/RAG/cleanup_service.py | 1815 ++++++++++++++--- .../services/RAG/embedding_storage_service.py | 2 +- .../back/services/RAG/retriever_db_service.py | 76 + .../services/RAG/retriever_setup_service.py | 58 +- .../RAG/session_configuration_service.py | 161 +- DashAI/back/services/RAG/session_params.py | 35 + DashAI/back/services/RAG/storage_layout.py | 14 + .../RAG/test_RAG_session_configuration_api.py | 50 +- tests/back/RAG/test_bridge_tree_cleanup.py | 649 ++++++ tests/back/RAG/test_cleanup_session_scope.py | 32 +- tests/back/RAG/test_index_cleanup.py | 1416 +++++++++++++ .../test_session_configuration_references.py | 77 + 16 files changed, 4562 insertions(+), 545 deletions(-) create mode 100644 DashAI/back/services/RAG/session_params.py create mode 100644 DashAI/back/services/RAG/storage_layout.py create mode 100644 tests/back/RAG/test_bridge_tree_cleanup.py create mode 100644 tests/back/RAG/test_index_cleanup.py create mode 100644 tests/back/RAG/test_session_configuration_references.py diff --git a/DashAI/back/api/api_v1/endpoints/rag.py b/DashAI/back/api/api_v1/endpoints/rag.py index c17f83ce3..73f0c51b1 100644 --- a/DashAI/back/api/api_v1/endpoints/rag.py +++ b/DashAI/back/api/api_v1/endpoints/rag.py @@ -31,6 +31,7 @@ get_retriever_presets as resolve_retriever_presets, ) from DashAI.back.services.RAG.session_configuration_service import ( + RAGSessionNotFoundError, SessionConfigurationService, ) from DashAI.back.services.RAG.session_defaults_service import build_default_parameters @@ -165,17 +166,22 @@ def session_configuration( Raises ------ HTTPException - 404 if the session does not exist. + 404 if the session does not exist, 422 if its stored configuration is + malformed. """ with session_factory() as db: try: configuration = SessionConfigurationService( db, component_registry ).get_configuration(session_id) - except ValueError as e: + except RAGSessionNotFoundError as e: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=str(e) ) from e + except ValueError as e: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e) + ) from e return localize(configuration, accept_language) diff --git a/DashAI/back/job/RAG_index_job.py b/DashAI/back/job/RAG_index_job.py index bd2a1a53c..a3616928f 100644 --- a/DashAI/back/job/RAG_index_job.py +++ b/DashAI/back/job/RAG_index_job.py @@ -17,7 +17,9 @@ from DashAI.back.job.base_job import BaseJob, JobError from DashAI.back.models.RAG.RAG_constants import RAG_PARAM_KEYS as _RAG_PARAM_KEYS from DashAI.back.models.RAG.RAG_pipeline import RAGPipelineConfig +from DashAI.back.services.RAG.cleanup_service import run_post_index_cleanup from DashAI.back.services.RAG.prompt_service import PromptService +from DashAI.back.services.RAG.session_params import filter_pipeline_params from DashAI.back.services.RAG.session_validation_service import ( SessionValidationService, ) @@ -106,9 +108,7 @@ def run(self) -> Dict[str, int]: session_id, dict(session.parameters or {}), ) - clean_params = { - k: v for k, v in raw_params.items() if k in _RAG_PARAM_KEYS - } + clean_params = filter_pipeline_params(raw_params, _RAG_PARAM_KEYS) if not (clean_params.get("documents") or []): raise JobError(f"Session {session_id} has no documents to index.") @@ -135,15 +135,26 @@ def run(self) -> Dict[str, int]: pipeline_config, progress=self.report_progress, ) + # Captured before the cleanup, which may roll the session back. + chunk_set_id = result.chunk_set_id + total_chunks = result.total_chunks + root_bridge_id = result.retriever.db_record_id + run_post_index_cleanup( + db, + component_registry, + session_id, + root_bridge_id, + config["RAG_PATH"], + ) log.debug( "Indexed session %d: chunk set %d, %d chunks", session_id, - result.chunk_set_id, - result.total_chunks, + chunk_set_id, + total_chunks, ) return { - "chunk_set_id": result.chunk_set_id, - "total_chunks": result.total_chunks, + "chunk_set_id": chunk_set_id, + "total_chunks": total_chunks, } except JobError: self.set_status_as_error() diff --git a/DashAI/back/job/RAG_job.py b/DashAI/back/job/RAG_job.py index 8a1672dc1..9ca5121a4 100644 --- a/DashAI/back/job/RAG_job.py +++ b/DashAI/back/job/RAG_job.py @@ -1,9 +1,12 @@ import gc import logging +from collections.abc import Iterable, Mapping +from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict from kink import di, inject from sqlalchemy import exc +from sqlalchemy.orm import Session from DashAI.back.core.enums.status import RunStatus from DashAI.back.dependencies.database.models import ( @@ -23,12 +26,27 @@ RAGPipeline, RAGPipelineConfig, ) +from DashAI.back.services.RAG.cleanup_service import ( + IndexFootprint, + capture_index_footprint, + has_stale_index_rows, + run_post_index_cleanup, +) from DashAI.back.services.RAG.prompt_service import PromptService +from DashAI.back.services.RAG.session_params import filter_pipeline_params from DashAI.back.services.RAG.setup_service import SetupService if TYPE_CHECKING: from sqlalchemy.orm import sessionmaker + from DashAI.back.dependencies.registry.component_registry import ( + ComponentRegistry, + ) + from DashAI.back.tasks.base_generative_task import BaseGenerativeTask + from DashAI.back.workflows.base_generative_workflow import ( + BaseGenerativeWorkflow, + ) + #: Session parameters the pipeline understands: the required model keys plus #: the optional (but still pipeline-shaped) model keys such as the query #: transformation stage. Any other key is filtered before the config guard. @@ -133,6 +151,364 @@ def report(progress: Dict[str, Any]) -> None: return report +def _load_turn_rows( + db: Session, generative_process_id: int +) -> tuple[GenerativeProcess, GenerativeSession]: + """Load a chat turn's process and its session, checking the session is RAG. + + Parameters + ---------- + db : Session + Session the rows are read in. + generative_process_id : int + The turn being run. + + Returns + ------- + tuple[GenerativeProcess, GenerativeSession] + The process and the session it belongs to. + + Raises + ------ + JobError + If the process or its session is missing, or the session is not a RAG one. + """ + generative_process = db.get(GenerativeProcess, generative_process_id) + if not generative_process: + raise JobError(f"Generative process {generative_process_id} not found in DB.") + generative_session = db.get(GenerativeSession, generative_process.session_id) + if not generative_session: + raise JobError(f"Session {generative_process.session_id} not found in DB.") + if generative_session.workflow_name != RAG_WORKFLOW_NAME: + raise JobError( + f"Session {generative_session.id} is run by " + f"{generative_session.workflow_name}, not " + f"{RAG_WORKFLOW_NAME}." + ) + return generative_process, generative_session + + +def _run_cleanup_if_rebuilt( + db: Session, + component_registry: "ComponentRegistry", + session_id: int, + footprint_before: "IndexFootprint", + model: RAGPipeline, + rag_path: str | Path, +) -> None: + """Run the post-index cleanup when a build changed the index, or left stale rows. + + A build adds chunk sets and bridges only when it creates something new, so a + footprint that differs from the one taken before the build means the cleanup + has work to do. A cleanup that failed earlier leaves stale rows behind a build + that reused everything, so those are checked as well. + + Parameters + ---------- + db : Session + Session the cleanup runs in. + component_registry : ComponentRegistry + Component registry, passed through to the cleanup. + session_id : int + The generative session being built. + footprint_before : IndexFootprint + The session's footprint captured before the build. + model : RAGPipeline + The pipeline the build returned; its root retriever is the live index. + rag_path : str | Path + The RAG storage root (``RAG_PATH``). + """ + footprint_after = capture_index_footprint(db, session_id) + if footprint_after == footprint_before and not has_stale_index_rows(db, session_id): + return + run_post_index_cleanup( + db, + component_registry, + session_id, + model.retriever.get_id(), + rag_path, + ) + + +def _build_turn_pipeline( + db: Session, + component_registry: "ComponentRegistry", + config: Mapping[str, Any], + generative_session: GenerativeSession, +) -> RAGPipeline: + """Build the session's pipeline for one turn, then clean up after a rebuild. + + Parameters + ---------- + db : Session + Session the pipeline is built in. + component_registry : ComponentRegistry + Component registry used to resolve the stored components. + config : Mapping[str, Any] + Application configuration, which holds the ``RAG_PATH`` setting. + generative_session : GenerativeSession + The RAG session whose parameters describe the pipeline. + + Returns + ------- + RAGPipeline + The built pipeline. + """ + # Whitelist-only: accept only known RAG pipeline keys. + # Prompts live in their own table, so materialize them + # back into the configuration before building the pipeline. + if generative_session.parameters is None: + raise JobError(f"Session {generative_session.id} has no stored parameters.") + raw_params = PromptService(db, component_registry).materialize_session_parameters( + generative_session.id, + dict(generative_session.parameters), + ) + extra_keys: set[str] = set(raw_params) - _RAG_PARAM_KEYS + if extra_keys: + log.debug("Filtered extra session parameter keys: %s", sorted(extra_keys)) + clean_params = filter_pipeline_params(raw_params, _RAG_PARAM_KEYS) + pipeline_config = RAGPipelineConfig.from_kwargs( + db=db, + component_registry=component_registry, + session_id=generative_session.id, + env_RAG_path=config["RAG_PATH"], + **clean_params, + ) + setup_service = SetupService(db, component_registry, config["RAG_PATH"]) + # The build reuses the stored index unless its configuration changed. Only a + # build that created rows can leave stale ones behind, so the cleanup runs + # after such a build. + footprint_before = capture_index_footprint(db, generative_session.id) + model: RAGPipeline = setup_service.build_pipeline(pipeline_config) + _run_cleanup_if_rebuilt( + db, + component_registry, + generative_session.id, + footprint_before, + model, + config["RAG_PATH"], + ) + return model + + +def _load_history( + db: Session, task: "BaseGenerativeTask", session_id: int, process_id: int +) -> list[tuple[str, str]]: + """Build the conversation history from the finished turns before this one. + + A retried turn keeps its place in the conversation (#969), so later turns are + not its history. Each prior answer is resolved by its row type, not its + position, and a finished process with no message row is skipped. + + Parameters + ---------- + db : Session + Session the finished processes are read in. + task : BaseGenerativeTask + The task that knows how to read the message out of a process's output. + session_id : int + The generative session of the turn. + process_id : int + The turn being run; only processes with a lower id are history. + + Returns + ------- + list[tuple[str, str]] + ``(user message, assistant message)`` pairs, oldest first. + """ + finished_processes: list[GenerativeProcess] = ( + db.query(GenerativeProcess) + .filter( + GenerativeProcess.session_id == session_id, + GenerativeProcess.status == RunStatus.FINISHED, + GenerativeProcess.id < process_id, + ) + .order_by(GenerativeProcess.id) + .all() + ) + history: list[tuple[str, str]] = [] + for prior in finished_processes: + message = task.extract_message_from_output(prior.output) + if message is None: + log.debug( + "Skipping process %d from history: no %r output row.", + prior.id, + RAG_OUTPUT_MESSAGE_TYPE, + ) + continue + history.append((prior.input[0].data, message)) + return history + + +def _prepare_turn( + db: Session, + component_registry: "ComponentRegistry", + config: Mapping[str, Any], + generative_process_id: int, +) -> tuple[RAGPipeline, Any, int, "BaseGenerativeWorkflow"]: + """Run the setup stage of a turn and mark the process as started. + + Builds the pipeline, prepares the input with the conversation history, and + commits the started status. The caller generates with the returned pipeline. + + Parameters + ---------- + db : Session + Session the setup runs in. + component_registry : ComponentRegistry + Component registry used to resolve the stored components. + config : Mapping[str, Any] + Application configuration. + generative_process_id : int + The turn being run. + + Returns + ------- + tuple[RAGPipeline, Any, int, BaseGenerativeWorkflow] + The built pipeline, the prepared input, the process id and the workflow + that saves the output. + + Raises + ------ + JobError + If the process or session is missing, or the session is not a RAG one. + """ + generative_process, generative_session = _load_turn_rows(db, generative_process_id) + model = _build_turn_pipeline(db, component_registry, config, generative_session) + input_data = generative_process.input + task: BaseGenerativeTask = component_registry[generative_session.task_name][ + "class" + ]() + workflow: BaseGenerativeWorkflow = component_registry[ + generative_session.workflow_name + ]["class"]() + history = _load_history(db, task, generative_session.id, generative_process.id) + input_data = task.prepare_for_task(input_data, history=history) + + generative_process.set_status_as_started() + generative_process.set_progress(None) + db.commit() + log.debug("Pipeline built and ready for process %d", generative_process_id) + return model, input_data, generative_process.id, workflow + + +def _process_data_rows( + output_data: Iterable[Any], process_id: int +) -> list[ProcessData]: + """Turn the workflow's ``(data, type)`` output pairs into process rows. + + Parameters + ---------- + output_data : Iterable[Any] + The pairs the workflow produced. + process_id : int + The process the rows belong to. + + Returns + ------- + list[ProcessData] + One output row per pair, in order. + + Raises + ------ + JobError + If an item is not a ``(data, type)`` pair. + """ + rows: list[ProcessData] = [] + for item in output_data: + if not isinstance(item, tuple) or len(item) != 2: + raise JobError("Output from task must be a list of tuples (data, type).") + data, data_type = item + rows.append( + ProcessData( + data=data, + data_type=data_type, + process_id=process_id, + is_input=False, + ) + ) + return rows + + +def _save_turn_output( + db: Session, + workflow: "BaseGenerativeWorkflow", + output: Any, + process_id: int, + images_path: str | Path, +) -> None: + """Save a generated answer and mark its process as finished. + + Parameters + ---------- + db : Session + Session the output is saved in. + workflow : BaseGenerativeWorkflow + The workflow that turns the raw generation into ``(data, type)`` pairs. + output : Any + The raw generation result. + process_id : int + The process that produced the output. + images_path : str | Path + The ``IMAGES_PATH`` setting, where generated images are written. + + Raises + ------ + JobError + If the process is missing, or the workflow output is malformed. + """ + generative_process = db.get(GenerativeProcess, process_id) + if not generative_process: + raise JobError(f"Generative process {process_id} not found when saving output.") + output_data = workflow.process_output(output, images_path=images_path) + db.add_all(_process_data_rows(output_data, process_id)) + db.commit() + + db.refresh(generative_process) + generative_process.set_progress(None) + generative_process.set_status_as_finished() + db.commit() + log.debug("Output saved for process %d", process_id) + + +def _stage_error(prefix: str, error: Exception) -> JobError: + """Log a stage failure and wrap it in a job error that carries the stage prefix. + + Parameters + ---------- + prefix : str + Human-readable stage description, e.g. ``"Error during RAG pipeline + setup"``. + error : Exception + The exception that ended the stage. It is logged with its traceback. + + Returns + ------- + JobError + The job error to store and raise, built by :func:`_job_error`. + """ + log.exception(error) + return _job_error(prefix, error) + + +def _release_run_resources(failure: BaseException | None) -> None: + """Release what a run held, once its failure has left the except block. + + The frame release runs first, then ``gc.collect()`` so ``empty_cache()`` can + hand the freed blocks back to CUDA. Every step is best-effort and must not + replace the failure that ended the run. + + Parameters + ---------- + failure : BaseException | None + The failure that ended the run, or ``None`` when the run completed. + """ + if failure is not None: + _release_frames(failure) + gc.collect() + _empty_accelerator_cache() + + class RAGJob(BaseJob): """RAGJob handles the full RAG pipeline lifecycle as a background job.""" @@ -250,6 +626,132 @@ def get_job_name(self) -> str: return f"RAG Process #{generative_process_id}" + def _run_setup( + self, + session_factory: "sessionmaker", + component_registry: "ComponentRegistry", + config: Mapping[str, Any], + generative_process_id: int, + ) -> tuple[RAGPipeline, Any, int, "BaseGenerativeWorkflow"]: + """Run session 1: load, build, prepare and mark the turn as started. + + A ``JobError`` is stored on the process and re-raised unchanged. Any + other exception is logged, wrapped with the setup prefix, stored and + raised. + + Parameters + ---------- + session_factory : sessionmaker + Factory for the short-lived setup session. + component_registry : ComponentRegistry + Component registry used to resolve the stored components. + config : Mapping[str, Any] + Application configuration. + generative_process_id : int + The turn being run. + + Returns + ------- + tuple[RAGPipeline, Any, int, BaseGenerativeWorkflow] + The built pipeline, the prepared input, the process id and the + workflow that saves the output. + + Raises + ------ + JobError + If the setup fails. + """ + try: + with session_factory() as db: + return _prepare_turn( + db, component_registry, config, generative_process_id + ) + except JobError as e: + self._fail(e) + raise + except Exception as e: + error = _stage_error("Error during RAG pipeline setup", e) + self._fail(error) + raise error from e + + def _run_generation( + self, + session_factory: "sessionmaker", + model: RAGPipeline, + input_data: Any, + process_id: int, + ) -> Any: + """Run the generation stage, with no database session held open. + + Parameters + ---------- + session_factory : sessionmaker + Factory for the progress reporter's short-lived sessions. + model : RAGPipeline + The pipeline built by the setup stage. + input_data : Any + The prepared input the pipeline generates from. + process_id : int + The process whose live progress the reporter writes. + + Returns + ------- + Any + The raw generation result, saved by the output stage. + + Raises + ------ + JobError + If the generation fails. + """ + reporter = _make_progress_reporter(session_factory, process_id) + try: + output: Any = model.generate(input_data, progress_callback=reporter) + log.debug("Generation completed for process %d", process_id) + except Exception as e: + error = _stage_error("Error during RAG pipeline execution", e) + self._fail(error) + raise error from e + return output + + def _run_save( + self, + session_factory: "sessionmaker", + workflow: "BaseGenerativeWorkflow", + output: Any, + process_id: int, + config: Mapping[str, Any], + ) -> None: + """Run session 2: save the generated output and mark the turn finished. + + Parameters + ---------- + session_factory : sessionmaker + Factory for the short-lived save session. + workflow : BaseGenerativeWorkflow + The workflow that turns the raw generation into ``(data, type)`` pairs. + output : Any + The raw generation result. + process_id : int + The process that produced the output. + config : Mapping[str, Any] + Application configuration, which holds the ``IMAGES_PATH`` setting. + + Raises + ------ + JobError + If the output cannot be saved. + """ + try: + with session_factory() as db: + _save_turn_output( + db, workflow, output, process_id, config["IMAGES_PATH"] + ) + except Exception as e: + error = _stage_error("Error processing and saving RAG generation output", e) + self._fail(error) + raise error from e + @inject def run(self) -> None: """Execute the full RAG pipeline lifecycle as a background job. @@ -283,185 +785,19 @@ def run(self) -> None: # failure is propagating its traceback still pins the model (and the # half-built pipeline), so cleanup must run after the except block. try: - # ── Session 1: Load, build, prepare ──────────────────────── - try: - with session_factory() as db: - generative_process = db.get( - GenerativeProcess, generative_process_id - ) - if not generative_process: - raise JobError( - f"Generative process {generative_process_id} " - "not found in DB." - ) - generative_session = db.get( - GenerativeSession, generative_process.session_id - ) - if not generative_session: - raise JobError( - f"Session {generative_process.session_id} not found in DB." - ) - if generative_session.workflow_name != RAG_WORKFLOW_NAME: - raise JobError( - f"Session {generative_session.id} is run by " - f"{generative_session.workflow_name}, not " - f"{RAG_WORKFLOW_NAME}." - ) - - # Whitelist-only: accept only known RAG pipeline keys. - # Prompts live in their own table, so materialize them - # back into the configuration before building the pipeline. - raw_params = PromptService( - db, component_registry - ).materialize_session_parameters( - generative_session.id, - dict(generative_session.parameters or {}), - ) - extra_keys: set[str] = set(raw_params) - _RAG_PARAM_KEYS - if extra_keys: - log.debug( - "Filtered extra session parameter keys: %s", - sorted(extra_keys), - ) - clean_params = { - k: v for k, v in raw_params.items() if k in _RAG_PARAM_KEYS - } - pipeline_config = RAGPipelineConfig.from_kwargs( - db=db, - component_registry=component_registry, - session_id=generative_session.id, - env_RAG_path=config["RAG_PATH"], - **clean_params, - ) - setup_service = SetupService( - db, - component_registry, - config["RAG_PATH"], - ) - model: RAGPipeline = setup_service.build_pipeline(pipeline_config) - - # Build conversation history from the finished turns before - # this one: a retried turn keeps its place in the - # conversation (#969), so later turns are not its history. - input_data = generative_process.input - task = component_registry[generative_session.task_name]["class"]() - workflow = component_registry[generative_session.workflow_name][ - "class" - ]() - finished_processes: list[GenerativeProcess] = ( - db.query(GenerativeProcess) - .filter( - GenerativeProcess.session_id == generative_session.id, - GenerativeProcess.status == RunStatus.FINISHED, - GenerativeProcess.id < generative_process.id, - ) - .order_by(GenerativeProcess.id) - .all() - ) - # Resolve each prior answer by row TYPE rather than position: - # a finished process now stores its message last (after the - # Queries and Dict rows), so ``output[0]`` is no longer the - # message. A process whose output has no message row is - # malformed; skip it instead of crashing the whole job. - history: list[tuple[str, str]] = [] - for prior in finished_processes: - message = task.extract_message_from_output(prior.output) - if message is None: - log.debug( - "Skipping process %d from history: no %r output row.", - prior.id, - RAG_OUTPUT_MESSAGE_TYPE, - ) - continue - history.append((prior.input[0].data, message)) - input_data = task.prepare_for_task(input_data, history=history) - - generative_process.set_status_as_started() - generative_process.set_progress(None) - db.commit() - - process_id = generative_process.id - log.debug( - "Pipeline built and ready for process %d", - generative_process_id, - ) - except JobError as e: - self._fail(e) - raise - except Exception as e: - log.exception(e) - error = _job_error("Error during RAG pipeline setup", e) - self._fail(error) - raise error from e - - # ── Generation (no DB session) ───────────────────────────── - reporter = _make_progress_reporter(session_factory, process_id) - try: - output: Any = model.generate(input_data, progress_callback=reporter) - log.debug("Generation completed for process %d", generative_process_id) - except Exception as e: - log.exception(e) - error = _job_error("Error during RAG pipeline execution", e) - self._fail(error) - raise error from e - - # ── Session 2: Save output ───────────────────────────────── - try: - with session_factory() as db: - generative_process = db.get(GenerativeProcess, process_id) - if not generative_process: - raise JobError( - f"Generative process {process_id} not found when " - "saving output." - ) - - output_data = workflow.process_output( - output, images_path=config["IMAGES_PATH"] - ) - outputs_for_database = [] - for o in output_data: - if not isinstance(o, tuple) or len(o) != 2: - raise JobError( - "Output from task must be a list of tuples " - "(data, type)." - ) - data, data_type = o - outputs_for_database.append( - ProcessData( - data=data, - data_type=data_type, - process_id=generative_process.id, - is_input=False, - ) - ) - - db.add_all(outputs_for_database) - db.commit() - - db.refresh(generative_process) - generative_process.set_progress(None) - generative_process.set_status_as_finished() - db.commit() - log.debug("Output saved for process %d", generative_process_id) - except Exception as e: - log.exception(e) - error = _job_error( - "Error processing and saving RAG generation output", e - ) - self._fail(error) - raise error from e + model, input_data, process_id, workflow = self._run_setup( + session_factory, component_registry, config, generative_process_id + ) + output = self._run_generation( + session_factory, model, input_data, process_id + ) + self._run_save(session_factory, workflow, output, process_id, config) except BaseException as error: failure = error # Cleanup runs here, after the except block, because while an exception # is propagating its traceback still references the model and pipeline. - # The frame release runs first, then gc.collect() so empty_cache() can - # hand the freed blocks back to CUDA. All steps are best-effort and must - # not replace the original failure. model = None - if failure is not None: - _release_frames(failure) - gc.collect() - _empty_accelerator_cache() + _release_run_resources(failure) if failure is not None: raise failure diff --git a/DashAI/back/services/RAG/chunking_service.py b/DashAI/back/services/RAG/chunking_service.py index c2d4dd5fa..57c61bb10 100644 --- a/DashAI/back/services/RAG/chunking_service.py +++ b/DashAI/back/services/RAG/chunking_service.py @@ -25,12 +25,11 @@ from DashAI.back.models.RAG.documents.source_document import SourceDocument from DashAI.back.models.RAG.RAG_models_factory import RAGModelsFactory from DashAI.back.models.RAG.utils import hash_function +from DashAI.back.services.RAG.storage_layout import CHUNK_SETS_DIRNAME from DashAI.back.types.value_types import Text log = logging.getLogger(__name__) -CHUNK_SETS_DIRNAME = "chunk_sets" - def chunk_document_dir( rag_path: str | Path, chunk_set_id: int, document_id: int diff --git a/DashAI/back/services/RAG/cleanup_service.py b/DashAI/back/services/RAG/cleanup_service.py index 04a8d5d81..64e3f0288 100644 --- a/DashAI/back/services/RAG/cleanup_service.py +++ b/DashAI/back/services/RAG/cleanup_service.py @@ -1,7 +1,11 @@ import logging +import os +from collections.abc import Iterable +from dataclasses import dataclass from pathlib import Path from typing import Any, Sequence +from sqlalchemy import select from sqlalchemy.orm import Session from DashAI.back.core.schema_fields.utils import normalize_payload @@ -20,19 +24,144 @@ from DashAI.back.dependencies.registry.component_registry import ComponentRegistry from DashAI.back.models.RAG.exceptions import RAGComponentNotFoundError from DashAI.back.models.RAG.RAG_constants import ( - COMPOSITE_RETRIEVER_NAMES, + RAG_PARAM_CHUNKING_MODEL, RAG_PARAM_RETRIEVER_MODEL, ) from DashAI.back.models.RAG.retrievers.persistence_signature import ( reference_signature, ) -from DashAI.back.models.RAG.retrievers.ref_utils import is_component_ref +from DashAI.back.models.RAG.retrievers.ref_utils import COMPONENT_KEY, is_component_ref +from DashAI.back.services.RAG.config_equality import configs_equal from DashAI.back.services.RAG.deferred_fs import remove_after_commit from DashAI.back.services.RAG.retriever_db_service import RetrieverDBService +from DashAI.back.services.RAG.storage_layout import ( + CHUNK_SETS_DIRNAME, + EMBEDDINGS_DIRNAME, + SPARSE_RETRIEVERS_DIRNAME, +) log = logging.getLogger(__name__) +@dataclass(frozen=True) +class IndexCleanupSummary: + """Counts of what :meth:`CleanupService.cleanup_after_reindex` released. + + Attributes + ---------- + chunk_sets : int + Stale chunk sets of the session that were invalidated. + bridges : int + Stale retriever bridges of the session's pipeline that were released, + composites and unit retrievers alike. Bridges removed with an + invalidated chunk set are not counted here. + embedding_matrices : int + Embedding matrices of the live chunk set that no live retriever uses. + embedding_models : int + Embedding models left unused by the release and deleted. + """ + + chunk_sets: int + bridges: int + embedding_matrices: int + embedding_models: int + + +@dataclass(frozen=True) +class _LiveIndex: + """The validated live index of a session after a successful reindex. + + Attributes + ---------- + pipeline_id : int + The session's pipeline, which owns every bridge of the index. + root_id : int + The bridge the reindex returned, which roots the live tree. + chunk_set_id : int + The chunk set the live retrievers read, owned by the session. + dense_model_ids : frozenset[int] + Embedding models used by the live dense retrievers. + """ + + pipeline_id: int + root_id: int + chunk_set_id: int + dense_model_ids: frozenset[int] + + +@dataclass(frozen=True) +class _LiveLeaves: + """The chunk set and embedding models that the leaves of a live tree read. + + Attributes + ---------- + chunk_set_id : int + The one chunk set every leaf reads. + dense_model_ids : frozenset[int] + Embedding models of the dense leaves. + """ + + chunk_set_id: int + dense_model_ids: frozenset[int] + + +@dataclass(frozen=True) +class _BridgeRelease: + """What the release of a set of bridge trees deleted. + + Attributes + ---------- + bridges : int + Bridges deleted, composites and leaves alike. + dense_leaves : frozenset[tuple[int, int]] + ``(chunk set id, embedding model id)`` of every dense leaf deleted. The + caller decides which matrices and models those leaves left unused. + """ + + bridges: int + dense_leaves: frozenset[tuple[int, int]] + + @property + def model_ids(self) -> frozenset[int]: + """Embedding models the deleted dense leaves used.""" + return frozenset(_model_ids_of(self.dense_leaves)) + + +def _model_ids_of(pairs: Iterable[tuple[int, int]]) -> set[int]: + """Return the embedding model ids of ``(chunk set id, model id)`` pairs. + + Parameters + ---------- + pairs : Iterable[tuple[int, int]] + Pairs of a chunk set id and an embedding model id. + + Returns + ------- + set[int] + The model ids, without repeats. + """ + model_ids: set[int] = set() + for _chunk_set_id, model_id in pairs: + model_ids.add(model_id) + return model_ids + + +@dataclass(frozen=True) +class _MatrixRelease: + """What :meth:`CleanupService._release_unused_matrices` released. + + Attributes + ---------- + matrices : int + Embedding matrices of the live chunk set deleted. + models : int + Embedding models deleted because nothing references them any more. + """ + + matrices: int + models: int + + def _retriever_identity(reference: Any, registry: ComponentRegistry | None) -> Any: """Return a retriever reference reduced to its persistence signature. @@ -71,6 +200,150 @@ def _retriever_identity(reference: Any, registry: ComponentRegistry | None) -> A return reference_signature(canonical, registry) +def _stored_reference(parameters: dict[str, Any], key: str) -> dict[str, Any]: + """Return the stored component reference under ``key``, or ``{}`` for none. + + A session that never set the parameter, or stored it as null, has no + reference to clean up, so ``{}`` says so. Any other value must be an object, + since a reference is always a ``{component, params}`` mapping. + + Parameters + ---------- + parameters : dict[str, Any] + Session parameters, possibly without ``key``. + key : str + The parameter whose reference is read, such as ``retriever_model``. + + Returns + ------- + dict[str, Any] + The stored reference, or ``{}`` when the parameter is absent or null. + + Raises + ------ + ValueError + If the stored value is neither null nor an object. + """ + reference = parameters.get(key) + if reference is None: + return {} + if not isinstance(reference, dict): + raise ValueError( + f"Stored parameter {key!r} must be a component reference object." + ) + return reference + + +def _retriever_component_name(parameters: dict[str, Any]) -> str | None: + """Return the class name of the retriever a session's parameters name. + + Parameters + ---------- + parameters : dict[str, Any] + Session parameters, possibly without a retriever. + + Returns + ------- + str | None + The ``component`` of the retriever reference, or ``None`` when the + session names no retriever or the reference has no component. A + reference that exists but has no component is logged as a warning, since + nothing can be matched for it. + """ + retriever_model = _stored_reference(parameters, RAG_PARAM_RETRIEVER_MODEL) + component = retriever_model.get(COMPONENT_KEY) + if retriever_model and not component: + log.warning( + "The retriever reference of a session has no component; no retriever " + "bridge is matched for it." + ) + return component + + +def _folder_key(path: str) -> str: + """Return the key under which two spellings of one folder compare equal. + + The key uses the same normalisation as :func:`_is_within`, so a folder + reached through a junction or symlink keys the same as its target. + + Parameters + ---------- + path : str + A folder path as stored on a retriever or matrix row. + + Returns + ------- + str + The resolved path, with the case and separators the platform uses. + """ + return os.path.normcase(os.path.realpath(path)) + + +def _is_within(path: str | Path, root: str | Path) -> bool: + """Whether a path lies strictly inside a folder, after resolving links. + + Parameters + ---------- + path : str | Path + The candidate. It need not exist. + root : str | Path + The folder it must lie under. + + Returns + ------- + bool + ``True`` when the resolved path is a proper descendant of the resolved + root. A path on another drive is never inside. + """ + candidate = os.path.normcase(os.path.realpath(path)) + base = os.path.normcase(os.path.realpath(root)) + if candidate == base: + return False + try: + return os.path.commonpath([candidate, base]) == base + except ValueError: + return False + + +def _storage_roots(rag_path: str | Path) -> list[Path]: + """Return the storage folders a post-index removal must stay inside. + + Parameters + ---------- + rag_path : str | Path + The ``RAG_PATH`` setting. + + Returns + ------- + list[Path] + ``/sparse_retrievers``, ``/embeddings`` and + ``/chunk_sets``. + """ + root = Path(rag_path) + return [ + root / SPARSE_RETRIEVERS_DIRNAME, + root / EMBEDDINGS_DIRNAME, + root / CHUNK_SETS_DIRNAME, + ] + + +def _is_within_any(path: str, roots: list[Path]) -> bool: + """Whether a path lies inside at least one of the given folders. + + Parameters + ---------- + path : str + The candidate path. + roots : list[Path] + The folders to test against. + + Returns + ------- + bool + """ + return any(_is_within(path, root) for root in roots) + + class CleanupService: """Cascade deletion of RAG resources when a session is deleted or updated. @@ -79,6 +352,17 @@ class CleanupService: deleted or its parameters are updated. Order of operations is critical: retrievers must be cleaned up BEFORE chunking models. + The post-index cleanup (:meth:`cleanup_after_reindex`) is scoped to one + session, and only its candidates come from that session's stale rows. Two + known limitations remain, and no global lock is taken to close them: + + - Embedding models are keyed by configuration, not by session. A model that + another session's in-flight index has resolved but not yet referenced + could be released here. That needs more than one concurrent consumer; the + Huey consumer currently runs a single worker. + - The same applies to a chat turn and an index job of the same session, + which can run concurrently. + Parameters ---------- db : Session @@ -86,18 +370,46 @@ class CleanupService: registry : ComponentRegistry | None Registry used to compare retriever configurations when a session's parameters are updated. Not needed for deletion-only use. + rag_path : str | Path | None + The RAG storage root (``RAG_PATH``). Required by + :meth:`cleanup_after_reindex`, which only removes folders inside it. + When omitted, the other cascade paths remove folders as they always + have. """ - def __init__(self, db: Session, registry: ComponentRegistry | None = None): + def __init__( + self, + db: Session, + registry: ComponentRegistry | None = None, + *, + rag_path: str | Path | None = None, + ): + """Bind the cleanup to a session, and optionally a registry and storage root. + + Parameters + ---------- + db : Session + SQLAlchemy session the cleanup reads and writes in. Methods that take + a ``commit`` flag leave the commit to the caller when it is ``False``. + registry : ComponentRegistry | None, optional + Registry used to compare retriever configurations when a session's + parameters are updated. Not needed for deletion-only use. + rag_path : str | Path | None, optional + The RAG storage root (``RAG_PATH``). Required by + :meth:`cleanup_after_reindex`, which only removes folders inside it. + When omitted, the other cascade paths remove folders as they always + have. + """ self.db = db self._registry = registry + self._rag_path = rag_path self._retriever_db = RetrieverDBService(db) def cleanup_orphaned_resources( self, session_id: int, - old_parameters: dict, - new_parameters: dict | None = None, + old_parameters: dict[str, Any], + new_parameters: dict[str, Any] | None = None, *, commit: bool = True, ) -> None: @@ -141,43 +453,36 @@ def _component_changed(key: str) -> bool: new_value = new_parameters.get(key) # Identical raw values cannot differ in identity, so the registry # is only needed when the configuration really changed. - if old_value == new_value: + if configs_equal(old_value, new_value): return False if key != RAG_PARAM_RETRIEVER_MODEL: return True return self._retriever_changed(old_value, new_value) - documents_ids = sorted(old_parameters.get("documents") or []) - # ── Retriever cleanup (MUST run BEFORE chunking) ── - retriever_model_params = old_parameters.get("retriever_model") or {} - retriever_component_name = retriever_model_params.get("component", "") + retriever_model_params = _stored_reference( + old_parameters, RAG_PARAM_RETRIEVER_MODEL + ) # The retriever rows deleted below hang off this session's chunk # set, which no other session can share now that documents belong # to one session. Rows keyed by configuration alone -- the chunking - # model here, the embedding model in _cleanup_dense_retriever -- - # *are* shared, and are guarded where they are deleted. + # model here, the embedding model in _release_dense_storage -- *are* + # shared, and are guarded where they are deleted. should_cleanup_retriever = bool(retriever_model_params) and ( - _component_changed("retriever_model") + _component_changed(RAG_PARAM_RETRIEVER_MODEL) ) if should_cleanup_retriever: - if retriever_component_name in COMPOSITE_RETRIEVER_NAMES: - self._cleanup_composite_retriever(old_parameters, session_id) - else: - self._cleanup_unit_retriever( - old_parameters, - documents_ids, - retriever_model_params, - session_id, - ) + self._cleanup_retriever(old_parameters, session_id) # ── Chunking model cleanup (AFTER retriever) ── - chunking_model_params = old_parameters.get("chunking_model") or {} + chunking_model_params = _stored_reference( + old_parameters, RAG_PARAM_CHUNKING_MODEL + ) should_cleanup_chunking = bool(chunking_model_params) and ( - _component_changed("chunking_model") + _component_changed(RAG_PARAM_CHUNKING_MODEL) ) if should_cleanup_chunking: @@ -227,7 +532,8 @@ def _retriever_changed(self, old_value: Any, new_value: Any) -> bool: except RAGComponentNotFoundError as error: log.warning("%s; treating the retriever as changed.", error) return True - return old_identity != _retriever_identity(new_value, self._registry) + new_identity = _retriever_identity(new_value, self._registry) + return not configs_equal(old_identity, new_identity) def _drop_chunking_model_if_unused(self, session_id: int) -> None: """Release the chunking model a session's pipeline points at. @@ -263,6 +569,43 @@ def _drop_chunking_model_if_unused(self, session_id: int) -> None: if record is not None: self.db.delete(record) + def _folder_in_use( + self, + model: type[RAGSparseRetriever] | type[RAGEmbeddingMatrix], + storage_folder: str, + exclude_ids: Sequence[int], + ) -> bool: + """Whether a row of ``model`` outside ``exclude_ids`` reaches a folder. + + Rows are compared by their normalised folder key, so the same folder + spelled with forward slashes, a trailing separator or another drive-letter + case still counts as in use. The tables hold one row per fitted index or + matrix, so every row is read and compared in Python. + + Parameters + ---------- + model : type + The row class whose ``storage_folder`` is compared. + storage_folder : str + Absolute folder path being released. + exclude_ids : Sequence[int] + Rows being deleted in the same transaction, which must not count as + live references. + + Returns + ------- + bool + ``True`` when at least one other row still uses the folder. + """ + key = _folder_key(storage_folder) + excluded = set(exclude_ids) + for row_id, folder in self.db.query(model.id, model.storage_folder).all(): + if row_id in excluded: + continue + if _folder_key(folder) == key: + return True + return False + def _sparse_folder_in_use( self, storage_folder: str, exclude_ids: Sequence[int] = () ) -> bool: @@ -286,12 +629,7 @@ def _sparse_folder_in_use( bool ``True`` when at least one other row still uses the folder. """ - query = self.db.query(RAGSparseRetriever).filter( - RAGSparseRetriever.storage_folder == storage_folder - ) - if exclude_ids: - query = query.filter(RAGSparseRetriever.id.notin_(list(exclude_ids))) - return bool(query.count()) + return self._folder_in_use(RAGSparseRetriever, storage_folder, exclude_ids) def _embedding_folder_in_use( self, storage_folder: str, exclude_ids: Sequence[int] = () @@ -315,24 +653,102 @@ def _embedding_folder_in_use( bool ``True`` when at least one other row still uses the folder. """ - query = self.db.query(RAGEmbeddingMatrix).filter( - RAGEmbeddingMatrix.storage_folder == storage_folder + return self._folder_in_use(RAGEmbeddingMatrix, storage_folder, exclude_ids) + + def _queue_removal(self, path: str | None) -> None: + """Queue a storage folder for removal once the transaction commits. + + Every removal of the post-index path goes through here. When a RAG root + was given, the folder must lie inside one of the storage sub-folders, so + a row that points elsewhere cannot delete unrelated files. The caller + still deletes the row; only the folder is kept. Without a root, removal + is queued as it always was. + + Accepted trade-off: when ``RAG_PATH`` changed after indexing, the stored + rows point outside the current root. Their folders are then kept with a + warning while the rows are deleted, so the folders are never retried by + a later cleanup and must be removed by hand if wanted. + + Parameters + ---------- + path : str | None + The folder to remove. ``None`` is ignored, as by + :func:`remove_after_commit`. + """ + if ( + self._rag_path is not None + and path + and not _is_within_any(path, _storage_roots(self._rag_path)) + ): + log.warning( + "Not removing %s: it is outside the RAG storage folders. Its rows " + "are deleted and the folder is kept.", + path, + ) + return + remove_after_commit(self.db, path) + + def _queue_chunk_set_removal(self, chunk_set_id: int) -> None: + """Queue the chunk folders of one chunk set for removal. + + Without a RAG root, the parent of each stored document folder is queued, + as it always was. With one, only the chunk set's own folder + ``/chunk_sets/`` can go, and only when a stored + folder lies inside it. Any other stored path is kept and logged. + + Parameters + ---------- + chunk_set_id : int + The chunk set being invalidated. Its rows are still present. + """ + rows = ( + self.db.query(RAGChunkSetDocument.path) + .filter( + RAGChunkSetDocument.chunk_set_id == chunk_set_id, + RAGChunkSetDocument.path.isnot(None), + ) + .all() + ) + paths: list[str] = [] + for row in rows: + paths.append(row[0]) + if self._rag_path is None: + parent_folders: set[str] = set() + for path in paths: + parent_folders.add(str(Path(path).parent)) + for folder in parent_folders: + remove_after_commit(self.db, folder) + return + chunk_set_dir = str( + Path(self._rag_path) / CHUNK_SETS_DIRNAME / str(chunk_set_id) ) - if exclude_ids: - query = query.filter(RAGEmbeddingMatrix.id.notin_(list(exclude_ids))) - return bool(query.count()) + owned = False + for path in paths: + if _is_within(path, chunk_set_dir): + owned = True + continue + log.warning( + "Not removing chunk folder %s: it is outside chunk set %d's folder. " + "Its rows are deleted and the folder is kept.", + path, + chunk_set_id, + ) + if owned: + self._queue_removal(chunk_set_dir) + else: + log.warning( + "Not removing chunk set %d's folder %s: no stored chunk path lies " + "inside it. Its rows are deleted and the folder is kept.", + chunk_set_id, + chunk_set_dir, + ) - def _embedding_model_in_use( - self, embedding_model_id: int, *, exclude_dense_retriever_id: int | None = None - ) -> bool: + def _embedding_model_in_use(self, embedding_model_id: int) -> bool: """Whether anything still references an embedding model. Parameters ---------- embedding_model_id : int - exclude_dense_retriever_id : int | None - A dense retriever being deleted in the same transaction, which - should not count as a live reference. Returns ------- @@ -341,10 +757,6 @@ def _embedding_model_in_use( retrievers = self.db.query(RAGDenseRetriever).filter( RAGDenseRetriever.embedding_model_id == embedding_model_id ) - if exclude_dense_retriever_id is not None: - retrievers = retrievers.filter( - RAGDenseRetriever.id != exclude_dense_retriever_id - ) if retrievers.count(): return True return bool( @@ -365,70 +777,136 @@ def _find_pipeline_id(self, session_id: int) -> int | None: pipeline = self.db.query(RAGPipeline).filter_by(session_id=session_id).first() return pipeline.id if pipeline else None - def _cleanup_composite_retriever( - self, - old_parameters: dict, - session_id: int, + def _cleanup_retriever( + self, old_parameters: dict[str, Any], session_id: int ) -> None: - """Cascade-delete a composite retriever and its children. + """Release the retriever bridges that a session's parameter update replaces. - Finds the composite bridge record, recursively deletes child - retrievers (sparse detail storage folders, dense detail records), - then removes the parent bridge record. + Every bridge of the retriever class the session named, in its pipeline, is + released, whether it is a composite or a unit. A composite is torn down + top-down with the children that no surviving tree still reads. A unit's + sparse folder goes once no other row uses it, and its dense matrices and + model go once nothing reads them. A unit bridge that a surviving composite + still reads is kept, with that composite. The other pipeline roots are + kept too. The matrices and models of the dense leaves that were deleted + are released by :meth:`_release_dense_storage`. - Args: - old_parameters: Session parameters containing the retriever - component name. - session_id: Generative session identifier. + Parameters + ---------- + old_parameters : dict[str, Any] + Session parameters before the update, holding the old retriever. + session_id : int + Generative session identifier. + """ + class_name = _retriever_component_name(old_parameters) + if class_name is None: + # The session names no retriever class, so there is nothing to + # release. Querying with no class would match only rows that have + # no class name at all, which is never what a session means. + return + self._release_class_bridges(session_id, class_name) + + def _release_class_bridges(self, session_id: int, class_name: str) -> None: + """Release every bridge of one class in a session's pipeline. + + Parameters + ---------- + session_id : int + Generative session identifier. + class_name : str + The class whose bridges are released, composite or unit. """ pipeline_id = self._find_pipeline_id(session_id) if pipeline_id is None: return - - retriever_component_name = old_parameters.get("retriever_model", {}).get( - "component" + # Every bridge of the class in this pipeline belongs to the configuration + # being replaced, so all of them go, not only the first one found. Other + # roots are kept, and so is every bridge a surviving tree still reads. + bridge_ids = self._bridge_ids_of_class(pipeline_id, class_name) + release = self._release_bridge_trees( + bridge_ids, + self._other_roots(pipeline_id, bridge_ids), + frozenset(), ) + self._release_dense_storage(release) + + def _bridge_ids_of_class(self, pipeline_id: int, class_name: str) -> list[int]: + """List the bridge ids of one class in a pipeline, in ascending order. - composite_bridges = ( - self.db.query(RAGRetriever) + Parameters + ---------- + pipeline_id : int + The pipeline whose bridges are listed. + class_name : str + The retriever class to match. + + Returns + ------- + list[int] + The matching bridge ids, ascending. + """ + rows = ( + self.db.query(RAGRetriever.id) .filter( RAGRetriever.pipeline_id == pipeline_id, - RAGRetriever.class_name == retriever_component_name, + RAGRetriever.class_name == class_name, ) + .order_by(RAGRetriever.id) .all() ) + return [row[0] for row in rows] - for bridge in composite_bridges: - self._release_bridge_tree(bridge) + def _release_dense_storage(self, release: _BridgeRelease) -> None: + """Release the matrices and embedding models that deleted dense leaves used. - def _release_bridge_tree(self, bridge: RAGRetriever) -> None: - """Delete a composite bridge together with every child bridge beneath it. + A chunk set and model pair that no surviving dense leaf reads loses its + matrices, and each matrix folder goes once no other row uses it. Then + every model the release touched is deleted, unless a row still references + it. A pair that a surviving leaf still reads is left alone. + + Parameters + ---------- + release : _BridgeRelease + The release whose dense leaves were deleted. + """ + self.db.flush() + model_ids = set(release.model_ids) + for chunk_set_id, model_id in sorted(release.dense_leaves): + if self._pair_still_read(chunk_set_id, model_id): + continue + matrices = ( + self.db.query(RAGEmbeddingMatrix) + .filter( + RAGEmbeddingMatrix.chunk_set_id == chunk_set_id, + RAGEmbeddingMatrix.embedding_model_id == model_id, + ) + .all() + ) + model_ids |= self._drop_matrices(matrices) + self.db.flush() + self._release_unused_models(model_ids) - Children are released first, recursively, so a composite nested in - another composite leaves no orphaned bridge row. A leaf's fitted detail - goes with its bridge; a sparse storage folder is removed only once no - other row still uses it. + def _pair_still_read(self, chunk_set_id: int, embedding_model_id: int) -> bool: + """Whether a surviving dense leaf reads a chunk set with an embedding model. Parameters ---------- - bridge : RAGRetriever - The composite or leaf bridge to delete. + chunk_set_id : int + embedding_model_id : int + + Returns + ------- + bool """ - child_links = ( - self.db.query(RAGRetrieverChild) - .filter_by(parent_id=bridge.id) - .order_by(RAGRetrieverChild.child_order) - .all() + readers = ( + self.db.query(RAGDenseRetriever) + .filter( + RAGDenseRetriever.chunk_set_id == chunk_set_id, + RAGDenseRetriever.embedding_model_id == embedding_model_id, + ) + .count() ) - for link in child_links: - child_bridge = self.db.get(RAGRetriever, link.child_id) - if child_bridge is not None: - self._release_bridge_tree(child_bridge) - if bridge.sparse_detail is not None: - self._cleanup_sparse_retriever(bridge) - elif bridge.dense_detail is not None: - self.db.delete(bridge.dense_detail) - self._delete_bridge_row(bridge) + return readers > 0 def _delete_bridge_row(self, bridge: RAGRetriever) -> None: """Delete a bridge row and every child link that points at it. @@ -437,6 +915,9 @@ def _delete_bridge_row(self, bridge: RAGRetriever) -> None: the ORM cascade. The links where it is a child are removed explicitly, because nothing else would remove them and they would dangle. + Every deletion of a bridge goes through here, the composites and the + leaves of :meth:`_release_bridge_trees` alike. + Parameters ---------- bridge : RAGRetriever @@ -447,272 +928,1004 @@ def _delete_bridge_row(self, bridge: RAGRetriever) -> None: ).delete(synchronize_session="fetch") self.db.delete(bridge) - def _cleanup_unit_retriever( - self, - old_parameters: dict, - documents_ids: list, - retriever_model_params: dict, - session_id: int, + def invalidate_session_artifacts( + self, session_id: int, *, commit: bool = True ) -> None: - """Cascade-delete a unit retriever (dense or sparse). + """Delete every chunk set a session owns, with what was fitted on it. - Determines retriever type by inspecting the bridge relationship - (``dense_detail`` vs ``sparse_detail``) rather than parameter heuristics. + Chunk sets carry their owning ``session_id``, so this never reaches the + index of another session, even one using the same Data documents. - Args: - old_parameters: Session parameters dict. - documents_ids: Document ids associated with the session. - retriever_model_params: The ``retriever_model`` parameter dict. - session_id: Generative session identifier. + Parameters + ---------- + session_id : int + The generative session whose indexes are discarded. + commit : bool + When ``False`` the caller owns the transaction and commits it. """ - pipeline_id = self._find_pipeline_id(session_id) - if pipeline_id is None: - return - - # Every bridge of the class in this pipeline belongs to the configuration - # being replaced, so all of them go, not only the first one found. - bridges = ( - self.db.query(RAGRetriever) - .filter( - RAGRetriever.pipeline_id == pipeline_id, - RAGRetriever.class_name == retriever_model_params.get("component"), - ) - .all() + rows = self.db.query(RAGChunkSet.id).filter( + RAGChunkSet.session_id == session_id ) - for bridge in bridges: - if bridge.dense_detail is not None: - self._cleanup_dense_retriever(bridge, documents_ids) - elif bridge.sparse_detail is not None: - self._cleanup_sparse_retriever(bridge) - self._delete_bridge_row(bridge) + chunk_set_ids: list[int] = [] + for row in rows: + chunk_set_ids.append(row[0]) + for chunk_set_id in chunk_set_ids: + self._invalidate_chunk_set(chunk_set_id) + if commit: + self.db.commit() - def _cleanup_dense_retriever( - self, - bridge: RAGRetriever, - documents_ids: list, - ) -> None: - """Cascade-delete a dense retriever and its embedding resources. + def invalidate_legacy_artifacts(self, *, commit: bool = True) -> int: + """Delete the chunk sets that have no owning session. - Removes embedding matrix storage folders, deletes matrix DB records, - the embedding model record, and the dense detail record. + Migration d8f3a1c6e2b9 detaches every chunk set that existed before + chunks became Arrow documents, and older ones indexed rows of the + legacy ``document`` table. None of them can be used again, so this + removes their rows and folders at startup. - Args: - bridge: The bridge record for the dense retriever. - documents_ids: Document ids whose embeddings to delete. - """ - dense_retriever = bridge.dense_detail - chunk_set_id = dense_retriever.chunk_set_id - embedding_model_id = dense_retriever.embedding_model_id + Parameters + ---------- + commit : bool + When ``False`` the caller owns the transaction and commits it. - embedding_matrices = ( - self.db.query(RAGEmbeddingMatrix) - .filter( - RAGEmbeddingMatrix.chunk_set_id == chunk_set_id, - RAGEmbeddingMatrix.embedding_model_id == embedding_model_id, - RAGEmbeddingMatrix.document_id.in_(documents_ids), + Returns + ------- + int + Number of chunk sets deleted. + """ + rows = self.db.query(RAGChunkSet.id).filter(RAGChunkSet.session_id.is_(None)) + chunk_set_ids: list[int] = [] + for row in rows.all(): + chunk_set_ids.append(row[0]) + for chunk_set_id in chunk_set_ids: + self._invalidate_chunk_set(chunk_set_id) + if commit: + self.db.commit() + return len(chunk_set_ids) + + def _invalidate_chunk_set(self, chunk_set_id: int) -> None: + """Delete one chunk set and everything fitted on it. + + Removes the composite retrievers built over its retrievers, its sparse + and dense retrievers, every embedding matrix that carries its id (linked + to a dense retriever or not), the embedding models that nothing else + uses, and the chunk set itself, whose chunks and membership rows go with + it. Chunk folders belong to one chunk set, so they are queued for removal + with it; see :meth:`_queue_chunk_set_removal`. + + The retrievers fitted on the chunk set are the doomed leaves. Every + pipeline tree that reaches one of them is torn down top-down, and the + trees that do not are kept, so a composite of another chunk set that + still stands is left alone. A leaf that no root reaches, for example one + behind a rootless cycle, is deleted directly, so that no leaf is left + pointing at the chunk set. See :meth:`_release_bridge_trees` for the + deletion order. + + Parameters + ---------- + chunk_set_id : int + The chunk set to delete. + """ + doomed = self._chunk_set_bridge_ids(chunk_set_id) + release = self._release_chunk_set_trees(doomed) + model_ids = set(release.model_ids) + model_ids |= self._drop_leftover_leaves(chunk_set_id) + model_ids |= self._drop_chunk_set_matrices(chunk_set_id) + self.db.flush() + self._release_unused_models(model_ids) + self._queue_chunk_set_removal(chunk_set_id) + chunk_set = self.db.get(RAGChunkSet, chunk_set_id) + if chunk_set is not None: + self.db.delete(chunk_set) + + def _drop_leftover_leaves(self, chunk_set_id: int) -> set[int]: + """Delete the leaves of a chunk set that the pipeline trees did not release. + + Runs after :meth:`_release_chunk_set_trees`. A leaf that is still listed + sits behind no root, so nothing else would delete it and it would keep + pointing at the chunk set. A listed bridge that has lost its fitted + detail is deleted outright, since no tree would reach it. Composites + belong to the trees that hold them and are not touched here. + + Parameters + ---------- + chunk_set_id : int + The chunk set being invalidated. + + Returns + ------- + set[int] + Embedding models the deleted dense leaves used. + """ + leftover = sorted(self._chunk_set_bridge_ids(chunk_set_id)) + if not leftover: + return set() + leaves: list[RAGRetriever] = [] + for bridge_id in leftover: + bridge = self.db.get(RAGRetriever, bridge_id) + if bridge is None: + # Already gone, so there is no row left to delete. + continue + if bridge.sparse_detail is None and bridge.dense_detail is None: + self._delete_bridge_row(bridge) + else: + leaves.append(bridge) + return _model_ids_of(self._drop_leaf_bridges(leaves)) + + def _chunk_set_bridge_ids(self, chunk_set_id: int) -> frozenset[int]: + """List the bridges of the sparse and dense leaves fitted on a chunk set. + + Parameters + ---------- + chunk_set_id : int + The chunk set whose fitted leaves are listed. + + Returns + ------- + frozenset[int] + Bridge ids of the leaves that read the chunk set. + """ + bridge_ids: set[int] = set() + sparse_rows = ( + self.db.query(RAGSparseRetriever.bridge_id) + .filter(RAGSparseRetriever.chunk_set_id == chunk_set_id) + .all() + ) + for row in sparse_rows: + bridge_ids.add(row[0]) + dense_rows = ( + self.db.query(RAGDenseRetriever.bridge_id) + .filter(RAGDenseRetriever.chunk_set_id == chunk_set_id) + .all() + ) + for row in dense_rows: + bridge_ids.add(row[0]) + return frozenset(bridge_ids) + + def _release_chunk_set_trees(self, doomed: frozenset[int]) -> _BridgeRelease: + """Release the pipeline trees that hold doomed leaves. + + The pipelines are those of the doomed bridges. In each one, a root whose + tree reaches a doomed leaf is torn down; every other root is kept, with + the trees under it. A chunk set without a bridge in any pipeline releases + nothing here, and its rows are deleted by the caller. + + Parameters + ---------- + doomed : frozenset[int] + Bridge ids of the leaves that read the chunk set being invalidated. + + Returns + ------- + _BridgeRelease + Bridges deleted, and the embedding models their dense details used. + """ + roots: list[int] = [] + keep: list[int] = [] + for pipeline_id in self._pipelines_of(doomed): + for root_id in self._pipeline_root_ids(pipeline_id): + if self._reaches(root_id, doomed): + roots.append(root_id) + else: + keep.append(root_id) + return self._release_bridge_trees(roots, keep, doomed) + + def _pipelines_of(self, bridge_ids: frozenset[int]) -> set[int]: + """List the pipelines that own the given bridges. + + Parameters + ---------- + bridge_ids : frozenset[int] + Bridges whose owning pipelines are wanted. Ids of bridges that no + longer exist contribute nothing. + + Returns + ------- + set[int] + Pipeline ids of the bridges that still exist. + """ + pipeline_ids: set[int] = set() + for bridge_id in bridge_ids: + bridge = self.db.get(RAGRetriever, bridge_id) + if bridge is not None: + pipeline_ids.add(bridge.pipeline_id) + return pipeline_ids + + def _tree_order(self, root_ids: Sequence[int]) -> list[int]: + """List every bridge under the given roots, parents before children. + + The walk keeps an explicit stack, so a composite nested at any depth is + reached without recursion. Children are pushed in reverse, so they pop + in ``child_order``, which makes the result a pre-order walk. A bridge + reached more than once, through a shared child or a cycle, is listed + only at its first visit. + + Parameters + ---------- + root_ids : Sequence[int] + The roots to walk from. Each one is listed before its children. + + Returns + ------- + list[int] + The de-duplicated bridge ids, top-down. + """ + order: list[int] = [] + seen: set[int] = set() + pending = list(reversed(root_ids)) + while pending: + current = pending.pop() + if current in seen: + continue + seen.add(current) + order.append(current) + pending.extend(reversed(self._retriever_db.child_ids_in_order(current))) + return order + + def _reaches(self, root_id: int, bridge_ids: frozenset[int]) -> bool: + """Whether the tree under a root contains any of the given bridges. + + Parameters + ---------- + root_id : int + The root whose tree is searched. + bridge_ids : frozenset[int] + The bridges to look for. + + Returns + ------- + bool + """ + return any(bridge_id in bridge_ids for bridge_id in self._tree_order([root_id])) + + def _pipeline_root_ids(self, pipeline_id: int) -> list[int]: + """List the bridges of a pipeline that no child link points at. + + Each root heads one tree. A link can name a bridge of another pipeline + only through corrupt data, so the referenced set is read whole. + + Parameters + ---------- + pipeline_id : int + The pipeline whose roots are listed. + + Returns + ------- + list[int] + Root bridge ids in ascending order. + """ + referenced: set[int] = set() + for row in self.db.query(RAGRetrieverChild.child_id).all(): + referenced.add(row[0]) + bridge_rows = ( + self.db.query(RAGRetriever.id) + .filter(RAGRetriever.pipeline_id == pipeline_id) + .order_by(RAGRetriever.id) + .all() + ) + roots: list[int] = [] + for row in bridge_rows: + if row[0] not in referenced: + roots.append(row[0]) + return roots + + def _other_roots(self, pipeline_id: int, excluded: Sequence[int]) -> list[int]: + """List the pipeline's roots that are not in ``excluded``. + + Parameters + ---------- + pipeline_id : int + The pipeline whose roots are listed. + excluded : Sequence[int] + Roots being torn down, or the live root, which is not a candidate. + + Returns + ------- + list[int] + The remaining root bridge ids, in ascending order. + """ + skipped = set(excluded) + remaining: list[int] = [] + for root_id in self._pipeline_root_ids(pipeline_id): + if root_id not in skipped: + remaining.append(root_id) + return remaining + + def _release_bridge_trees( + self, + roots: Sequence[int], + keep_roots: Sequence[int], + doomed_leaves: frozenset[int], + ) -> _BridgeRelease: + """Delete the trees under ``roots``, except what ``keep_roots`` reaches. + + Every bridge under ``roots`` is deleted unless a tree under + ``keep_roots`` still references it, directly or through children. A + child is therefore removed only when no surviving tree references it. + The leaves in ``doomed_leaves`` are deleted even when a kept tree reaches + them, and every deleted bridge takes its child links with it. + + Deletion order is fixed, and each step goes through + :meth:`_delete_bridge_row`: + + 1. composites, and bridges without a fitted detail, top-down; + 2. leaves, each one's fitted details first (a sparse folder is queued only + once no other row uses it; a dense row is deleted), then its bridge; + 3. the embedding matrices and models are not touched here. The + ``(chunk set, model)`` pairs of the dense leaves are returned instead. + + Contract: this method deletes bridges, child links and fitted details + only. The caller must release the matrices and models of the returned + dense leaves, through :meth:`_release_dense_storage` or, for the + post-index path, :meth:`_release_unused_matrices`. Otherwise those rows + are left orphaned. + + Parameters + ---------- + roots : Sequence[int] + Roots whose trees are torn down. + keep_roots : Sequence[int] + Roots whose trees survive. + doomed_leaves : frozenset[int] + Leaf bridges deleted even when a surviving tree reaches them. + + Returns + ------- + _BridgeRelease + Bridges deleted, and the ``(chunk set, model)`` pairs of the dense + leaves deleted. + """ + surviving = set(self._tree_order(keep_roots)) - doomed_leaves + deleting: list[int] = [] + for bridge_id in self._tree_order(roots): + if bridge_id not in surviving: + deleting.append(bridge_id) + composites, leaves = self._partition_bridges(deleting) + for bridge in composites: + self._delete_bridge_row(bridge) + dense_leaves = self._drop_leaf_bridges(leaves) + self.db.flush() + return _BridgeRelease( + bridges=len(composites) + len(leaves), + dense_leaves=frozenset(dense_leaves), + ) + + def _partition_bridges( + self, bridge_ids: list[int] + ) -> tuple[list[RAGRetriever], list[RAGRetriever]]: + """Split bridges into composites and leaves, keeping their order. + + A leaf is a bridge with a fitted detail. Every other bridge, including + one with neither a detail nor children, counts as a composite. + + Parameters + ---------- + bridge_ids : list[int] + Bridge ids to split. Ids of bridges that no longer exist are skipped. + + Returns + ------- + tuple[list[RAGRetriever], list[RAGRetriever]] + The composites and the leaves. + """ + composites: list[RAGRetriever] = [] + leaves: list[RAGRetriever] = [] + for bridge_id in bridge_ids: + bridge = self.db.get(RAGRetriever, bridge_id) + if bridge is None: + continue + if bridge.sparse_detail is None and bridge.dense_detail is None: + composites.append(bridge) + else: + leaves.append(bridge) + return composites, leaves + + def _drop_leaf_bridges(self, leaves: list[RAGRetriever]) -> set[tuple[int, int]]: + """Delete leaf bridges together with every fitted detail they hold. + + A bridge may hold a sparse detail, a dense detail, or both, and every + detail present is deleted. The bridge row goes last, once. + + Parameters + ---------- + leaves : list[RAGRetriever] + Bridges that each have a sparse or a dense detail. + + Returns + ------- + set[tuple[int, int]] + ``(chunk set id, embedding model id)`` of each dense detail deleted. + The caller decides which matrices and models are still referenced. + """ + sparse_details: list[RAGSparseRetriever] = [] + dense_details: list[RAGDenseRetriever] = [] + for bridge in leaves: + if bridge.sparse_detail is not None: + sparse_details.append(bridge.sparse_detail) + if bridge.dense_detail is not None: + dense_details.append(bridge.dense_detail) + sparse_ids = [detail.id for detail in sparse_details] + for sparse_detail in sparse_details: + self._drop_sparse_detail(sparse_detail, sparse_ids) + dense_pairs: set[tuple[int, int]] = set() + for dense_detail in dense_details: + dense_pairs.add( + (dense_detail.chunk_set_id, dense_detail.embedding_model_id) ) + self.db.delete(dense_detail) + for bridge in leaves: + self._delete_bridge_row(bridge) + return dense_pairs + + def _drop_chunk_set_matrices(self, chunk_set_id: int) -> set[int]: + """Delete every embedding matrix of a chunk set, linked or not. + + A matrix can exist without a dense retriever that reads it, for example + after a failed index. Matching on the chunk set itself catches those too, + so the chunk set row can always be deleted. + + Parameters + ---------- + chunk_set_id : int + The chunk set whose matrices go. + + Returns + ------- + set[int] + Embedding models the deleted matrices used. + """ + matrices = ( + self.db.query(RAGEmbeddingMatrix) + .filter(RAGEmbeddingMatrix.chunk_set_id == chunk_set_id) .all() ) + return self._drop_matrices(matrices) + + def _drop_matrices(self, matrices: list[RAGEmbeddingMatrix]) -> set[int]: + """Delete embedding matrix rows, and each folder once nothing else uses it. + + Parameters + ---------- + matrices : list[RAGEmbeddingMatrix] + The rows to delete. Rows in this list do not count as live references + to each other's folders. - matrix_ids = [matrix.id for matrix in embedding_matrices] - for matrix in embedding_matrices: + Returns + ------- + set[int] + Embedding models the deleted matrices used. + """ + doomed_ids = [matrix.id for matrix in matrices] + model_ids: set[int] = set() + for matrix in matrices: + model_ids.add(matrix.embedding_model_id) if not self._embedding_folder_in_use( - matrix.storage_folder, exclude_ids=matrix_ids + matrix.storage_folder, exclude_ids=doomed_ids ): - remove_after_commit(self.db, matrix.storage_folder) - - if matrix_ids: - self.db.query(RAGEmbeddingMatrix).filter( - RAGEmbeddingMatrix.id.in_(matrix_ids) - ).delete(synchronize_session="fetch") - - # Embedding models are also keyed by configuration alone, so another - # session's dense retriever or embedding matrix may still need this row. - embedding_model = self.db.get(RAGEmbeddingModel, embedding_model_id) - if embedding_model is not None and not self._embedding_model_in_use( - embedding_model_id, exclude_dense_retriever_id=dense_retriever.id - ): - self.db.delete(embedding_model) + self._queue_removal(matrix.storage_folder) + self.db.delete(matrix) + return model_ids + + def cleanup_after_reindex( + self, session_id: int, live_root_bridge_id: int + ) -> IndexCleanupSummary: + """Release what a session's reindex left behind, in one transaction. + + The live index is the tree under ``live_root_bridge_id``: the root and + every bridge reached through the child links. Its leaves fix the live + chunk set, which must belong to the session. Anything else of the + session is an orphan: + + 1. chunk sets of the session other than the live one, with their + retrievers, matrices and chunk folders; + 2. pipeline bridges outside the live tree: stale composites with their + child links, and stale unit retrievers with their sparse or dense + detail; + 3. embedding matrices of the live chunk set that no live dense + retriever uses, and the embedding models this leaves unused. + + Scope is the session, never the database or the disk. Candidates come + only from this session's stale rows, so a distinct-configuration model + of another session is never a candidate, and nothing unreferenced on + disk is swept. Embedding models are keyed by configuration, though, so + a model that another session's in-flight index has resolved but not yet + referenced could be released here. That needs more than one concurrent + consumer, and the same holds for a chat turn and an index job of the + same session. Both are known limitations; no global lock is taken. + + A shared folder or model is removed only once no surviving row uses it, + and every folder removed lies inside the RAG storage root. + + Calling it again when nothing is stale changes nothing. - self.db.delete(dense_retriever) + Parameters + ---------- + session_id : int + The session that was just indexed. + live_root_bridge_id : int + Bridge id of the root of the retriever the reindex built. - def _cleanup_sparse_retriever( - self, - bridge: RAGRetriever, - ) -> None: - """Cascade-delete a sparse retriever and its storage folder. + Returns + ------- + IndexCleanupSummary + How many rows of each kind were released. + + Raises + ------ + ValueError + If no RAG storage root was given to the service, the session has no + pipeline, the root is unknown or belongs to another pipeline, or the + live retrievers do not read exactly one chunk set owned by the + session. Nothing is deleted in that case. + """ + if self._rag_path is None: + raise ValueError( + "cleanup_after_reindex needs the RAG storage root to check the " + "folders it removes; construct CleanupService with rag_path." + ) + try: + live = self._live_index(session_id, live_root_bridge_id) + chunk_sets = self._invalidate_stale_chunk_sets( + session_id, live.chunk_set_id + ) + bridges = self._release_stale_bridges(live) + matrices = self._release_unused_matrices(live, bridges.model_ids) + self.db.commit() + except Exception: + self.db.rollback() + raise + return IndexCleanupSummary( + chunk_sets=chunk_sets, + bridges=bridges.bridges, + embedding_matrices=matrices.matrices, + embedding_models=matrices.models, + ) - Removes the sparse detail DB record and, when no other row shares it, - the on-disk storage folder: folders are content-addressed, so another - session may still be using this one. + def _live_index(self, session_id: int, root_id: int) -> _LiveIndex: + """Resolve and validate the live index rooted at ``root_id``. - Args: - bridge: The bridge record for the sparse retriever. + Parameters + ---------- + session_id : int + The generative session that owns the index. + root_id : int + The root bridge of the index. It must belong to the session's + pipeline. + + Returns + ------- + _LiveIndex + + Raises + ------ + ValueError + If the session has no pipeline, or the root is unknown or belongs + to another pipeline. """ - sparse_retriever = bridge.sparse_detail - if not self._sparse_folder_in_use( - sparse_retriever.storage_folder, exclude_ids=[sparse_retriever.id] - ): - remove_after_commit(self.db, sparse_retriever.storage_folder) - self.db.delete(sparse_retriever) + pipeline_id = self._find_pipeline_id(session_id) + if pipeline_id is None: + raise ValueError(f"Session {session_id} has no pipeline to clean up.") + root = self.db.get(RAGRetriever, root_id) + if root is None or root.pipeline_id != pipeline_id: + raise ValueError( + f"Retriever {root_id} is not a retriever of session {session_id}." + ) + bridge_ids = set(self._tree_order([root_id])) + self._assert_same_pipeline(session_id, bridge_ids, pipeline_id) + leaves = self._live_leaves(session_id, bridge_ids) + return _LiveIndex( + pipeline_id=pipeline_id, + root_id=root_id, + chunk_set_id=leaves.chunk_set_id, + dense_model_ids=leaves.dense_model_ids, + ) - def invalidate_session_artifacts( - self, session_id: int, *, commit: bool = True + def _assert_same_pipeline( + self, session_id: int, bridge_ids: set[int], pipeline_id: int ) -> None: - """Delete every chunk set a session owns, with what was fitted on it. + """Refuse a live tree that reaches a bridge of another pipeline. - Chunk sets carry their owning ``session_id``, so this never reaches the - index of another session, even one using the same Data documents. + Parameters + ---------- + session_id : int + bridge_ids : set[int] + The bridges of the live tree. + pipeline_id : int + The session's own pipeline. + + Raises + ------ + ValueError + If a bridge of the tree belongs to another pipeline. + """ + for bridge_id in bridge_ids: + bridge = self.db.get(RAGRetriever, bridge_id) + if bridge is not None and bridge.pipeline_id != pipeline_id: + raise ValueError( + f"The retriever tree of session {session_id} reaches another " + "session's pipeline." + ) + + def _live_leaves(self, session_id: int, bridge_ids: set[int]) -> _LiveLeaves: + """Validate the leaves of a live tree and read its chunk set and models. + + Every bridge must be either a leaf with a fitted detail or a composite + with children. The leaves must all read one chunk set, owned by the + session. Parameters ---------- session_id : int - The generative session whose indexes are discarded. - commit : bool - When ``False`` the caller owns the transaction and commits it. + bridge_ids : set[int] + The bridges of the live tree. + + Returns + ------- + _LiveLeaves + The live chunk set id and the embedding models of the dense leaves. + + Raises + ------ + ValueError + If a bridge is neither a leaf nor a composite, or the leaves do not + read exactly one chunk set owned by the session. """ - chunk_set_ids = [ - row[0] - for row in self.db.query(RAGChunkSet.id) - .filter(RAGChunkSet.session_id == session_id) + ids = list(bridge_ids) + sparse = ( + self.db.query(RAGSparseRetriever) + .filter(RAGSparseRetriever.bridge_id.in_(ids)) .all() - ] - for chunk_set_id in chunk_set_ids: - self._invalidate_chunk_set(chunk_set_id) - if commit: - self.db.commit() + ) + dense = ( + self.db.query(RAGDenseRetriever) + .filter(RAGDenseRetriever.bridge_id.in_(ids)) + .all() + ) + leaves = sparse + dense + leaf_ids = {detail.bridge_id for detail in leaves} + composite_ids: set[int] = set() + for bridge_id in bridge_ids: + if self._retriever_db.child_ids_in_order(bridge_id): + composite_ids.add(bridge_id) + if bridge_ids - leaf_ids - composite_ids: + raise ValueError( + f"A retriever of session {session_id} has neither a fitted detail " + "nor children." + ) + chunk_set_id = self._owned_chunk_set( + session_id, {detail.chunk_set_id for detail in leaves} + ) + return _LiveLeaves( + chunk_set_id=chunk_set_id, + dense_model_ids=frozenset(detail.embedding_model_id for detail in dense), + ) - def invalidate_legacy_artifacts(self, *, commit: bool = True) -> int: - """Delete the chunk sets that have no owning session. + def _owned_chunk_set(self, session_id: int, chunk_set_ids: set[int]) -> int: + """Return the one chunk set the live retrievers read, if the session owns it. - Migration d8f3a1c6e2b9 detaches every chunk set that existed before - chunks became Arrow documents, and older ones indexed rows of the - legacy ``document`` table. None of them can be used again, so this - removes their rows and folders at startup. + Parameters + ---------- + session_id : int + chunk_set_ids : set[int] + The chunk sets read by the live leaves. + + Returns + ------- + int + The chunk set id. + + Raises + ------ + ValueError + If the leaves read other than exactly one chunk set, or that chunk + set is not owned by the session. + """ + if len(chunk_set_ids) != 1: + raise ValueError( + f"The live retriever of session {session_id} must read exactly one " + f"chunk set, found {len(chunk_set_ids)}." + ) + chunk_set_id = next(iter(chunk_set_ids)) + owner = self.db.get(RAGChunkSet, chunk_set_id) + if owner is None or owner.session_id != session_id: + raise ValueError( + f"Chunk set {chunk_set_id} of the live retriever is not owned by " + f"session {session_id}." + ) + return chunk_set_id + + def _invalidate_stale_chunk_sets( + self, session_id: int, live_chunk_set_id: int + ) -> int: + """Invalidate every chunk set of the session except the live one. Parameters ---------- - commit : bool - When ``False`` the caller owns the transaction and commits it. + session_id : int + live_chunk_set_id : int + The chunk set the live retriever reads, which is kept. Returns ------- int - Number of chunk sets deleted. + Number of chunk sets invalidated. """ - chunk_set_ids = [ - row[0] - for row in self.db.query(RAGChunkSet.id) - .filter(RAGChunkSet.session_id.is_(None)) - .all() - ] - for chunk_set_id in chunk_set_ids: + rows = self.db.query(RAGChunkSet.id).filter( + RAGChunkSet.session_id == session_id, + RAGChunkSet.id != live_chunk_set_id, + ) + stale_ids: list[int] = [] + for row in rows.all(): + stale_ids.append(row[0]) + for chunk_set_id in stale_ids: self._invalidate_chunk_set(chunk_set_id) - if commit: - self.db.commit() - return len(chunk_set_ids) + return len(stale_ids) - def _invalidate_chunk_set(self, chunk_set_id: int) -> None: - """Delete one chunk set and everything fitted on it. + def _release_stale_bridges(self, live: _LiveIndex) -> _BridgeRelease: + """Release every pipeline tree other than the live one. - Removes the composite retrievers built over its retrievers, its sparse - and dense retrievers, its embedding matrices (and their embedding model - once nothing else uses it) and the chunk set itself, whose chunks and - membership rows go with it. Storage folders are content-addressed, so a - folder is only queued with ``remove_after_commit`` once no other row - still references it. + The roots of the other trees are torn down top-down, so composites nested + at any depth go with their children. The live root is kept, and with it + every bridge the live tree reaches. A dense detail is deleted, but its + embedding model is left to the caller to release. Parameters ---------- - chunk_set_id : int - The chunk set to delete. + live : _LiveIndex + The validated live index, whose tree must survive. + + Returns + ------- + _BridgeRelease + The number of bridges released, and the embedding models their + dense details used. """ - document_ids = [ - row[0] - for row in self.db.query(RAGChunkSetDocument.document_id) - .filter(RAGChunkSetDocument.chunk_set_id == chunk_set_id) - .all() - ] - sparse_links = ( - self.db.query(RAGSparseRetriever, RAGRetriever) - .join(RAGRetriever, RAGSparseRetriever.bridge_id == RAGRetriever.id) - .filter(RAGSparseRetriever.chunk_set_id == chunk_set_id) - .all() + roots = self._other_roots(live.pipeline_id, [live.root_id]) + return self._release_bridge_trees(roots, [live.root_id], frozenset()) + + def _drop_sparse_detail( + self, detail: RAGSparseRetriever, stale_sparse_ids: Sequence[int] + ) -> None: + """Delete a stale sparse detail and its folder when nothing else uses it. + + Parameters + ---------- + detail : RAGSparseRetriever + The stale detail being deleted. + stale_sparse_ids : Sequence[int] + Every stale sparse detail, which must not count as a live reference. + """ + if not self._sparse_folder_in_use( + detail.storage_folder, exclude_ids=stale_sparse_ids + ): + self._queue_removal(detail.storage_folder) + self.db.delete(detail) + + def _release_unused_matrices( + self, live: _LiveIndex, candidate_models: frozenset[int] + ) -> _MatrixRelease: + """Release live-chunk-set matrices no live dense retriever needs. + + Parameters + ---------- + live : _LiveIndex + The validated live index. + candidate_models : frozenset[int] + Embedding models that the release may have left unused. The models + of the matrices released here are added to them. + + Returns + ------- + _MatrixRelease + Matrices released, and embedding models deleted. + """ + stale = self._stale_matrices(live) + stale_ids = [matrix.id for matrix in stale] + model_ids = set(candidate_models) + for matrix in stale: + model_ids.add(matrix.embedding_model_id) + if not self._embedding_folder_in_use( + matrix.storage_folder, exclude_ids=stale_ids + ): + self._queue_removal(matrix.storage_folder) + self.db.delete(matrix) + self.db.flush() + return _MatrixRelease( + matrices=len(stale), models=self._release_unused_models(model_ids) ) - dense_links = ( - self.db.query(RAGDenseRetriever, RAGRetriever) - .join(RAGRetriever, RAGDenseRetriever.bridge_id == RAGRetriever.id) - .filter(RAGDenseRetriever.chunk_set_id == chunk_set_id) + + def _stale_matrices(self, live: _LiveIndex) -> list[RAGEmbeddingMatrix]: + """List the matrices of the live chunk set that no live dense retriever uses. + + Parameters + ---------- + live : _LiveIndex + The validated live index. + + Returns + ------- + list[RAGEmbeddingMatrix] + """ + stale: list[RAGEmbeddingMatrix] = [] + matrices = ( + self.db.query(RAGEmbeddingMatrix) + .filter(RAGEmbeddingMatrix.chunk_set_id == live.chunk_set_id) .all() ) + for matrix in matrices: + if matrix.embedding_model_id not in live.dense_model_ids: + stale.append(matrix) + return stale - child_bridge_ids = {bridge.id for _, bridge in sparse_links + dense_links} - if child_bridge_ids: - parent_ids = { - link.parent_id - for link in self.db.query(RAGRetrieverChild) - .filter(RAGRetrieverChild.child_id.in_(child_bridge_ids)) - .all() - } - for parent_id in parent_ids: - parent = self.db.get(RAGRetriever, parent_id) - if parent is not None: - self.db.delete(parent) + def _release_unused_models(self, model_ids: set[int]) -> int: + """Delete each given embedding model that no row references any more. - sparse_ids = [detail.id for detail, _bridge in sparse_links] + Parameters + ---------- + model_ids : set[int] + Candidate embedding model ids. - for sparse_detail, bridge in sparse_links: - if not self._sparse_folder_in_use( - sparse_detail.storage_folder, exclude_ids=sparse_ids - ): - remove_after_commit(self.db, sparse_detail.storage_folder) - self.db.delete(sparse_detail) - self.db.delete(bridge) + Returns + ------- + int + Number of embedding models deleted. + """ + removed = 0 + for model_id in sorted(model_ids): + if self._embedding_model_in_use(model_id): + continue + model = self.db.get(RAGEmbeddingModel, model_id) + if model is not None: + self.db.delete(model) + removed += 1 + self.db.flush() + return removed - dense_matrices: dict[int, list[RAGEmbeddingMatrix]] = {} - for dense_detail, _bridge in dense_links: - dense_matrices[dense_detail.id] = ( - self.db.query(RAGEmbeddingMatrix) - .filter( - RAGEmbeddingMatrix.chunk_set_id == chunk_set_id, - RAGEmbeddingMatrix.embedding_model_id - == dense_detail.embedding_model_id, - RAGEmbeddingMatrix.document_id.in_(document_ids), - ) - .all() + +@dataclass(frozen=True) +class IndexFootprint: + """The chunk sets and retriever bridges a session holds at one moment. + + Attributes + ---------- + chunk_set_ids : frozenset[int] + Chunk sets owned by the session. + bridge_ids : frozenset[int] + Retriever bridges of the session's pipeline, composites and leaves alike. + """ + + chunk_set_ids: frozenset[int] + bridge_ids: frozenset[int] + + +def capture_index_footprint(db: Session, session_id: int) -> IndexFootprint: + """Record which chunk sets and bridges a session holds right now. + + A build adds chunk sets and bridges and a cleanup removes them, so two + footprints taken around a build differ exactly when the build created + something new. A build that reuses every row leaves the footprint equal. + + Parameters + ---------- + db : Session + SQLAlchemy session. + session_id : int + The generative session whose rows are counted. + + Returns + ------- + IndexFootprint + The session's chunk set ids and its pipeline's bridge ids. + """ + chunk_set_rows = ( + db.query(RAGChunkSet.id).filter(RAGChunkSet.session_id == session_id).all() + ) + chunk_set_ids: set[int] = set() + for row in chunk_set_rows: + chunk_set_ids.add(row[0]) + bridge_ids: set[int] = set() + pipeline_row = db.query(RAGPipeline.id).filter_by(session_id=session_id).first() + if pipeline_row is not None: + bridge_rows = ( + db.query(RAGRetriever.id).filter( + RAGRetriever.pipeline_id == pipeline_row[0] ) - doomed_matrix_ids = [ - matrix.id for matrices in dense_matrices.values() for matrix in matrices - ] - - for dense_detail, bridge in dense_links: - embedding_model_id = dense_detail.embedding_model_id - for matrix in dense_matrices[dense_detail.id]: - if not self._embedding_folder_in_use( - matrix.storage_folder, exclude_ids=doomed_matrix_ids - ): - remove_after_commit(self.db, matrix.storage_folder) - self.db.delete(matrix) - if not self._embedding_model_in_use( - embedding_model_id, exclude_dense_retriever_id=dense_detail.id - ): - embedding_model = self.db.get(RAGEmbeddingModel, embedding_model_id) - if embedding_model is not None: - self.db.delete(embedding_model) - self.db.delete(dense_detail) - self.db.delete(bridge) + ).all() + for row in bridge_rows: + bridge_ids.add(row[0]) + return IndexFootprint( + chunk_set_ids=frozenset(chunk_set_ids), + bridge_ids=frozenset(bridge_ids), + ) - chunk_folders = { - str(Path(row[0]).parent) - for row in self.db.query(RAGChunkSetDocument.path) - .filter( - RAGChunkSetDocument.chunk_set_id == chunk_set_id, - RAGChunkSetDocument.path.isnot(None), + +def has_stale_index_rows(db: Session, session_id: int) -> bool: + """Whether a session holds rows that a cleanup would release, without a rebuild. + + A healthy session has one pipeline root, the live tree, and one chunk set, + the live one. More than one of either is left over from a cleanup that + failed. A build that reused its index would never retry that cleanup, so the + chat path asks this as well. It reads two counts and no tree, so it is cheap + enough to ask on every turn. + + Parameters + ---------- + db : Session + SQLAlchemy session. + session_id : int + The generative session to check. + + Returns + ------- + bool + ``True`` when the session owns more than one chunk set, or its pipeline + has more than one root bridge. + """ + chunk_set_count = ( + db.query(RAGChunkSet.id).filter(RAGChunkSet.session_id == session_id).count() + ) + if chunk_set_count > 1: + return True + pipeline_row = db.query(RAGPipeline.id).filter_by(session_id=session_id).first() + if pipeline_row is None: + return False + linked = select(RAGRetrieverChild.child_id) + root_count = ( + db.query(RAGRetriever.id) + .filter( + RAGRetriever.pipeline_id == pipeline_row[0], + RAGRetriever.id.not_in(linked), + ) + .count() + ) + return root_count > 1 + + +def run_post_index_cleanup( + db: Session, + registry: ComponentRegistry, + session_id: int, + live_root_bridge_id: int | None, + rag_path: str | Path, +) -> None: + """Run the post-index cleanup for a session, without ever failing the caller. + + Called by the index and chat jobs once an index has been built. The index + is already committed and complete by then, so a cleanup failure must not + mark the job failed: the failure is logged with its traceback and the + session is rolled back to a clean state. Cancellation and interpreter + shutdown are ``BaseException``s and still propagate. + + Parameters + ---------- + db : Session + Session the cleanup runs in. + registry : ComponentRegistry + Component registry, passed through to :class:`CleanupService`. + session_id : int + The session that was just indexed. + live_root_bridge_id : int | None + Bridge id of the root of the retriever the index built. ``None`` is + refused inside the guarded path, so it is logged rather than raised. + rag_path : str | Path + The RAG storage root (``RAG_PATH``). Removals are confined to it. + """ + try: + if live_root_bridge_id is None: + raise ValueError( + f"Session {session_id} has no live root bridge to clean up after; " + "the index is kept and nothing is released." ) - .all() - } - for folder in chunk_folders: - remove_after_commit(self.db, folder) - chunk_set = self.db.get(RAGChunkSet, chunk_set_id) - if chunk_set is not None: - self.db.delete(chunk_set) + summary = CleanupService(db, registry, rag_path=rag_path).cleanup_after_reindex( + session_id, live_root_bridge_id + ) + except Exception: + db.rollback() + log.exception( + "Post-index cleanup failed for session %d; the index is kept.", session_id + ) + return + log.debug( + "Post-index cleanup of session %d: %s", + session_id, + summary, + ) diff --git a/DashAI/back/services/RAG/embedding_storage_service.py b/DashAI/back/services/RAG/embedding_storage_service.py index d5e3eb900..4ceef5924 100644 --- a/DashAI/back/services/RAG/embedding_storage_service.py +++ b/DashAI/back/services/RAG/embedding_storage_service.py @@ -11,10 +11,10 @@ from DashAI.back.dependencies.database.models import RAGEmbeddingMatrix from DashAI.back.models.RAG.exceptions import RAGEmbeddingLoadError from DashAI.back.services.RAG.retriever_db_service import RetrieverDBService +from DashAI.back.services.RAG.storage_layout import EMBEDDINGS_DIRNAME logger = logging.getLogger(__name__) -EMBEDDINGS_DIRNAME = "embeddings" EMBEDDINGS_FILENAME = "embeddings.npy" diff --git a/DashAI/back/services/RAG/retriever_db_service.py b/DashAI/back/services/RAG/retriever_db_service.py index 33b804383..00fa2b032 100644 --- a/DashAI/back/services/RAG/retriever_db_service.py +++ b/DashAI/back/services/RAG/retriever_db_service.py @@ -343,6 +343,82 @@ def save_composite( raise return bridge_record + def find_composite( + self, + class_name: str, + pipeline_id: int, + child_bridge_ids: List[int], + ) -> Optional[RetrieverDBModel]: + """Find the composite bridge of a pipeline over these children, in order. + + A composite matches when its class and pipeline are the same and its + child links, read in ``child_order``, name exactly ``child_bridge_ids``. + The oldest such bridge is returned. + + Parameters + ---------- + class_name : str + "SequentialRetriever" or "ParallelRetriever". + pipeline_id : int + Owning pipeline. + child_bridge_ids : list[int] + Ordered list of child bridge ids (RAG_retriever.id). Must not be + empty: a composite always has at least one child, and an empty list + would otherwise match a childless bridge. + + Returns + ------- + RetrieverDBModel or None + The matching bridge record, or ``None`` when none exists. + + Raises + ------ + ValueError + If *child_bridge_ids* is empty. + """ + wanted = list(child_bridge_ids) + if not wanted: + raise ValueError( + "find_composite needs at least one child bridge id to match." + ) + candidates = ( + self.db.query(RetrieverDBModel) + .filter_by(class_name=class_name, pipeline_id=pipeline_id) + .order_by(RetrieverDBModel.id) + .all() + ) + for candidate in candidates: + if self.child_ids_in_order(candidate.id) == wanted: + return candidate + return None + + def child_ids_in_order(self, parent_id: int) -> List[int]: + """List the child bridge ids of a composite, in ``child_order``. + + A link may name a bridge that no longer exists, so callers must not + assume that every returned id is still a bridge. + + Parameters + ---------- + parent_id : int + The composite bridge id. + + Returns + ------- + list[int] + Child bridge ids in their stored order. + """ + links = ( + self.db.query(RAGRetrieverChild) + .filter_by(parent_id=parent_id) + .order_by(RAGRetrieverChild.child_order) + .all() + ) + child_ids: List[int] = [] + for link in links: + child_ids.append(link.child_id) + return child_ids + # ── Embedding model / matrix ─────────────────────────────────────── def find_or_create_embedding_model( diff --git a/DashAI/back/services/RAG/retriever_setup_service.py b/DashAI/back/services/RAG/retriever_setup_service.py index 9f188c65e..a58aa75b4 100644 --- a/DashAI/back/services/RAG/retriever_setup_service.py +++ b/DashAI/back/services/RAG/retriever_setup_service.py @@ -21,6 +21,7 @@ from sqlalchemy.orm import Session from DashAI.back.core.schema_fields.utils import normalize_payload +from DashAI.back.dependencies.database.models import RAGRetriever from DashAI.back.dependencies.registry.component_registry import ComponentRegistry from DashAI.back.models.RAG.documents.chunk import Chunk from DashAI.back.models.RAG.documents.source_document import SourceDocument @@ -54,6 +55,10 @@ from DashAI.back.services.RAG.embedding_storage_service import EmbeddingStorageService from DashAI.back.services.RAG.retrieval_llm_service import RetrievalLLMService from DashAI.back.services.RAG.retriever_db_service import RetrieverDBService +from DashAI.back.services.RAG.storage_layout import ( + EMBEDDINGS_DIRNAME, + SPARSE_RETRIEVERS_DIRNAME, +) from DashAI.back.services.RAG.utils import build_corpus_content_hash log = logging.getLogger(__name__) @@ -80,9 +85,11 @@ class RetrieverSetupService: 2. Initialization — heavy I/O (embeddings, similarity matrices). 3. Persistence — save to DB (bridge records, sub-table rows). - **Composite retrievers** are never cached in the DB. They are always - reconstructed fresh because they are lightweight to build (their - children are individually cached). + **Composite retrievers** are never cached in the DB. Their live object is + always reconstructed fresh because it is lightweight to build (their + children are individually cached). Their bridge row is reused when the same + children are wired again in the same order, so a rebuild with an unchanged + composite creates no new root. """ def __init__( @@ -238,20 +245,47 @@ def _setup_composite( ) model.inject_infra(self._env_RAG_path, self._chunks, None, self._documents) + bridge = self._composite_bridge( + model_class.__name__, [c.db_record_id for c in children] + ) + model.set_id(bridge.id) + return RetrieverSetupResult(db_record_id=bridge.id, model=model) + + def _composite_bridge( + self, class_name: str, child_bridge_ids: list[int] + ) -> RAGRetriever: + """Return the composite bridge over these children, creating it if absent. + + The bridge is matched by class, pipeline and the ordered child bridge + ids. Creating a new root on every setup would make an unchanged index + look rebuilt, so the existing root is reused whenever there is one. + + Args: + class_name: The composite class name. + child_bridge_ids: Ordered bridge ids of the composite's children. + + Returns: + The existing or newly saved composite bridge record. + + Raises: + SQLAlchemyError: If the lookup or the save fails. + """ + existing = self._db_service.find_composite( + class_name, self._pipeline_id, child_bridge_ids + ) + if existing is not None: + return existing try: - bridge = self._db_service.save_composite( - model_class.__name__, + return self._db_service.save_composite( + class_name, self._pipeline_id, - [c.db_record_id for c in children], + child_bridge_ids, commit=True, ) except SQLAlchemyError: log.exception("Failed to save composite retriever.") raise - model.set_id(bridge.id) - return RetrieverSetupResult(db_record_id=bridge.id, model=model) - def _setup_child(self, child_config: dict) -> RetrieverSetupResult: if "component" not in child_config or "params" not in child_config: raise RAGRetrieverMissingParameterError( @@ -495,7 +529,7 @@ def _build_sparse_persistence_for( )[:16] storage_folder = os.path.join( self._env_RAG_path, - "sparse_retrievers", + SPARSE_RETRIEVERS_DIRNAME, f"sparse_retriever_id-{identity}", ) return SparsePersistence(model_dir=storage_folder) @@ -535,7 +569,7 @@ def _build_dense_persistence(self, embedding_model_id: int) -> DensePersistence: embedding_model_id, ) matrix_dirs[doc_id] = self._existing_matrix_dir( - os.path.join(self._env_RAG_path, "embeddings", folder), + os.path.join(self._env_RAG_path, EMBEDDINGS_DIRNAME, folder), doc_id, embedding_model_id, ) @@ -567,7 +601,7 @@ def _existing_matrix_dir( return content_dir legacy_dir = os.path.join( self._env_RAG_path, - "embeddings", + EMBEDDINGS_DIRNAME, f"doc_id-{doc_id}__chunk_set_id-{self._chunk_set_id}__" f"embedding_model_id-{embedding_model_id}", ) diff --git a/DashAI/back/services/RAG/session_configuration_service.py b/DashAI/back/services/RAG/session_configuration_service.py index 4bff96b8f..4d4982fdc 100644 --- a/DashAI/back/services/RAG/session_configuration_service.py +++ b/DashAI/back/services/RAG/session_configuration_service.py @@ -11,7 +11,6 @@ Everything it returns is read-only and derived; nothing here mutates a session. """ -import logging from typing import Any, Dict, List, Optional from DashAI.back.core.utils import MultilingualString @@ -24,6 +23,7 @@ RAG_PARAM_QUERY_TRANSFORMATION, RAG_PARAM_RETRIEVER_MODEL, ) +from DashAI.back.models.RAG.retrievers.ref_utils import COMPONENT_KEY, PARAMS_KEY from DashAI.back.services.RAG import chunking_presets, retriever_presets from DashAI.back.services.RAG.prompt_service import PromptService from DashAI.back.services.RAG.session_defaults_service import ( @@ -31,8 +31,6 @@ RAG_MAX_TOKENS, ) -log = logging.getLogger(__name__) - #: Characters per token, for turning prompt text into a token estimate. CHARS_PER_TOKEN = 4 @@ -75,6 +73,111 @@ } +class RAGSessionNotFoundError(ValueError): + """Raised when the RAG session whose configuration is requested does not exist.""" + + +def _reference_component(ref: Dict[str, Any]) -> str: + """Return the component name of a reference, or ``""`` for an empty one. + + Only an empty reference (``{}``) describes as a custom configuration, so it + has the empty name. Any non-empty reference must name its component with a + string. One that does not is malformed, and it raises rather than being read + as an empty component. + + Parameters + ---------- + ref : Dict[str, Any] + A ``{"component", "params"}`` reference, or an empty ``{}``. + + Returns + ------- + str + The component name, or ``""`` for an empty reference. + + Raises + ------ + ValueError + If the reference is not empty and its component is missing or not a + string. + """ + if not ref: + return "" + component = ref.get(COMPONENT_KEY) + if not isinstance(component, str): + raise ValueError( + f"Component reference with keys {sorted(ref)} must name its " + f"{COMPONENT_KEY!r} as a string." + ) + return component + + +def _reference_params(ref: Dict[str, Any]) -> Dict[str, Any]: + """Return the ``params`` object of a component reference. + + An empty reference names no component, so it has no parameters. A reference + that names a component must carry a ``params`` object. One that does not is + malformed, and it raises rather than being read as an empty configuration. + + Parameters + ---------- + ref : Dict[str, Any] + A ``{"component", "params"}`` reference, or an empty one. + + Returns + ------- + Dict[str, Any] + The parameters, or an empty dict for an empty reference. + + Raises + ------ + ValueError + If the reference names a component but its ``params`` is not an object. + """ + if not ref: + return {} + params = ref.get(PARAMS_KEY) + if not isinstance(params, dict): + raise ValueError( + f"Component reference {ref.get(COMPONENT_KEY)!r} has no params object." + ) + return params + + +def _prompt_template(ref: Dict[str, Any]) -> str: + """Return the template text of a prompt reference, or ``""`` for an empty one. + + An empty reference (``{}``) has no prompt, so it contributes no template + text. A reference that names a component must carry its template as a + string. One that does not is malformed, and it raises rather than being + priced as an empty prompt. + + Parameters + ---------- + ref : Dict[str, Any] + A ``{"component", "params"}`` prompt reference, or an empty ``{}``. + + Returns + ------- + str + The template text, or ``""`` for an empty reference. + + Raises + ------ + ValueError + If the reference names a component but its ``template`` is missing or + not a string. + """ + if not ref: + return "" + template = _reference_params(ref).get("template") + if not isinstance(template, str): + raise ValueError( + f"Prompt reference {_reference_component(ref)!r} has no string template." + ) + return template + + class SessionConfigurationService: """Resolves a stored RAG configuration into labels the UI can render.""" @@ -110,12 +213,16 @@ def get_configuration(self, session_id: int) -> Dict[str, Any]: Raises ------ - ValueError + RAGSessionNotFoundError If the session does not exist. + ValueError + If the stored configuration is malformed. """ session = self._db.get(GenerativeSession, session_id) if session is None: - raise ValueError(f"Generative session {session_id} does not exist.") + raise RAGSessionNotFoundError( + f"Generative session {session_id} does not exist." + ) parameters = PromptService( self._db, self._registry @@ -144,9 +251,11 @@ def get_configuration(self, session_id: int) -> Dict[str, Any]: def _describe_chunking(self, ref: Dict[str, Any]) -> Dict[str, Any]: """Describe the chunking component, naming its preset when it has one.""" section = self._describe_component(RAG_PARAM_CHUNKING_MODEL, ref) - component = ref.get("component") or "" - params = ref.get("params") or {} - preset_key = chunking_presets.match_preset_key(component, params) + component = _reference_component(ref) + params = _reference_params(ref) + preset_key = chunking_presets.match_preset_key( + component, params, self._registry + ) section["preset_key"] = preset_key section["preset_display_name"] = self._chunking_preset_name(preset_key) chunk_size = params.get("chunk_size") @@ -157,15 +266,11 @@ def _describe_chunking(self, ref: Dict[str, Any]) -> Dict[str, Any]: def _describe_retriever(self, ref: Dict[str, Any]) -> Dict[str, Any]: """Describe the retriever component, naming its preset when it has one.""" section = self._describe_component(RAG_PARAM_RETRIEVER_MODEL, ref) - component = ref.get("component") or "" - params = ref.get("params") or {} - preset_key: Optional[str] = None - try: - preset_key = retriever_presets.match_preset_key( - component, params, self._registry - ) - except Exception: # pragma: no cover - a stale preset must not 500 - log.exception("Retriever preset matching failed for %s", component) + component = _reference_component(ref) + params = _reference_params(ref) + preset_key = retriever_presets.match_preset_key( + component, params, self._registry + ) section["preset_key"] = preset_key section["preset_display_name"] = self._retriever_preset_name(preset_key) section["top_k"] = retriever_presets.effective_top_k(component, params) @@ -183,7 +288,7 @@ def _describe_generation(self, ref: Dict[str, Any]) -> Dict[str, Any]: guessing from the class name. """ section = self._describe_component(RAG_PARAM_GENERATION_MODEL, ref) - component = ref.get("component") or "" + component = _reference_component(ref) entry = self._registry_entry(component) if entry is None: section["requires_download"] = False @@ -234,8 +339,7 @@ def _describe_transformation(self, ref: Dict[str, Any]) -> Dict[str, Any]: runs. Multilingual values are returned as :class:`MultilingualString`; the caller localizes them. """ - enabled = isinstance(ref, dict) and bool(ref.get("component")) - if not enabled: + if not _reference_component(ref): return { "section_name": _SECTION_NAMES[RAG_PARAM_QUERY_TRANSFORMATION], "component": None, @@ -265,8 +369,8 @@ def _registry_entry(self, component: str) -> Optional[Dict[str, Any]]: def _describe_component(self, key: str, ref: Dict[str, Any]) -> Dict[str, Any]: """Build the common part of a section: names, description, parameters.""" - component = ref.get("component") or "" - params = ref.get("params") or {} + component = _reference_component(ref) + params = _reference_params(ref) entry = self._registry_entry(component) if entry is None: @@ -308,7 +412,7 @@ def _describe_params( "label": prop.get("title") or name, "description": prop.get("description"), "value": value, - "is_component": isinstance(value, dict) and "component" in value, + "is_component": isinstance(value, dict) and COMPONENT_KEY in value, } ) return described @@ -365,11 +469,11 @@ def _chunk_unit(self, component: str) -> str: def _chunk_tokens(self, chunking: Dict[str, Any]) -> int: """Return the token cost of a single retrieved chunk.""" - params = chunking.get("params") or {} + params = _reference_params(chunking) chunk_size = params.get("chunk_size") if not isinstance(chunk_size, int): return 0 - if self._chunk_unit(chunking.get("component") or "") == "tokens": + if self._chunk_unit(_reference_component(chunking)) == "tokens": return chunk_size return chunking_presets.estimate_tokens(chunk_size) @@ -392,7 +496,7 @@ def _context_budget( text of every chunk it covers, so retrieve-then-expand costs more context than its ``top_k`` alone suggests. """ - generation_params = generation.get("params") or {} + generation_params = _reference_params(generation) context_window = generation_params.get("context_window") if not isinstance(context_window, int): context_window = RAG_CONTEXT_WINDOW @@ -401,12 +505,11 @@ def _context_budget( max_tokens = RAG_MAX_TOKENS chunk_count = retriever_presets.effective_chunk_count( - retriever.get("component") or "", retriever.get("params") or {} + _reference_component(retriever), _reference_params(retriever) ) used_by_chunks = self._chunk_tokens(chunking) * chunk_count - template = (prompt.get("params") or {}).get("template") or "" - used_by_prompt = len(template) // CHARS_PER_TOKEN + used_by_prompt = len(_prompt_template(prompt)) // CHARS_PER_TOKEN available = context_window - used_by_chunks - used_by_prompt - max_tokens return { diff --git a/DashAI/back/services/RAG/session_params.py b/DashAI/back/services/RAG/session_params.py new file mode 100644 index 000000000..afb0c97d3 --- /dev/null +++ b/DashAI/back/services/RAG/session_params.py @@ -0,0 +1,35 @@ +"""Whitelist filtering of a RAG session's stored parameters. + +A session stores whatever its client sent, so the parameters can carry keys the +pipeline does not understand. Each job keeps only the keys its own stage uses. +""" + +from collections.abc import Collection, Mapping +from typing import Any + + +def filter_pipeline_params( + raw_params: Mapping[str, Any], allowed_keys: Collection[str] +) -> dict[str, Any]: + """Keep only the session parameters that a pipeline stage accepts. + + Parameters + ---------- + raw_params : Mapping[str, Any] + The session parameters, with prompts already materialized. + allowed_keys : Collection[str] + The key names the stage accepts. Each caller passes its own set: the + chat job also admits the optional query transformation stage, while the + index job does not. + + Returns + ------- + dict[str, Any] + A new mapping holding the entries of *raw_params* whose keys are allowed. + """ + allowed = frozenset(allowed_keys) + filtered: dict[str, Any] = {} + for key, value in raw_params.items(): + if key in allowed: + filtered[key] = value + return filtered diff --git a/DashAI/back/services/RAG/storage_layout.py b/DashAI/back/services/RAG/storage_layout.py new file mode 100644 index 000000000..4c2ad8925 --- /dev/null +++ b/DashAI/back/services/RAG/storage_layout.py @@ -0,0 +1,14 @@ +"""Names of the sub-folders of the RAG storage root. + +Every module that writes or reads a fitted artifact folder imports its name +from here, so the layout is spelled out in one place. +""" + +#: Sub-folder that holds the fitted sparse retrievers, one folder per fit. +SPARSE_RETRIEVERS_DIRNAME = "sparse_retrievers" + +#: Sub-folder that holds the embedding matrices, one folder per document and model. +EMBEDDINGS_DIRNAME = "embeddings" + +#: Sub-folder that holds the chunk sets, one folder per chunk set and document. +CHUNK_SETS_DIRNAME = "chunk_sets" diff --git a/tests/back/RAG/test_RAG_session_configuration_api.py b/tests/back/RAG/test_RAG_session_configuration_api.py index f1fd1eea0..6252af8aa 100644 --- a/tests/back/RAG/test_RAG_session_configuration_api.py +++ b/tests/back/RAG/test_RAG_session_configuration_api.py @@ -57,9 +57,9 @@ def register_stub_llm(client: TestClient) -> None: @pytest.fixture -def written_documents() -> list: +def written_documents() -> list[str]: """Collect the document files written by a test, and clean them up.""" - paths: list = [] + paths: list[str] = [] yield paths for path in paths: with contextlib.suppress(OSError): @@ -135,7 +135,7 @@ def _run_one_chat_turn(client: TestClient, session_id: int) -> None: def test_configuration_never_exposes_class_names( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): session_id, _ = _create_minimal_session( client, "config_no_class_names", written_documents @@ -155,7 +155,7 @@ def test_configuration_never_exposes_class_names( def test_configuration_labels_every_parameter( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): session_id, _ = _create_minimal_session(client, "config_labels", written_documents) data = client.get(f"/api/v1/rag/sessions/{session_id}/configuration").json() @@ -167,7 +167,7 @@ def test_configuration_labels_every_parameter( def test_configuration_names_the_matching_presets( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): session_id, _ = _create_minimal_session(client, "config_presets", written_documents) data = client.get(f"/api/v1/rag/sessions/{session_id}/configuration").json() @@ -194,7 +194,7 @@ def test_configuration_is_localized(client: TestClient, written_documents: list) def test_configuration_reports_the_context_budget( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): session_id, _ = _create_minimal_session(client, "config_budget", written_documents) budget = client.get(f"/api/v1/rag/sessions/{session_id}/configuration").json()[ @@ -215,7 +215,7 @@ def test_configuration_reports_the_context_budget( def test_default_session_context_budget_is_usable( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): """A session created from the defaults must actually fit in its context. @@ -238,7 +238,7 @@ def test_default_session_context_budget_is_usable( def test_explicit_context_window_survives_the_override( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): """A context window the caller sets is never overridden.""" base = _base_generation_model() @@ -259,7 +259,7 @@ def test_explicit_context_window_survives_the_override( def test_configuration_survives_an_unregistered_component( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): """An uninstalled plugin must degrade to a raw name, not break the page.""" session_id, _ = _create_minimal_session(client, "config_unknown", written_documents) @@ -293,6 +293,28 @@ def test_configuration_404s_for_an_unknown_session(client: TestClient): assert client.get("/api/v1/rag/sessions/999999/configuration").status_code == 404 +def test_configuration_422s_for_malformed_stored_data( + client: TestClient, written_documents: list[str] +): + """Malformed stored data is an invalid session, not a missing one.""" + session_id, _ = _create_minimal_session( + client, "config_malformed", written_documents + ) + + session_factory = client.app.container["session_factory"] + from DashAI.back.dependencies.database.models import GenerativeSession + + with session_factory() as db: + session = db.get(GenerativeSession, session_id) + parameters = dict(session.parameters) + parameters["retriever_model"] = {"component": "BM25Retriever"} + session.parameters = parameters + db.commit() + + response = client.get(f"/api/v1/rag/sessions/{session_id}/configuration") + assert response.status_code == 422, response.text + + # =================================================================== # Resolved query transformation section # =================================================================== @@ -322,7 +344,7 @@ def _enable_transformation(client: TestClient, session_id: int) -> None: def test_transformation_section_is_disabled_without_the_key( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): session_id, _ = _create_minimal_session( client, "config_transformation_disabled", written_documents @@ -342,7 +364,7 @@ def test_transformation_section_is_disabled_without_the_key( def test_transformation_section_name_is_localized( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): session_id, _ = _create_minimal_session( client, "config_transformation_localized", written_documents @@ -358,7 +380,7 @@ def test_transformation_section_name_is_localized( def test_configuration_describes_an_enabled_transformation( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): session_id, _ = _create_minimal_session( client, "config_transformation_enabled", written_documents @@ -382,7 +404,7 @@ def test_configuration_describes_an_enabled_transformation( def test_configuration_survives_an_unregistered_transformer( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): """A stale transformer reference must degrade, not break the page.""" session_id, _ = _create_minimal_session( @@ -434,7 +456,7 @@ def test_index_status_starts_not_indexed(client: TestClient, written_documents: def test_index_status_becomes_indexed_then_stale( - client: TestClient, written_documents: list + client: TestClient, written_documents: list[str] ): session_id, _ = _create_minimal_session( client, "index_lifecycle", written_documents diff --git a/tests/back/RAG/test_bridge_tree_cleanup.py b/tests/back/RAG/test_bridge_tree_cleanup.py new file mode 100644 index 000000000..08679c0ef --- /dev/null +++ b/tests/back/RAG/test_bridge_tree_cleanup.py @@ -0,0 +1,649 @@ +"""Bridge trees are released top-down, and no composite is left without children. + +Invalidating a chunk set deletes the leaves it fitted, every composite built over +them at any depth, and nothing a surviving tree still references. The post-index +release does the same for the stale trees of a session, and a composite that is +set up again over the same children reuses its existing root. +""" + +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy.orm import Session + +from DashAI.back.dependencies.database.models import ( + RAGChunkSet, + RAGDenseRetriever, + RAGEmbeddingMatrix, + RAGEmbeddingModel, + RAGPipeline, + RAGRetriever, + RAGRetrieverChild, +) +from DashAI.back.services.RAG.cleanup_service import ( + CleanupService, + capture_index_footprint, +) +from DashAI.back.services.RAG.retriever_db_service import RetrieverDBService +from DashAI.back.services.RAG.retriever_setup_service import RetrieverSetupService +from tests.back.RAG.conftest import ( + _insert_data_document, + _insert_rag_session, + bm25_retriever_params, +) +from tests.back.RAG.test_index_cleanup import ( + COMPOSITE_CLASS, + DENSE_CLASS, + EMBEDDINGS_DIR, + LIVE_K1, + SPARSE_CLASS, + SPARSE_DIR, + _build_index, + _chunk_set, + _cleanup, + _composite, + _dense_bridge, + _embedding_model, + _matrix, + _pipeline, + _rag, + _sparse_bridge, +) +from tests.back.RAG.test_retriever_identity import ( + _EMBEDDING_PARAMS, + _cache_corpus, + _dense_params, + _registry, +) + +#: Sparse leaves of the doomed chunk set, fitted with their own weighting. +LEAF_K1 = 1.1 +#: Sparse leaves that a surviving tree shares, which must stay intact. +SHARED_K1 = 1.3 +#: A sparse leaf added to show that the footprint sees a new bridge. +FOOTPRINT_K1 = 1.7 +#: A bridge id that no row uses, for a link that dangles. +MISSING_BRIDGE_ID = 999_998 + + +@dataclass(frozen=True) +class _TwoChunkSets: + """A pipeline with a doomed chunk set, a live chunk set and a sibling root. + + Attributes + ---------- + session_id : int + pipeline_id : int + document_id : int + rag : Path + The RAG storage root the fitted folders live under. + doomed_set : int + The chunk set the tests invalidate. + live_set : int + A chunk set that is not invalidated. + sibling_root : int + A unit sparse root over the live chunk set, which must survive. + sibling_folder : Path + The storage folder of the sibling root. + """ + + session_id: int + pipeline_id: int + document_id: int + rag: Path + doomed_set: int + live_set: int + sibling_root: int + sibling_folder: Path + + +@dataclass(frozen=True) +class _Fitted: + """A fitted leaf, with the storage it owns. + + Attributes + ---------- + bridge_id : int + folder : Path + The sparse folder, or the embedding matrix folder of a dense leaf. + model_id : int | None + The embedding model of a dense leaf; ``None`` for a sparse leaf. + """ + + bridge_id: int + folder: Path + model_id: int | None + + +def _two_chunk_sets(db: Session, tmp_path: Path) -> _TwoChunkSets: + """Build a session with a doomed chunk set, a live one and a sibling root.""" + session = _insert_rag_session(db, f"bridge_{uuid.uuid4().hex[:8]}") + document = _insert_data_document( + db, tmp_path / "docs", f"{uuid.uuid4().hex[:8]}.txt", ["t"] + ) + rag = _rag(tmp_path) + pipeline_id = _pipeline(db, session.id) + doomed_set = _chunk_set(db, session.id, document.id, rag) + live_set = _chunk_set(db, session.id, document.id, rag) + sibling_folder = rag / SPARSE_DIR / "sibling" + sibling_root = _sparse_bridge(db, pipeline_id, live_set, sibling_folder, LIVE_K1) + db.commit() + return _TwoChunkSets( + session_id=session.id, + pipeline_id=pipeline_id, + document_id=document.id, + rag=rag, + doomed_set=doomed_set, + live_set=live_set, + sibling_root=sibling_root, + sibling_folder=sibling_folder, + ) + + +def _sparse_leaf( + db: Session, scenario: _TwoChunkSets, chunk_set_id: int, label: str, k1: float +) -> _Fitted: + """Insert a sparse leaf of a chunk set with its own storage folder. + + ``k1`` must differ between the sparse leaves of one chunk set, because the + table keys a row by its class, parameters and chunk set. + """ + folder = scenario.rag / SPARSE_DIR / label + bridge_id = _sparse_bridge(db, scenario.pipeline_id, chunk_set_id, folder, k1) + return _Fitted(bridge_id=bridge_id, folder=folder, model_id=None) + + +def _dense_leaf( + db: Session, scenario: _TwoChunkSets, chunk_set_id: int, label: str +) -> _Fitted: + """Insert a dense leaf with its embedding model and matrix folder.""" + model_id = _embedding_model(db, label) + folder = scenario.rag / EMBEDDINGS_DIR / label + _matrix(db, scenario.document_id, chunk_set_id, model_id, folder) + bridge_id = _dense_bridge(db, scenario.pipeline_id, chunk_set_id, model_id, label) + return _Fitted(bridge_id=bridge_id, folder=folder, model_id=model_id) + + +def _invalidate(db: Session, scenario: _TwoChunkSets, chunk_set_id: int) -> None: + """Invalidate one chunk set, leaving the commit to the caller.""" + CleanupService(db, rag_path=scenario.rag)._invalidate_chunk_set(chunk_set_id) + + +def _assert_gone(db: Session, bridge_ids: list[int]) -> None: + """Every given bridge row must be deleted.""" + for bridge_id in bridge_ids: + assert db.get(RAGRetriever, bridge_id) is None, f"bridge {bridge_id} remains" + + +def _assert_sound(db: Session) -> None: + """No child link dangles, and every composite still has at least one child.""" + bridge_ids = {row[0] for row in db.query(RAGRetriever.id).all()} + links = db.query(RAGRetrieverChild).all() + dangling = [ + link.id + for link in links + if link.parent_id not in bridge_ids or link.child_id not in bridge_ids + ] + assert dangling == [], "child links point at missing bridges" + parents = {link.parent_id for link in links} + for bridge in db.query(RAGRetriever).all(): + if bridge.sparse_detail is None and bridge.dense_detail is None: + assert bridge.id in parents, f"composite {bridge.id} has no children" + + +def _nest( + db: Session, + scenario: _TwoChunkSets, + innermost: list[int], + levels: int, + label: str, +) -> tuple[list[int], list[int]]: + """Build ``levels`` composites, each wrapping the one below with a new leaf. + + The wrapping leaves belong to the live chunk set, so every composite above + the first has a child that is not invalidated. That is what leaves a + grandparent behind when only its direct parent is released. + + Returns the composite ids, innermost first, and the ids of the wrapping + leaves. + """ + composites = [_composite(db, scenario.pipeline_id, innermost)] + wrapping_leaves: list[int] = [] + for level in range(1, levels): + wrap = _sparse_leaf( + db, + scenario, + scenario.live_set, + f"{label}_wrap_{level}", + LEAF_K1 + level, + ) + wrapping_leaves.append(wrap.bridge_id) + composites.append( + _composite(db, scenario.pipeline_id, [composites[-1], wrap.bridge_id]) + ) + return composites, wrapping_leaves + + +# =================================================================== +# Chunk-set invalidation +# =================================================================== + + +def test_sparse_leaf_alone_is_released_after_commit(orm_db, tmp_path): + """A lone sparse leaf goes with its folder, and the sibling root survives.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + leaf = _sparse_leaf(orm_db, scenario, scenario.doomed_set, "alone", LEAF_K1) + orm_db.commit() + + _invalidate(orm_db, scenario, scenario.doomed_set) + assert leaf.folder.exists(), "folders must outlive the transaction" + orm_db.commit() + + _assert_gone(orm_db, [leaf.bridge_id]) + assert not leaf.folder.exists() + assert orm_db.get(RAGRetriever, scenario.sibling_root) is not None + assert scenario.sibling_folder.exists() + _assert_sound(orm_db) + + +def test_dense_leaf_alone_takes_its_matrix_and_model(orm_db, tmp_path): + """A lone dense leaf goes with its matrix folder and its embedding model.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + leaf = _dense_leaf(orm_db, scenario, scenario.doomed_set, "dense_alone") + orm_db.commit() + + _invalidate(orm_db, scenario, scenario.doomed_set) + orm_db.commit() + + _assert_gone(orm_db, [leaf.bridge_id]) + assert orm_db.get(RAGEmbeddingModel, leaf.model_id) is None + assert not leaf.folder.exists() + assert orm_db.get(RAGRetriever, scenario.sibling_root) is not None + _assert_sound(orm_db) + + +def test_composite_over_leaves_is_released_with_them(orm_db, tmp_path): + """A composite over a sparse and a dense leaf goes with both of them.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + sparse = _sparse_leaf(orm_db, scenario, scenario.doomed_set, "over_sparse", LEAF_K1) + dense = _dense_leaf(orm_db, scenario, scenario.doomed_set, "over_dense") + top = _composite(orm_db, scenario.pipeline_id, [sparse.bridge_id, dense.bridge_id]) + orm_db.commit() + + _invalidate(orm_db, scenario, scenario.doomed_set) + orm_db.commit() + + _assert_gone(orm_db, [top, sparse.bridge_id, dense.bridge_id]) + assert orm_db.get(RAGEmbeddingModel, dense.model_id) is None + assert not sparse.folder.exists() + assert not dense.folder.exists() + assert orm_db.get(RAGRetriever, scenario.sibling_root) is not None + _assert_sound(orm_db) + + +@pytest.mark.parametrize("levels", [2, 3], ids=["two_levels", "three_levels"]) +def test_nested_composites_over_leaves_leave_no_composite_behind( + orm_db, tmp_path, levels +): + """Every composite of a nested chain goes, whatever its depth.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + sparse = _sparse_leaf( + orm_db, scenario, scenario.doomed_set, "nested_sparse", LEAF_K1 + ) + dense = _dense_leaf(orm_db, scenario, scenario.doomed_set, "nested_dense") + composites, wrapping_leaves = _nest( + orm_db, + scenario, + [sparse.bridge_id, dense.bridge_id], + levels, + "nested", + ) + orm_db.commit() + + _invalidate(orm_db, scenario, scenario.doomed_set) + orm_db.commit() + + doomed = composites + wrapping_leaves + [sparse.bridge_id, dense.bridge_id] + _assert_gone(orm_db, doomed) + assert not sparse.folder.exists() + assert orm_db.get(RAGRetriever, scenario.sibling_root) is not None + _assert_sound(orm_db) + + +def test_a_leaf_shared_with_a_surviving_tree_is_kept(orm_db, tmp_path): + """A live-set leaf that a live composite also uses survives the invalidation.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + shared = _sparse_leaf(orm_db, scenario, scenario.live_set, "shared", SHARED_K1) + doomed = _sparse_leaf( + orm_db, scenario, scenario.doomed_set, "shared_doomed", LEAF_K1 + ) + stale_top = _composite( + orm_db, scenario.pipeline_id, [shared.bridge_id, doomed.bridge_id] + ) + live_top = _composite(orm_db, scenario.pipeline_id, [shared.bridge_id]) + orm_db.commit() + + _invalidate(orm_db, scenario, scenario.doomed_set) + orm_db.commit() + + _assert_gone(orm_db, [stale_top, doomed.bridge_id]) + assert orm_db.get(RAGRetriever, shared.bridge_id) is not None + assert shared.folder.exists() + assert orm_db.get(RAGRetriever, live_top) is not None + links = [ + (row.parent_id, row.child_id) + for row in orm_db.query(RAGRetrieverChild).filter_by(parent_id=live_top) + ] + assert links == [(live_top, shared.bridge_id)] + assert orm_db.get(RAGRetriever, scenario.sibling_root) is not None + _assert_sound(orm_db) + + +# =================================================================== +# Post-index release +# =================================================================== + + +@pytest.mark.parametrize("levels", [2, 3], ids=["two_levels", "three_levels"]) +def test_post_index_release_removes_nested_stale_composites(orm_db, tmp_path, levels): + """Stale composites nested over stale leaves go; the live tree keeps its leaves.""" + session = _insert_rag_session(orm_db, f"nested_post_{uuid.uuid4().hex[:6]}") + document = _insert_data_document( + orm_db, tmp_path / "docs", f"{uuid.uuid4().hex[:6]}.txt", ["p"] + ) + index = _build_index(orm_db, tmp_path, session.id, document.id) + stale = [ + _composite( + orm_db, index.pipeline_id, [index.stale_sparse_id, index.stale_dense_id] + ) + ] + for _level in range(1, levels): + stale.append( + _composite(orm_db, index.pipeline_id, [stale[-1], index.live_sparse_id]) + ) + orm_db.commit() + + _cleanup(orm_db, index) + + _assert_gone(orm_db, stale + [index.stale_sparse_id, index.stale_dense_id]) + assert not index.stale_sparse_folder.exists() + assert not index.stale_matrix_folder.exists() + assert orm_db.get(RAGRetriever, index.root_id) is not None + assert orm_db.get(RAGRetriever, index.live_sparse_id) is not None + assert orm_db.get(RAGRetriever, index.live_dense_id) is not None + assert index.live_sparse_folder.exists() + _assert_sound(orm_db) + + +# =================================================================== +# Composite roots are reused by setup +# =================================================================== + + +def _composite_params(child_k1: float) -> dict[str, Any]: + """Parameters of a round-robin composite over one BM25 child.""" + child = {**bm25_retriever_params(), "k1": child_k1} + return { + "merge_strategy": "round_robin", + "children": [{"component": SPARSE_CLASS, "params": child}], + } + + +def _setup_service(db: Session, client: TestClient, tmp_path: Path): + """Insert a session with a chunk set and pipeline, and return a setup service. + + Returns the service and the pipeline id, which scopes the row counts. + """ + session = _insert_rag_session(db, f"reuse_{uuid.uuid4().hex[:6]}") + chunk_set = RAGChunkSet( + signature=uuid.uuid4().hex, parameters={}, session_id=session.id + ) + pipeline = RAGPipeline(session_id=session.id, name="") + db.add_all([chunk_set, pipeline]) + db.commit() + service = RetrieverSetupService( + db, + _registry(client), + str(tmp_path), + _cache_corpus(), + chunk_set.id, + pipeline.id, + "test-chunking", + ) + return service, pipeline.id + + +def _count_bridges(db: Session, pipeline_id: int, class_name: str) -> int: + """Count the bridge rows of one class in one pipeline.""" + return ( + db.query(RAGRetriever) + .filter_by(pipeline_id=pipeline_id, class_name=class_name) + .count() + ) + + +def test_consecutive_setups_of_one_composite_reuse_its_root(orm_db, client, tmp_path): + """Setting up the same composite twice keeps one root and one child bridge.""" + service, pipeline_id = _setup_service(orm_db, client, tmp_path) + first = service.setup(COMPOSITE_CLASS, _composite_params(1.5)) + second = service.setup(COMPOSITE_CLASS, _composite_params(1.5)) + + assert second.db_record_id == first.db_record_id + assert _count_bridges(orm_db, pipeline_id, COMPOSITE_CLASS) == 1 + assert _count_bridges(orm_db, pipeline_id, SPARSE_CLASS) == 1 + + +def test_changing_a_child_creates_a_new_composite_root(orm_db, client, tmp_path): + """A composite over a changed child is a new root; the old one awaits cleanup.""" + service, pipeline_id = _setup_service(orm_db, client, tmp_path) + first = service.setup(COMPOSITE_CLASS, _composite_params(1.5)) + changed = service.setup(COMPOSITE_CLASS, _composite_params(2.0)) + + assert changed.db_record_id != first.db_record_id + assert _count_bridges(orm_db, pipeline_id, COMPOSITE_CLASS) == 2 + assert _count_bridges(orm_db, pipeline_id, SPARSE_CLASS) == 2 + + +# =================================================================== +# Walking and measuring the trees +# =================================================================== + + +def test_tree_walk_lists_a_shared_child_once_and_survives_a_cycle(orm_db, tmp_path): + """A shared child is listed once; a cycle or a dangling link ends the walk.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + shared = _sparse_leaf(orm_db, scenario, scenario.live_set, "walk", SHARED_K1) + left = _composite(orm_db, scenario.pipeline_id, [shared.bridge_id]) + right = _composite(orm_db, scenario.pipeline_id, [shared.bridge_id]) + top = _composite(orm_db, scenario.pipeline_id, [left, right]) + orm_db.add( + RAGRetrieverChild(parent_id=right, child_id=MISSING_BRIDGE_ID, child_order=1) + ) + orm_db.add( + RAGRetrieverChild(parent_id=shared.bridge_id, child_id=top, child_order=0) + ) + orm_db.commit() + + order = CleanupService(orm_db, rag_path=scenario.rag)._tree_order([top]) + + assert order == [top, left, shared.bridge_id, right, MISSING_BRIDGE_ID] + + +def test_footprint_is_unchanged_by_a_reuse_and_moves_on_a_new_bridge(orm_db, tmp_path): + """Footprints match when nothing was added, and differ after a new bridge.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + before = capture_index_footprint(orm_db, scenario.session_id) + + assert capture_index_footprint(orm_db, scenario.session_id) == before + + _sparse_leaf(orm_db, scenario, scenario.live_set, "footprint", FOOTPRINT_K1) + orm_db.commit() + after = capture_index_footprint(orm_db, scenario.session_id) + + assert after != before + assert after.chunk_set_ids == before.chunk_set_ids + assert len(after.bridge_ids) == len(before.bridge_ids) + 1 + + +# =================================================================== +# Session parameter updates release what the old configuration left +# =================================================================== + + +def _dense_composite_params() -> dict[str, Any]: + """Parameters of a round-robin composite over one dense child.""" + child = _dense_params(_EMBEDDING_PARAMS) + return { + "merge_strategy": "round_robin", + "children": [{"component": DENSE_CLASS, "params": child}], + } + + +@pytest.mark.parametrize( + "shared", [False, True], ids=["unshared_model", "shared_model"] +) +def test_composite_switched_to_a_unit_releases_its_dense_leaves( + orm_db, client, tmp_path, shared +): + """Dense leaves of a replaced composite release matrices; a shared model stays.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + label = f"cascade_{shared}" + dense = _dense_leaf(orm_db, scenario, scenario.doomed_set, label) + composite = _composite(orm_db, scenario.pipeline_id, [dense.bridge_id]) + if shared: + other = _insert_rag_session(orm_db, f"sharer_{uuid.uuid4().hex[:8]}") + other_pipeline = _pipeline(orm_db, other.id) + other_set = _chunk_set(orm_db, other.id, scenario.document_id, scenario.rag) + _dense_bridge(orm_db, other_pipeline, other_set, dense.model_id, "sharer") + orm_db.commit() + old_parameters = { + "documents": [], + "retriever_model": { + "component": COMPOSITE_CLASS, + "params": _dense_composite_params(), + }, + } + new_parameters = { + "documents": [], + "retriever_model": { + "component": SPARSE_CLASS, + "params": bm25_retriever_params(), + }, + } + + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + scenario.session_id, old_parameters, new_parameters + ) + + _assert_gone(orm_db, [composite, dense.bridge_id]) + matrices = ( + orm_db.query(RAGEmbeddingMatrix) + .filter_by(chunk_set_id=scenario.doomed_set, embedding_model_id=dense.model_id) + .count() + ) + assert matrices == 0 + assert not dense.folder.exists() + assert (orm_db.get(RAGEmbeddingModel, dense.model_id) is not None) is shared + assert orm_db.get(RAGRetriever, scenario.sibling_root) is not None + _assert_sound(orm_db) + + +def test_unit_cascade_keeps_a_child_of_a_surviving_composite(orm_db, client, tmp_path): + """A unit bridge that a surviving composite still reads is not deleted.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + child = _sparse_leaf(orm_db, scenario, scenario.live_set, "unit_child", SHARED_K1) + survivor = _composite(orm_db, scenario.pipeline_id, [child.bridge_id]) + orm_db.commit() + old_parameters = { + "documents": [], + "retriever_model": { + "component": SPARSE_CLASS, + "params": bm25_retriever_params(), + }, + } + changed = {**bm25_retriever_params(), "k1": 2.5} + new_parameters = { + "documents": [], + "retriever_model": {"component": SPARSE_CLASS, "params": changed}, + } + + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + scenario.session_id, old_parameters, new_parameters + ) + + assert orm_db.get(RAGRetriever, survivor) is not None + assert orm_db.get(RAGRetriever, child.bridge_id) is not None + assert child.folder.exists() + _assert_sound(orm_db) + + +def test_invalidation_releases_a_leaf_behind_a_rootless_cycle(orm_db, tmp_path): + """A leaf that no root reaches is still released with its chunk set.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + other = _insert_rag_session(orm_db, f"cycle_{uuid.uuid4().hex[:8]}") + cycle_pipeline = _pipeline(orm_db, other.id) + folder = scenario.rag / SPARSE_DIR / "cycle_leaf" + leaf_bridge = _sparse_bridge( + orm_db, cycle_pipeline, scenario.doomed_set, folder, LEAF_K1 + ) + first = _composite(orm_db, cycle_pipeline, [leaf_bridge]) + second = _composite(orm_db, cycle_pipeline, [first]) + orm_db.add(RAGRetrieverChild(parent_id=first, child_id=second, child_order=1)) + orm_db.commit() + + _invalidate(orm_db, scenario, scenario.doomed_set) + orm_db.commit() + + _assert_gone(orm_db, [leaf_bridge]) + assert not folder.exists() + assert orm_db.get(RAGRetriever, first) is not None + assert orm_db.get(RAGRetriever, second) is not None + _assert_sound(orm_db) + + +def test_a_bridge_with_a_sparse_and_a_dense_detail_releases_both(orm_db, tmp_path): + """Both details of one bridge go with it, and no detail is left dangling.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + folder = scenario.rag / SPARSE_DIR / "both" + bridge_id = _sparse_bridge( + orm_db, scenario.pipeline_id, scenario.doomed_set, folder, LEAF_K1 + ) + model_id = _embedding_model(orm_db, "both") + matrix_folder = scenario.rag / EMBEDDINGS_DIR / "both" + _matrix(orm_db, scenario.document_id, scenario.doomed_set, model_id, matrix_folder) + dense = RAGDenseRetriever( + bridge_id=bridge_id, + chunk_set_id=scenario.doomed_set, + class_name=DENSE_CLASS, + parameters={"label": "both"}, + embedding_model_id=model_id, + ) + orm_db.add(dense) + orm_db.commit() + dense_id = dense.id + + _invalidate(orm_db, scenario, scenario.doomed_set) + orm_db.commit() + + _assert_gone(orm_db, [bridge_id]) + assert orm_db.get(RAGDenseRetriever, dense_id) is None + assert orm_db.get(RAGEmbeddingModel, model_id) is None + assert not folder.exists() + assert not matrix_folder.exists() + _assert_sound(orm_db) + + +def test_find_composite_refuses_an_empty_child_list(orm_db, tmp_path): + """An empty child list names no composite, so it must not match a childless one.""" + scenario = _two_chunk_sets(orm_db, tmp_path) + _composite(orm_db, scenario.pipeline_id, []) + orm_db.commit() + + with pytest.raises(ValueError, match="child"): + RetrieverDBService(orm_db).find_composite( + COMPOSITE_CLASS, scenario.pipeline_id, [] + ) diff --git a/tests/back/RAG/test_cleanup_session_scope.py b/tests/back/RAG/test_cleanup_session_scope.py index f1e53b553..24fe1c34a 100644 --- a/tests/back/RAG/test_cleanup_session_scope.py +++ b/tests/back/RAG/test_cleanup_session_scope.py @@ -1,6 +1,8 @@ """Index cleanup never leaves the session it was asked to clean.""" +import logging import uuid +from typing import Any from DashAI.back.dependencies.database.models import ( RAGChunkSet, @@ -12,9 +14,33 @@ RAGRetrieverChild, RAGSparseRetriever, ) -from DashAI.back.services.RAG.cleanup_service import CleanupService +from DashAI.back.models.RAG.RAG_constants import RAG_PARAM_RETRIEVER_MODEL +from DashAI.back.services.RAG.cleanup_service import ( + CleanupService, + _retriever_component_name, +) from tests.back.RAG.conftest import _insert_data_document, _insert_rag_session +CLEANUP_LOGGER = "DashAI.back.services.RAG.cleanup_service" + + +def test_a_retriever_reference_without_a_component_is_logged(caplog): + """A retriever reference that names no component yields None, with a warning.""" + with caplog.at_level(logging.WARNING, logger=CLEANUP_LOGGER): + name = _retriever_component_name({RAG_PARAM_RETRIEVER_MODEL: {"params": {}}}) + + assert name is None + assert "no component" in caplog.text + + +def test_a_session_without_a_retriever_is_not_logged(caplog): + """Only a reference that exists but names no component is worth a warning.""" + with caplog.at_level(logging.WARNING, logger=CLEANUP_LOGGER): + name = _retriever_component_name({}) + + assert name is None + assert caplog.text == "" + def _chunk_set_with_sparse_index(db, session_id, document_id, storage) -> int: """Insert a chunk set with one stored chunk folder and a fitted sparse retriever. @@ -159,7 +185,7 @@ def test_composite_cleanup_keeps_a_shared_sparse_folder(orm_db, tmp_path): ) orm_db.commit() - CleanupService(orm_db)._cleanup_composite_retriever( + CleanupService(orm_db)._cleanup_retriever( {"retriever_model": {"component": "ParallelRetriever"}}, first.id ) orm_db.flush() @@ -169,7 +195,7 @@ def test_composite_cleanup_keeps_a_shared_sparse_folder(orm_db, tmp_path): assert storage.exists(), "the second session still references the folder" -def _embedding_matrix_state(db, session_id, document_id, storage) -> list: +def _embedding_matrix_state(db, session_id, document_id, storage) -> list[Any]: """Insert one embedding model and two matrix rows sharing one folder.""" chunk_set = RAGChunkSet( signature=uuid.uuid4().hex, parameters={}, session_id=session_id diff --git a/tests/back/RAG/test_index_cleanup.py b/tests/back/RAG/test_index_cleanup.py new file mode 100644 index 000000000..3617a0e4b --- /dev/null +++ b/tests/back/RAG/test_index_cleanup.py @@ -0,0 +1,1416 @@ +"""Post-index cleanup removes what a session's stale index left behind. + +The cleanup runs after every successful index. It is scoped to one session: +only rows reachable from that session's own pipeline and chunk sets are +candidates, shared folders and embedding models survive while another row still +uses them, malformed input raises before anything is deleted, and a failure +leaves both the database and the disk as they were. Every folder it removes +lies inside the RAG storage root. +""" + +import contextlib +import logging +import os +import subprocess +import uuid +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy.orm import Session + +import DashAI.back.job.RAG_index_job as index_job_module +import DashAI.back.job.RAG_job as rag_job_module +from DashAI.back.core.enums.status import RunStatus +from DashAI.back.dependencies.database.models import ( + GenerativeProcess, + GenerativeSession, + ProcessData, + RAGChunkSet, + RAGChunkSetDocument, + RAGDenseRetriever, + RAGEmbeddingMatrix, + RAGEmbeddingModel, + RAGPipeline, + RAGRetriever, + RAGRetrieverChild, + RAGSparseRetriever, +) +from DashAI.back.job.base_job import JobError +from DashAI.back.job.RAG_index_job import RAGIndexJob +from DashAI.back.job.RAG_job import RAGJob +from DashAI.back.services.RAG import cleanup_service +from DashAI.back.services.RAG.chunking_service import chunk_document_dir +from DashAI.back.services.RAG.cleanup_service import ( + CleanupService, + IndexCleanupSummary, +) +from DashAI.back.services.RAG.setup_service import SetupService +from tests.back.RAG.conftest import ( + _insert_data_document, + _insert_rag_session, + bm25_retriever_params, + rag_session_columns, + write_test_doc_file, +) + +# Fixtures and helpers of the indexing tests, used by the job-level tests below. +from tests.back.RAG.test_RAG_indexing import ( # noqa: F401 + _create_session, + _create_session_with_document, + _register_stub_llm, +) + +# Chat-turn helpers, used by the RAGJob call-site tests below. +from tests.back.RAG.test_RAG_job_completes_flow import ( # noqa: F401 + DOC_TEXT, + StubLLM, + _create_test_document, + _frontend_session_parameters, +) + +SPARSE_CLASS = "BM25Retriever" +DENSE_CLASS = "DenseEmbeddingRetriever" +COMPOSITE_CLASS = "ParallelRetriever" +EMBEDDING_CLASS = "SentenceTransformerEmbedding" +STALE_K1 = 1.2 +LIVE_K1 = 1.5 +# Unusual values, so no other test in this module shares the fitted folders. +OLD_K1 = 1.37 +NEW_K1 = 1.91 +UNKNOWN_BRIDGE_ID = 999_999 +# Storage sub-folders of the RAG root, spelled out here on purpose: the tests +# check the layout the services write, not the constants they import. +SPARSE_DIR = "sparse_retrievers" +EMBEDDINGS_DIR = "embeddings" +CHUNK_SETS_DIR = "chunk_sets" +#: Ways of spelling one existing Windows folder differently. +SPELLINGS = [ + pytest.param("forward_slashes", id="forward_slashes"), + pytest.param("trailing_separator", id="trailing_separator"), + pytest.param( + "drive_case", + id="drive_case", + marks=pytest.mark.skipif(os.name != "nt", reason="Windows drive letters"), + ), +] + + +class _Cancelled(BaseException): + """Stands in for the queue cancelling a running job.""" + + +@dataclass(frozen=True) +class _Counts: + """Row counts of every table the cleanup may touch.""" + + retrievers: int + retriever_children: int + sparse_rows: int + dense_rows: int + matrices: int + models: int + chunk_sets: int + + +@dataclass(frozen=True) +class _Index: + """Ids and folders of one session with a live index and a stale one.""" + + session_id: int + pipeline_id: int + document_id: int + chunk_set_id: int + root_id: int + stale_sparse_id: int + live_sparse_id: int + stale_dense_id: int + live_dense_id: int + stale_model_id: int + live_model_id: int + stale_sparse_folder: Path + live_sparse_folder: Path + stale_matrix_folder: Path + live_matrix_folder: Path + rag_path: Path + + +def _rag(tmp_path: Path) -> Path: + """Return the RAG storage root of a test, which holds every fitted folder.""" + return tmp_path / "rag" + + +def _spell(path: Path, spelling: str) -> str: + """Spell an existing folder in another way that names the same folder.""" + text = str(path) + if spelling == "forward_slashes": + return text.replace("\\", "/") + if spelling == "trailing_separator": + return text + os.sep + if spelling == "drive_case": + return text[0].swapcase() + text[1:] + raise ValueError(f"Unknown spelling {spelling!r}.") + + +def _pipeline(db: Session, session_id: int) -> int: + """Insert the pipeline row of a session and return its id.""" + pipeline = RAGPipeline(session_id=session_id, name="") + db.add(pipeline) + db.flush() + return pipeline.id + + +def _chunk_set(db: Session, session_id: int, document_id: int, rag: Path) -> int: + """Insert a chunk set with one stored chunk folder under ``rag``.""" + chunk_set = RAGChunkSet( + signature=uuid.uuid4().hex, parameters={}, session_id=session_id + ) + db.add(chunk_set) + db.flush() + folder = chunk_document_dir(rag, chunk_set.id, document_id) + folder.mkdir(parents=True, exist_ok=True) + db.add( + RAGChunkSetDocument( + chunk_set_id=chunk_set.id, + document_id=document_id, + path=str(folder), + n_chunks=1, + ) + ) + db.flush() + return chunk_set.id + + +def _sparse_bridge( + db: Session, pipeline_id: int, chunk_set_id: int, storage: Path, k1: float +) -> int: + """Insert a sparse retriever with its storage folder and return the bridge id.""" + bridge = RAGRetriever(class_name=SPARSE_CLASS, pipeline_id=pipeline_id) + db.add(bridge) + db.flush() + storage.mkdir(parents=True, exist_ok=True) + db.add( + RAGSparseRetriever( + bridge_id=bridge.id, + chunk_set_id=chunk_set_id, + class_name=SPARSE_CLASS, + parameters={"k1": k1}, + storage_folder=str(storage), + ) + ) + db.flush() + return bridge.id + + +def _embedding_model(db: Session, label: str) -> int: + """Insert an embedding model and return its id.""" + model = RAGEmbeddingModel(class_name=EMBEDDING_CLASS, parameters={"label": label}) + db.add(model) + db.flush() + return model.id + + +def _matrix( + db: Session, document_id: int, chunk_set_id: int, model_id: int, storage: Path +) -> int: + """Insert an embedding matrix row with its folder and return its id.""" + storage.mkdir(parents=True, exist_ok=True) + matrix = RAGEmbeddingMatrix( + document_id=document_id, + chunk_set_id=chunk_set_id, + embedding_model_id=model_id, + storage_folder=str(storage), + matrix_shape=[1, 1], + ) + db.add(matrix) + db.flush() + return matrix.id + + +def _dense_bridge( + db: Session, pipeline_id: int, chunk_set_id: int, model_id: int, label: str +) -> int: + """Insert a dense retriever detail and return its bridge id.""" + bridge = RAGRetriever(class_name=DENSE_CLASS, pipeline_id=pipeline_id) + db.add(bridge) + db.flush() + db.add( + RAGDenseRetriever( + bridge_id=bridge.id, + chunk_set_id=chunk_set_id, + class_name=DENSE_CLASS, + parameters={"label": label}, + embedding_model_id=model_id, + ) + ) + db.flush() + return bridge.id + + +def _bare_bridge(db: Session, pipeline_id: int) -> int: + """Insert a bridge with neither a detail nor children, and return its id.""" + bridge = RAGRetriever(class_name=SPARSE_CLASS, pipeline_id=pipeline_id) + db.add(bridge) + db.flush() + return bridge.id + + +def _composite(db: Session, pipeline_id: int, child_ids: list[int]) -> int: + """Insert a composite over the given bridges, in order, and return its id.""" + parent = RAGRetriever(class_name=COMPOSITE_CLASS, pipeline_id=pipeline_id) + db.add(parent) + db.flush() + for order, child_id in enumerate(child_ids): + db.add( + RAGRetrieverChild(parent_id=parent.id, child_id=child_id, child_order=order) + ) + db.flush() + return parent.id + + +def _build_index( + db: Session, tmp_path: Path, session_id: int, document_id: int +) -> _Index: + """Build a session whose live index sits beside its stale rows and folders. + + The live tree is a composite over a live sparse and a live dense retriever. + The stale rows are an old sparse retriever (other parameters), an old dense + retriever with its own embedding model, and their folders, all under the + RAG storage root. + """ + rag = _rag(tmp_path) + pipeline_id = _pipeline(db, session_id) + chunk_set_id = _chunk_set(db, session_id, document_id, rag) + stale_sparse_folder = rag / SPARSE_DIR / "stale" + live_sparse_folder = rag / SPARSE_DIR / "live" + stale_sparse = _sparse_bridge( + db, pipeline_id, chunk_set_id, stale_sparse_folder, STALE_K1 + ) + live_sparse = _sparse_bridge( + db, pipeline_id, chunk_set_id, live_sparse_folder, LIVE_K1 + ) + stale_model = _embedding_model(db, "stale") + live_model = _embedding_model(db, "live") + stale_matrix_folder = rag / EMBEDDINGS_DIR / "stale" + live_matrix_folder = rag / EMBEDDINGS_DIR / "live" + _matrix(db, document_id, chunk_set_id, stale_model, stale_matrix_folder) + _matrix(db, document_id, chunk_set_id, live_model, live_matrix_folder) + stale_dense = _dense_bridge(db, pipeline_id, chunk_set_id, stale_model, "stale") + live_dense = _dense_bridge(db, pipeline_id, chunk_set_id, live_model, "live") + root = _composite(db, pipeline_id, [live_sparse, live_dense]) + db.commit() + return _Index( + session_id=session_id, + pipeline_id=pipeline_id, + document_id=document_id, + chunk_set_id=chunk_set_id, + root_id=root, + stale_sparse_id=stale_sparse, + live_sparse_id=live_sparse, + stale_dense_id=stale_dense, + live_dense_id=live_dense, + stale_model_id=stale_model, + live_model_id=live_model, + stale_sparse_folder=stale_sparse_folder, + live_sparse_folder=live_sparse_folder, + stale_matrix_folder=stale_matrix_folder, + live_matrix_folder=live_matrix_folder, + rag_path=rag, + ) + + +def _other_session_with_chunk_set( + db: Session, tmp_path: Path, document_id: int +) -> tuple[int, int]: + """Create a second session with a pipeline and a chunk set of its own.""" + other = _insert_rag_session(db, f"other_{uuid.uuid4().hex[:8]}") + pipeline_id = _pipeline(db, other.id) + chunk_set_id = _chunk_set(db, other.id, document_id, _rag(tmp_path)) + db.commit() + return pipeline_id, chunk_set_id + + +def _counts(db: Session) -> _Counts: + """Count the rows of every table the cleanup may touch.""" + return _Counts( + retrievers=db.query(RAGRetriever).count(), + retriever_children=db.query(RAGRetrieverChild).count(), + sparse_rows=db.query(RAGSparseRetriever).count(), + dense_rows=db.query(RAGDenseRetriever).count(), + matrices=db.query(RAGEmbeddingMatrix).count(), + models=db.query(RAGEmbeddingModel).count(), + chunk_sets=db.query(RAGChunkSet).count(), + ) + + +def _cleanup(db: Session, index: _Index) -> IndexCleanupSummary: + """Run the cleanup for an index built by :func:`_build_index`.""" + service = CleanupService(db, rag_path=index.rag_path) + return service.cleanup_after_reindex(index.session_id, index.root_id) + + +# =================================================================== +# Stale rows of the indexed session +# =================================================================== + + +def test_stale_rows_and_folders_are_released_after_commit( + orm_db, tmp_path, monkeypatch +): + """Old sparse and dense rows go with their folders, and only after commit.""" + session = _insert_rag_session(orm_db, "reindex_release") + document = _insert_data_document(orm_db, tmp_path / "docs", "release.txt", ["r"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + seen_at_commit: list[tuple[bool, bool]] = [] + real_commit = orm_db.commit + + def commit_and_record() -> None: + """Record whether the folders still exist, then commit for real.""" + seen_at_commit.append( + (index.stale_sparse_folder.exists(), index.stale_matrix_folder.exists()) + ) + real_commit() + + monkeypatch.setattr(orm_db, "commit", commit_and_record) + + result = _cleanup(orm_db, index) + + assert seen_at_commit == [(True, True)], "folders must outlive the transaction" + assert orm_db.get(RAGRetriever, index.stale_sparse_id) is None + assert orm_db.get(RAGRetriever, index.stale_dense_id) is None + assert orm_db.get(RAGEmbeddingModel, index.stale_model_id) is None + assert orm_db.get(RAGRetriever, index.root_id) is not None + assert orm_db.get(RAGRetriever, index.live_sparse_id) is not None + assert orm_db.get(RAGRetriever, index.live_dense_id) is not None + assert orm_db.get(RAGEmbeddingModel, index.live_model_id) is not None + assert not index.stale_sparse_folder.exists() + assert not index.stale_matrix_folder.exists() + assert index.live_sparse_folder.exists() + assert index.live_matrix_folder.exists() + assert result.bridges == 2 + assert result.embedding_matrices == 1 + assert result.embedding_models == 1 + assert result.chunk_sets == 0 + + +def test_stale_composite_is_removed_and_the_live_tree_survives(orm_db, tmp_path): + """A composite left by an earlier index goes; the live tree keeps its links.""" + session = _insert_rag_session(orm_db, "reindex_composite") + document = _insert_data_document(orm_db, tmp_path / "docs", "composite.txt", ["c"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + stale_composite = _composite( + orm_db, index.pipeline_id, [index.live_sparse_id, index.stale_sparse_id] + ) + orm_db.commit() + + _cleanup(orm_db, index) + + assert orm_db.get(RAGRetriever, stale_composite) is None + assert orm_db.get(RAGRetriever, index.stale_sparse_id) is None + assert orm_db.get(RAGRetriever, index.live_sparse_id) is not None + links = { + (link.parent_id, link.child_id) for link in orm_db.query(RAGRetrieverChild) + } + assert links == { + (index.root_id, index.live_sparse_id), + (index.root_id, index.live_dense_id), + } + assert index.live_sparse_folder.exists() + + +def test_stale_chunk_set_of_the_same_session_is_invalidated(orm_db, tmp_path): + """A chunk set the session no longer uses goes with what was fitted on it.""" + session = _insert_rag_session(orm_db, "reindex_chunks") + document = _insert_data_document(orm_db, tmp_path / "docs", "chunks.txt", ["k"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + old_set = _chunk_set(orm_db, session.id, document.id, index.rag_path) + old_folder = index.rag_path / SPARSE_DIR / "old_set" + old_sparse = _sparse_bridge(orm_db, index.pipeline_id, old_set, old_folder, LIVE_K1) + orm_db.commit() + old_chunk_folder = index.rag_path / CHUNK_SETS_DIR / str(old_set) + + result = _cleanup(orm_db, index) + + assert orm_db.get(RAGChunkSet, old_set) is None + assert orm_db.get(RAGRetriever, old_sparse) is None + assert not old_folder.exists() + assert not old_chunk_folder.exists() + assert orm_db.get(RAGChunkSet, index.chunk_set_id) is not None + assert result.chunk_sets == 1 + + +# =================================================================== +# Shared artifacts +# =================================================================== + + +def test_artifacts_another_session_references_are_kept(orm_db, tmp_path): + """A folder or model another session still uses survives the cleanup.""" + session = _insert_rag_session(orm_db, "reindex_shared_owner") + document = _insert_data_document(orm_db, tmp_path / "docs", "shared.txt", ["s"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + other = _insert_rag_session(orm_db, "reindex_shared_other") + other_pipeline = _pipeline(orm_db, other.id) + other_set = _chunk_set(orm_db, other.id, document.id, index.rag_path) + _sparse_bridge( + orm_db, other_pipeline, other_set, index.stale_sparse_folder, STALE_K1 + ) + _sparse_bridge(orm_db, other_pipeline, other_set, index.live_sparse_folder, LIVE_K1) + _matrix( + orm_db, document.id, other_set, index.stale_model_id, index.stale_matrix_folder + ) + _matrix( + orm_db, document.id, other_set, index.live_model_id, index.live_matrix_folder + ) + orm_db.commit() + + result = _cleanup(orm_db, index) + + assert orm_db.get(RAGRetriever, index.stale_sparse_id) is None + assert ( + orm_db.query(RAGSparseRetriever).filter_by(chunk_set_id=other_set).count() == 2 + ) + assert index.stale_sparse_folder.exists(), "the other session still uses it" + assert orm_db.get(RAGEmbeddingModel, index.stale_model_id) is not None + assert ( + orm_db.query(RAGEmbeddingMatrix).filter_by(chunk_set_id=other_set).count() == 2 + ) + assert index.stale_matrix_folder.exists(), "the other session still uses it" + assert index.live_matrix_folder.exists() + assert result.embedding_models == 0 + assert result.embedding_matrices == 1 + + +@pytest.mark.parametrize("spelling", SPELLINGS) +def test_sparse_folder_another_row_spells_differently_is_kept( + orm_db, tmp_path, spelling +): + """A folder a live row reaches under another spelling still counts as used.""" + session = _insert_rag_session(orm_db, f"spelling_sparse_{spelling}") + document = _insert_data_document( + orm_db, tmp_path / "docs", f"sp_{spelling}.txt", ["p"] + ) + index = _build_index(orm_db, tmp_path, session.id, document.id) + other = _insert_rag_session(orm_db, f"spelling_sparse_other_{spelling}") + other_pipeline = _pipeline(orm_db, other.id) + other_set = _chunk_set(orm_db, other.id, document.id, index.rag_path) + bridge_id = _sparse_bridge( + orm_db, other_pipeline, other_set, index.stale_sparse_folder, LIVE_K1 + ) + other_row = orm_db.query(RAGSparseRetriever).filter_by(bridge_id=bridge_id).one() + other_row.storage_folder = _spell(index.stale_sparse_folder, spelling) + orm_db.commit() + + _cleanup(orm_db, index) + + assert orm_db.get(RAGRetriever, index.stale_sparse_id) is None + assert index.stale_sparse_folder.exists(), "a live row still reaches the folder" + + +@pytest.mark.parametrize("spelling", SPELLINGS) +def test_embedding_folder_another_row_spells_differently_is_kept( + orm_db, tmp_path, spelling +): + """A matrix folder another row reaches under another spelling is kept.""" + session = _insert_rag_session(orm_db, f"spelling_matrix_{spelling}") + document = _insert_data_document( + orm_db, tmp_path / "docs", f"mx_{spelling}.txt", ["q"] + ) + index = _build_index(orm_db, tmp_path, session.id, document.id) + other = _insert_rag_session(orm_db, f"spelling_matrix_other_{spelling}") + other_set = _chunk_set(orm_db, other.id, document.id, index.rag_path) + matrix_id = _matrix( + orm_db, document.id, other_set, index.live_model_id, index.live_matrix_folder + ) + other_row = orm_db.get(RAGEmbeddingMatrix, matrix_id) + other_row.storage_folder = _spell(index.stale_matrix_folder, spelling) + orm_db.commit() + + _cleanup(orm_db, index) + + assert orm_db.get(RAGEmbeddingMatrix, matrix_id) is not None + assert index.stale_matrix_folder.exists(), "another row still reaches the folder" + + +@pytest.fixture +def folder_link() -> Iterator[Callable[[Path, Path], None]]: + """Yield a maker of folder links, and remove those links afterwards.""" + links: list[Path] = [] + + def make(link: Path, target: Path) -> None: + """Create ``link`` as a folder link that names ``target``.""" + _make_folder_link(link, target) + links.append(link) + + yield make + for link in links: + with contextlib.suppress(OSError): + os.rmdir(link) + + +def _make_folder_link(link: Path, target: Path) -> None: + """Create ``link`` as a directory junction, or a symlink, to ``target``. + + The test is skipped when neither can be created on this machine. + """ + try: + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(link), str(target)], + check=True, + capture_output=True, + timeout=60, + ) + return + except (OSError, subprocess.SubprocessError): + pass + try: + os.symlink(target, link, target_is_directory=True) + except OSError as error: + pytest.skip(f"Cannot create a folder link here: {error}") + + +def test_folder_reached_through_a_junction_is_kept( + orm_db, tmp_path, monkeypatch, folder_link +): + """A folder a row reaches through a junction is in use, whatever the spelling.""" + session = _insert_rag_session(orm_db, "spelling_junction") + document = _insert_data_document(orm_db, tmp_path / "docs", "junction.txt", ["j"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + alias = index.rag_path / SPARSE_DIR / "alias" + folder_link(alias, index.stale_sparse_folder) + other = _insert_rag_session(orm_db, "spelling_junction_other") + other_pipeline = _pipeline(orm_db, other.id) + other_set = _chunk_set(orm_db, other.id, document.id, index.rag_path) + _sparse_bridge(orm_db, other_pipeline, other_set, alias, LIVE_K1) + stale_row = ( + orm_db.query(RAGSparseRetriever) + .filter_by(bridge_id=index.stale_sparse_id) + .one() + ) + # The stale row stores a path relative to the working directory, the live row + # the absolute junction path: both name the same folder. + stale_row.storage_folder = os.path.join("rag", SPARSE_DIR, "stale") + orm_db.commit() + monkeypatch.chdir(tmp_path) + + _cleanup(orm_db, index) + + assert orm_db.get(RAGRetriever, index.stale_sparse_id) is None + assert index.stale_sparse_folder.exists(), "a live row still reaches the folder" + assert alias.is_dir(), "the live row's junction is untouched" + + +def test_cleanup_leaves_artifacts_no_row_of_the_session_points_at(orm_db, tmp_path): + """Scope is the session: a model another session committed is not a candidate.""" + session = _insert_rag_session(orm_db, "reindex_scope") + document = _insert_data_document(orm_db, tmp_path / "docs", "scope.txt", ["x"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + in_flight_model = _embedding_model(orm_db, "in_flight") + unreferenced_folder = index.rag_path / SPARSE_DIR / "sparse_retriever_id-free" + unreferenced_folder.mkdir(parents=True) + orm_db.commit() + + result = _cleanup(orm_db, index) + + assert orm_db.get(RAGEmbeddingModel, in_flight_model) is not None + assert unreferenced_folder.exists(), "no global sweep of the disk" + assert result.embedding_models == 1 + + +# =================================================================== +# Orphan matrices of a stale chunk set +# =================================================================== + + +def test_stale_chunk_set_matrix_without_a_dense_retriever_is_released(orm_db, tmp_path): + """A matrix with no dense link must not block deleting its chunk set.""" + session = _insert_rag_session(orm_db, "orphan_matrix") + document = _insert_data_document(orm_db, tmp_path / "docs", "orphan.txt", ["o"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + old_set = _chunk_set(orm_db, session.id, document.id, index.rag_path) + orphan_model = _embedding_model(orm_db, "orphan") + orphan_folder = index.rag_path / EMBEDDINGS_DIR / "orphan" + orphan_matrix = _matrix(orm_db, document.id, old_set, orphan_model, orphan_folder) + orm_db.commit() + + result = _cleanup(orm_db, index) + + assert orm_db.get(RAGChunkSet, old_set) is None + assert orm_db.get(RAGEmbeddingMatrix, orphan_matrix) is None + assert orm_db.get(RAGEmbeddingModel, orphan_model) is None + assert not orphan_folder.exists() + assert result.chunk_sets == 1 + + +def test_orphan_matrix_keeps_a_folder_another_row_uses(orm_db, tmp_path): + """An orphan's folder and model survive while another session's row uses them.""" + session = _insert_rag_session(orm_db, "orphan_shared") + document = _insert_data_document(orm_db, tmp_path / "docs", "orphan_s.txt", ["t"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + old_set = _chunk_set(orm_db, session.id, document.id, index.rag_path) + shared_model = _embedding_model(orm_db, "shared_orphan") + shared_folder = index.rag_path / EMBEDDINGS_DIR / "shared_orphan" + _matrix(orm_db, document.id, old_set, shared_model, shared_folder) + other = _insert_rag_session(orm_db, "orphan_shared_other") + other_set = _chunk_set(orm_db, other.id, document.id, index.rag_path) + other_matrix = _matrix(orm_db, document.id, other_set, shared_model, shared_folder) + orm_db.commit() + + _cleanup(orm_db, index) + + assert orm_db.get(RAGChunkSet, old_set) is None + assert shared_folder.exists(), "the other session's matrix still uses it" + assert orm_db.get(RAGEmbeddingMatrix, other_matrix) is not None + assert orm_db.get(RAGEmbeddingModel, shared_model) is not None + + +# =================================================================== +# Containment under the RAG storage root +# =================================================================== + + +def test_sparse_row_outside_the_rag_root_is_deleted_and_its_folder_kept( + orm_db, tmp_path, caplog +): + """A stale row pointing outside the RAG root goes; the folder is not touched.""" + session = _insert_rag_session(orm_db, "contain_sparse") + document = _insert_data_document(orm_db, tmp_path / "docs", "contain.txt", ["n"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + precious = tmp_path / "outside" / "sparse" + precious.mkdir(parents=True) + (precious / "precious.txt").write_text("keep me", encoding="utf-8") + stale = _sparse_bridge(orm_db, index.pipeline_id, index.chunk_set_id, precious, 1.1) + orm_db.commit() + + with caplog.at_level(logging.WARNING, logger=cleanup_service.__name__): + _cleanup(orm_db, index) + + assert orm_db.get(RAGRetriever, stale) is None + assert (precious / "precious.txt").read_text(encoding="utf-8") == "keep me" + assert any( + record.levelno == logging.WARNING and "outside" in record.getMessage() + for record in caplog.records + ) + + +def test_chunk_path_outside_its_chunk_set_is_not_removed(orm_db, tmp_path, caplog): + """A chunk row whose parent is an unrelated folder never removes that folder.""" + session = _insert_rag_session(orm_db, "contain_chunk") + document = _insert_data_document(orm_db, tmp_path / "docs", "chunk_c.txt", ["c"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + old_set = _chunk_set(orm_db, session.id, document.id, index.rag_path) + unrelated = tmp_path / "unrelated" + unrelated.mkdir() + (unrelated / "doc.arrow").write_bytes(b"data") + row = orm_db.query(RAGChunkSetDocument).filter_by(chunk_set_id=old_set).one() + row.path = str(unrelated / "doc.arrow") + orm_db.commit() + + with caplog.at_level(logging.WARNING, logger=cleanup_service.__name__): + _cleanup(orm_db, index) + + assert orm_db.get(RAGChunkSet, old_set) is None + assert (unrelated / "doc.arrow").exists() + assert any( + record.levelno == logging.WARNING and "outside" in record.getMessage() + for record in caplog.records + ) + + +def test_chunk_folder_is_kept_with_a_warning_when_no_stored_path_is_inside_it( + orm_db, tmp_path, caplog +): + """With a RAG root, a chunk set whose paths all lie elsewhere keeps its folder.""" + session = _insert_rag_session(orm_db, f"keep_chunk_{uuid.uuid4().hex[:6]}") + document = _insert_data_document(orm_db, tmp_path / "docs", "keep.txt", ["k"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + old_set = _chunk_set(orm_db, session.id, document.id, index.rag_path) + chunk_folder = index.rag_path / CHUNK_SETS_DIR / str(old_set) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + row = orm_db.query(RAGChunkSetDocument).filter_by(chunk_set_id=old_set).one() + row.path = str(elsewhere) + orm_db.commit() + + with caplog.at_level(logging.WARNING, logger=cleanup_service.__name__): + _cleanup(orm_db, index) + + assert orm_db.get(RAGChunkSet, old_set) is None + assert chunk_folder.exists() + assert any( + "no stored chunk path lies inside" in record.getMessage() + for record in caplog.records + ) + + +def test_cleanup_without_a_rag_path_is_refused(orm_db, tmp_path): + """Without the storage root the removals cannot be checked, so nothing runs.""" + session = _insert_rag_session(orm_db, "contain_refused") + document = _insert_data_document(orm_db, tmp_path / "docs", "refused.txt", ["r"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + before = _counts(orm_db) + + with pytest.raises(ValueError, match="rag_path"): + CleanupService(orm_db).cleanup_after_reindex(index.session_id, index.root_id) + + assert _counts(orm_db) == before + assert index.stale_sparse_folder.exists() + + +# =================================================================== +# Idempotence and malformed input +# =================================================================== + + +def test_a_second_cleanup_changes_nothing(orm_db, tmp_path): + """Once the stale rows are gone, running the cleanup again is a no-op.""" + session = _insert_rag_session(orm_db, "reindex_idempotent") + document = _insert_data_document(orm_db, tmp_path / "docs", "idem.txt", ["i"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + service = CleanupService(orm_db, rag_path=index.rag_path) + service.cleanup_after_reindex(index.session_id, index.root_id) + state = _counts(orm_db) + + second = service.cleanup_after_reindex(index.session_id, index.root_id) + + assert ( + second.chunk_sets, + second.bridges, + second.embedding_matrices, + second.embedding_models, + ) == (0, 0, 0, 0) + assert _counts(orm_db) == state + + +@pytest.mark.parametrize( + ("case", "message"), + [ + ("unknown_root", "is not a retriever of session"), + ("other_session_root", "is not a retriever of session"), + ("bare_root", "neither a fitted detail"), + ("foreign_chunk_set_root", "not owned by session"), + ], +) +def test_malformed_live_root_raises_and_deletes_nothing( + orm_db, tmp_path, case, message +): + """A root that cannot describe this session's live index is refused outright.""" + session = _insert_rag_session(orm_db, f"malformed_{case}") + document = _insert_data_document(orm_db, tmp_path / "docs", f"{case}.txt", ["m"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + other_pipeline, other_set = _other_session_with_chunk_set( + orm_db, tmp_path, document.id + ) + if case == "unknown_root": + root_id = UNKNOWN_BRIDGE_ID + elif case == "other_session_root": + root_id = _sparse_bridge( + orm_db, other_pipeline, other_set, tmp_path / "foreign_root", LIVE_K1 + ) + elif case == "bare_root": + root_id = _bare_bridge(orm_db, index.pipeline_id) + else: + root_id = _sparse_bridge( + orm_db, index.pipeline_id, other_set, tmp_path / "foreign_set", LIVE_K1 + ) + orm_db.commit() + before = _counts(orm_db) + + with pytest.raises(ValueError, match=message): + CleanupService(orm_db, rag_path=index.rag_path).cleanup_after_reindex( + index.session_id, root_id + ) + + assert _counts(orm_db) == before + assert index.stale_sparse_folder.exists() + assert index.stale_matrix_folder.exists() + + +def test_a_session_without_a_pipeline_is_rejected(orm_db, tmp_path): + """Without a pipeline there is no live index to protect, so nothing is guessed.""" + session = _insert_rag_session(orm_db, "reindex_no_pipeline") + + with pytest.raises(ValueError, match="has no pipeline"): + CleanupService(orm_db, rag_path=_rag(tmp_path)).cleanup_after_reindex( + session.id, UNKNOWN_BRIDGE_ID + ) + + +# =================================================================== +# Failure handling +# =================================================================== + + +@pytest.mark.parametrize("failure", ["commit", "mid_run"]) +def test_a_failed_cleanup_keeps_rows_and_folders( + orm_db, tmp_path, monkeypatch, failure +): + """Any failure rolls back the rows and drops the queued folder removals.""" + session = _insert_rag_session(orm_db, f"failing_{failure}") + document = _insert_data_document(orm_db, tmp_path / "docs", f"{failure}.txt", ["f"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + before = _counts(orm_db) + if failure == "commit": + + def fail_commit() -> None: + """Fail the commit that ends the cleanup.""" + raise RuntimeError("commit failed") + + monkeypatch.setattr(orm_db, "commit", fail_commit) + else: + + def fail_guard(self, storage_folder, exclude_ids=()) -> bool: + """Fail the folder guard in the middle of the cleanup.""" + raise RuntimeError("guard failed") + + monkeypatch.setattr(CleanupService, "_embedding_folder_in_use", fail_guard) + + with pytest.raises(RuntimeError): + _cleanup(orm_db, index) + + assert _counts(orm_db) == before + assert index.stale_sparse_folder.exists(), "a queued removal must be dropped" + assert index.stale_matrix_folder.exists() + + +def test_the_entry_point_swallows_failures_but_not_cancellation( + client: TestClient, tmp_path, monkeypatch, caplog +): + """Cleanup errors are logged and dropped; a cancellation still propagates.""" + session_factory = client.app.container["session_factory"] + registry = client.app.container["component_registry"] + session_id = _create_session(client, "entry_point") + + def explode(self, session_id, live_root_bridge_id): + """Fail the way a broken cleanup would.""" + raise RuntimeError("cleanup broke") + + monkeypatch.setattr(CleanupService, "cleanup_after_reindex", explode) + with ( + caplog.at_level(logging.ERROR, logger=cleanup_service.__name__), + session_factory() as db, + ): + cleanup_service.run_post_index_cleanup( + db, registry, session_id, UNKNOWN_BRIDGE_ID, _rag(tmp_path) + ) + assert any(record.exc_info for record in caplog.records) + + def cancel(self, session_id, live_root_bridge_id): + """Raise the cancellation the queue delivers to a running job.""" + raise _Cancelled + + monkeypatch.setattr(CleanupService, "cleanup_after_reindex", cancel) + with session_factory() as db, pytest.raises(_Cancelled): + cleanup_service.run_post_index_cleanup( + db, registry, session_id, UNKNOWN_BRIDGE_ID, _rag(tmp_path) + ) + + +def test_a_missing_live_root_is_logged_and_not_fatal( + client: TestClient, tmp_path, caplog +): + """A None root id is refused inside the guarded path, logged, and returned.""" + session_factory = client.app.container["session_factory"] + registry = client.app.container["component_registry"] + session_id = _create_session(client, "missing_root") + + with ( + caplog.at_level(logging.ERROR, logger=cleanup_service.__name__), + session_factory() as db, + ): + result = cleanup_service.run_post_index_cleanup( + db, registry, session_id, None, _rag(tmp_path) + ) + + assert result is None + records = [record for record in caplog.records if record.exc_info] + assert records, "the refusal must be logged with its traceback" + assert "live root" in str(records[0].exc_info[1]) + + +# =================================================================== +# Job level +# =================================================================== + + +def test_index_job_succeeds_when_the_post_index_cleanup_fails( + client: TestClient, document_files: list[str], monkeypatch, caplog +): + """A cleanup failure is logged; the index is complete and the job succeeds.""" + session_id, _ = _create_session_with_document( + client, "cleanup_failure", document_files + ) + + def explode(self, session_id, live_root_bridge_id): + """Fail the way a broken cleanup would.""" + raise RuntimeError("cleanup broke") + + monkeypatch.setattr(CleanupService, "cleanup_after_reindex", explode) + with caplog.at_level(logging.ERROR, logger=cleanup_service.__name__): + result = RAGIndexJob(session_id=session_id).run() + + assert result["total_chunks"] > 0 + assert isinstance(result["chunk_set_id"], int) + assert any(record.exc_info for record in caplog.records) + status = client.get(f"/api/v1/rag/sessions/{session_id}/index-status").json() + assert status["status"] == "indexed", status + + +def test_index_job_returns_its_result_when_the_live_root_is_missing( + client: TestClient, document_files: list[str], monkeypatch, caplog +): + """A missing root id is logged by the cleanup; the job still returns its result.""" + session_id, _ = _create_session_with_document( + client, "index_no_root", document_files + ) + original_build_index = SetupService.build_index + + def build_index_without_root(self, config, progress=None): + """Build the index, then hand back a result with no root bridge id.""" + result = original_build_index(self, config, progress=progress) + return SimpleNamespace( + chunk_set_id=result.chunk_set_id, + total_chunks=result.total_chunks, + retriever=SimpleNamespace(db_record_id=None), + ) + + monkeypatch.setattr(SetupService, "build_index", build_index_without_root) + with caplog.at_level(logging.ERROR, logger=cleanup_service.__name__): + result = RAGIndexJob(session_id=session_id).run() + + assert result["total_chunks"] > 0 + assert any(record.exc_info for record in caplog.records) + + +def test_index_job_passes_the_configured_rag_path_to_the_cleanup( + client: TestClient, document_files: list[str], monkeypatch +): + """The index job hands the configured RAG root to the post-index cleanup.""" + session_id, _ = _create_session_with_document( + client, "index_rag_path", document_files + ) + roots: list[int] = [] + original_build_index = SetupService.build_index + + def build_index(self, config, progress=None): + """Build the index and remember the root bridge it produced.""" + result = original_build_index(self, config, progress=progress) + roots.append(result.retriever.db_record_id) + return result + + calls: list[tuple[object, ...]] = [] + monkeypatch.setattr(SetupService, "build_index", build_index) + monkeypatch.setattr( + index_job_module, + "run_post_index_cleanup", + lambda *args: calls.append(args[2:]), + ) + + RAGIndexJob(session_id=session_id).run() + + rag_path = client.app.container["config"]["RAG_PATH"] + assert calls == [(session_id, roots[0], rag_path)] + + +def _raise_build_failure(error: BaseException): + """Build a ``build_index`` replacement that raises ``error``.""" + + def build_index(self, config, progress=None): + """Raise the configured error in place of building an index.""" + raise error + + return build_index + + +def test_post_index_cleanup_does_not_run_when_indexing_fails( + client: TestClient, document_files: list[str], monkeypatch +): + """A failed index has nothing to clean up after; the cleanup is not invoked.""" + session_id, _ = _create_session_with_document( + client, "cleanup_not_on_failure", document_files + ) + calls: list[tuple[object, ...]] = [] + monkeypatch.setattr( + index_job_module, + "run_post_index_cleanup", + lambda *args, **kwargs: calls.append(args), + ) + monkeypatch.setattr( + SetupService, "build_index", _raise_build_failure(RuntimeError("bad")) + ) + + with pytest.raises(JobError): + RAGIndexJob(session_id=session_id).run() + + assert calls == [] + + +def test_post_index_cleanup_does_not_run_when_the_job_is_cancelled( + client: TestClient, document_files: list[str], monkeypatch +): + """Cancellation is a BaseException; it skips the cleanup and propagates.""" + session_id, _ = _create_session_with_document( + client, "cleanup_not_on_cancel", document_files + ) + calls: list[tuple[object, ...]] = [] + monkeypatch.setattr( + index_job_module, + "run_post_index_cleanup", + lambda *args, **kwargs: calls.append(args), + ) + monkeypatch.setattr(SetupService, "build_index", _raise_build_failure(_Cancelled())) + + with pytest.raises(_Cancelled): + RAGIndexJob(session_id=session_id).run() + + assert calls == [] + + +@pytest.fixture +def document_files() -> Iterator[list[str]]: + """Collect the document files a job test writes, and remove them afterwards.""" + paths: list[str] = [] + yield paths + for path in paths: + with contextlib.suppress(OSError): + os.remove(path) + + +def _set_bm25_k1(client: TestClient, session_id: int, k1: float) -> None: + """Give a session a BM25 retriever with the given ``k1`` weighting.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session = db.get(GenerativeSession, session_id) + parameters = dict(session.parameters) + parameters["retriever_model"] = { + "component": SPARSE_CLASS, + "params": {**bm25_retriever_params(), "k1": k1}, + } + session.parameters = parameters + db.commit() + + +def _sparse_rows_of(client: TestClient, session_id: int) -> list[tuple[int, str]]: + """Return ``(row id, storage folder)`` of every sparse row of a session.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + rows = ( + db.query(RAGSparseRetriever) + .join(RAGRetriever, RAGSparseRetriever.bridge_id == RAGRetriever.id) + .join(RAGPipeline, RAGRetriever.pipeline_id == RAGPipeline.id) + .filter(RAGPipeline.session_id == session_id) + .all() + ) + return [(row.id, row.storage_folder) for row in rows] + + +def test_reindex_after_an_identity_change_releases_the_old_sparse_index( + client: TestClient, document_files: list[str] +): + """Changing BM25's weighting re-fits it; the old row and folder are released.""" + session_id, _ = _create_session_with_document( + client, "reindex_identity", document_files + ) + _set_bm25_k1(client, session_id, OLD_K1) + RAGIndexJob(session_id=session_id).run() + before = _sparse_rows_of(client, session_id) + + _set_bm25_k1(client, session_id, NEW_K1) + RAGIndexJob(session_id=session_id).run() + after = _sparse_rows_of(client, session_id) + + assert len(before) == 1, before + assert len(after) == 1, after + (old_id, old_folder), (new_id, new_folder) = before[0], after[0] + assert new_id != old_id + assert new_folder != old_folder + assert not os.path.exists(old_folder), "the stale folder must be released" + assert os.path.isdir(new_folder) + + +# =================================================================== +# Chat job call site +# =================================================================== + + +@pytest.fixture +def chat_stub_llm(client: TestClient) -> None: + """Register the stub generation model the chat turns below use.""" + registry = client.app.container["component_registry"] + if "StubLLM" not in registry: + registry.register_component(StubLLM) + + +def _chat_process( + client: TestClient, document_files: list[str], tag: str +) -> tuple[int, int]: + """Create a RAG session with one document and one pending turn. + + Returns the session id and the process id. + """ + suffix = f"_post_index_{tag}_{uuid.uuid4().hex[:6]}" + doc_id = _create_test_document(client, suffix=suffix, text=DOC_TEXT) + document_files.append(write_test_doc_file(suffix, DOC_TEXT)) + parameters = _frontend_session_parameters( + doc_id, "BM25Retriever", "DefaultRAGGenerationPrompt" + ) + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session = GenerativeSession( + **rag_session_columns(parameters), + name=f"post_index_{tag}", + description=None, + ) + db.add(session) + db.commit() + db.refresh(session) + process = GenerativeProcess(session_id=session.id, status=RunStatus.NOT_STARTED) + db.add(process) + db.commit() + db.refresh(process) + db.add( + ProcessData( + process_id=process.id, + is_input=True, + data="Tell me about DashAI", + data_type="str", + ) + ) + db.commit() + return session.id, process.id + + +def test_chat_turn_cleans_up_after_the_pipeline_is_built( + client: TestClient, document_files: list[str], monkeypatch, chat_stub_llm +): + """The turn cleans up once the pipeline exists, with its live root and RAG path.""" + session_id, process_id = _chat_process(client, document_files, "built") + events: list[tuple[str, object]] = [] + original_build_pipeline = SetupService.build_pipeline + + def build_pipeline(self, config): + """Build the pipeline and record its root bridge id.""" + pipeline = original_build_pipeline(self, config) + events.append(("build", pipeline.retriever.get_id())) + return pipeline + + monkeypatch.setattr(SetupService, "build_pipeline", build_pipeline) + monkeypatch.setattr( + rag_job_module, + "run_post_index_cleanup", + lambda *args: events.append(("cleanup", args[2:])), + ) + + RAGJob(generative_process_id=process_id).run() + + rag_path = client.app.container["config"]["RAG_PATH"] + (build_kind, root_id), (cleanup_kind, cleanup_args) = events + assert (build_kind, cleanup_kind) == ("build", "cleanup") + assert cleanup_args == (session_id, root_id, rag_path) + + +def test_chat_turn_does_not_clean_up_when_the_pipeline_cannot_be_built( + client: TestClient, document_files: list[str], monkeypatch, chat_stub_llm +): + """A pipeline that fails to build has nothing to clean up after.""" + _session_id, process_id = _chat_process(client, document_files, "unbuilt") + calls: list[tuple[object, ...]] = [] + + def build_pipeline(self, config): + """Fail the way a pipeline that cannot be built would.""" + raise RuntimeError("cannot build") + + monkeypatch.setattr(SetupService, "build_pipeline", build_pipeline) + monkeypatch.setattr( + rag_job_module, + "run_post_index_cleanup", + lambda *args: calls.append(args), + ) + + with pytest.raises(JobError): + RAGJob(generative_process_id=process_id).run() + + assert calls == [] + + +def test_chat_turn_finishes_when_the_post_index_cleanup_fails( + client: TestClient, document_files: list[str], monkeypatch, caplog, chat_stub_llm +): + """A cleanup failure is logged and the answered turn still finishes.""" + _session_id, process_id = _chat_process(client, document_files, "cleanup_fails") + + def explode(self, session_id, live_root_bridge_id): + """Fail the way a broken cleanup would.""" + raise RuntimeError("cleanup broke") + + monkeypatch.setattr(CleanupService, "cleanup_after_reindex", explode) + with caplog.at_level(logging.ERROR, logger=cleanup_service.__name__): + RAGJob(generative_process_id=process_id).run() + + session_factory = client.app.container["session_factory"] + with session_factory() as db: + process = db.get(GenerativeProcess, process_id) + assert process.status == RunStatus.FINISHED + assert any(record.exc_info for record in caplog.records) + + +def _add_turn(client: TestClient, session_id: int, text: str) -> int: + """Add one more pending chat turn to an existing session and return its id.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + process = GenerativeProcess(session_id=session_id, status=RunStatus.NOT_STARTED) + db.add(process) + db.commit() + db.refresh(process) + db.add( + ProcessData( + process_id=process.id, is_input=True, data=text, data_type="str" + ) + ) + db.commit() + return process.id + + +def test_chat_turn_skips_cleanup_when_the_index_is_reused( + client: TestClient, document_files: list[str], monkeypatch, chat_stub_llm +): + """A turn that finds its index already built has nothing new to clean up.""" + session_id, first_turn = _chat_process(client, document_files, "reused") + RAGJob(generative_process_id=first_turn).run() + second_turn = _add_turn(client, session_id, "Tell me more about DashAI") + calls: list[tuple[object, ...]] = [] + monkeypatch.setattr( + rag_job_module, + "run_post_index_cleanup", + lambda *args: calls.append(args), + ) + + RAGJob(generative_process_id=second_turn).run() + + assert calls == [] + + +def test_chat_turn_cleans_up_when_the_identity_changed_before_the_turn( + client: TestClient, document_files: list[str], monkeypatch, chat_stub_llm +): + """A turn that rebuilds a changed retriever cleans up around its live root.""" + session_id, first_turn = _chat_process(client, document_files, "rebuilt") + RAGJob(generative_process_id=first_turn).run() + _set_bm25_k1(client, session_id, NEW_K1) + second_turn = _add_turn(client, session_id, "Tell me more about DashAI") + events: list[tuple[str, object]] = [] + original_build_pipeline = SetupService.build_pipeline + + def build_pipeline(self, config): + """Build the pipeline and record its root bridge id.""" + pipeline = original_build_pipeline(self, config) + events.append(("build", pipeline.retriever.get_id())) + return pipeline + + monkeypatch.setattr(SetupService, "build_pipeline", build_pipeline) + monkeypatch.setattr( + rag_job_module, + "run_post_index_cleanup", + lambda *args: events.append(("cleanup", args[2:])), + ) + + RAGJob(generative_process_id=second_turn).run() + + rag_path = client.app.container["config"]["RAG_PATH"] + (build_kind, root_id), (cleanup_kind, cleanup_args) = events + assert (build_kind, cleanup_kind) == ("build", "cleanup") + assert cleanup_args == (session_id, root_id, rag_path) + + +def test_chat_turn_releases_the_index_it_replaced( + client: TestClient, document_files: list[str], chat_stub_llm +): + """After a rebuilding turn only the live sparse row of the session remains.""" + session_id, first_turn = _chat_process(client, document_files, "replaced") + RAGJob(generative_process_id=first_turn).run() + before = _sparse_rows_of(client, session_id) + _set_bm25_k1(client, session_id, NEW_K1) + second_turn = _add_turn(client, session_id, "Tell me more about DashAI") + + RAGJob(generative_process_id=second_turn).run() + + after = _sparse_rows_of(client, session_id) + assert len(before) == 1, before + assert len(after) == 1, after + assert after[0][0] != before[0][0] + assert not os.path.exists(before[0][1]), "the replaced folder must be released" + + +# =================================================================== +# Stale rows that a failed cleanup left behind +# =================================================================== + + +def _pipeline_id_of(db: Session, session_id: int) -> int: + """Return the pipeline id of a session.""" + return db.query(RAGPipeline.id).filter_by(session_id=session_id).scalar() + + +def test_stale_row_probe_sees_leftovers_only(orm_db, tmp_path): + """The probe is false for a clean index and true once a stale root or set exists.""" + session = _insert_rag_session(orm_db, f"probe_{uuid.uuid4().hex[:8]}") + document = _insert_data_document(orm_db, tmp_path / "docs", "probe.txt", ["p"]) + index = _build_index(orm_db, tmp_path, session.id, document.id) + assert cleanup_service.has_stale_index_rows(orm_db, session.id) is True + + _cleanup(orm_db, index) + assert cleanup_service.has_stale_index_rows(orm_db, session.id) is False + + _chunk_set(orm_db, session.id, document.id, index.rag_path) + orm_db.commit() + assert cleanup_service.has_stale_index_rows(orm_db, session.id) is True + + +def test_stale_row_probe_is_false_for_a_session_without_rows(orm_db): + """A session that never indexed has nothing to clean.""" + session = _insert_rag_session(orm_db, f"probe_empty_{uuid.uuid4().hex[:8]}") + + assert cleanup_service.has_stale_index_rows(orm_db, session.id) is False + + +def _add_leftover_root(client: TestClient, session_id: int) -> int: + """Add a bridge no child link reaches, as a failed cleanup would leave it.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + bridge_id = _bare_bridge(db, _pipeline_id_of(db, session_id)) + db.commit() + return bridge_id + + +def test_chat_turn_retries_leftover_stale_rows_once( + client: TestClient, document_files: list[str], monkeypatch, chat_stub_llm +): + """Stale rows left by an earlier failed cleanup are released by the next turn.""" + session_id, first_turn = _chat_process(client, document_files, "leftover") + RAGJob(generative_process_id=first_turn).run() + leftover = _add_leftover_root(client, session_id) + calls: list[tuple[object, ...]] = [] + original_cleanup = rag_job_module.run_post_index_cleanup + + def record_cleanup(*args): + """Count the call and run the real cleanup.""" + calls.append(args) + original_cleanup(*args) + + monkeypatch.setattr(rag_job_module, "run_post_index_cleanup", record_cleanup) + second_turn = _add_turn(client, session_id, "Tell me more about DashAI") + + RAGJob(generative_process_id=second_turn).run() + + assert len(calls) == 1 + session_factory = client.app.container["session_factory"] + with session_factory() as db: + assert db.get(RAGRetriever, leftover) is None + + third_turn = _add_turn(client, session_id, "And one more question") + RAGJob(generative_process_id=third_turn).run() + + assert len(calls) == 1, "a clean index must not trigger the cleanup again" diff --git a/tests/back/RAG/test_session_configuration_references.py b/tests/back/RAG/test_session_configuration_references.py new file mode 100644 index 000000000..fc6bdb5f9 --- /dev/null +++ b/tests/back/RAG/test_session_configuration_references.py @@ -0,0 +1,77 @@ +"""Component references in a session's configuration are read strictly. + +An empty reference (``{}`` or ``{"component": "", "params": {}}``) names nothing +and describes as a custom configuration. A reference that names no component, +or whose component is not a string, is malformed and raises ValueError rather +than being read as an empty component. +""" + +import pytest + +from DashAI.back.services.RAG.session_configuration_service import ( + SessionConfigurationService, +) + + +def _service() -> SessionConfigurationService: + """Return a service with no database and no registered components.""" + return SessionConfigurationService(db=None, registry={}) + + +def test_an_empty_retriever_reference_describes_as_custom(): + section = _service()._describe_retriever({}) + + assert section["preset_key"] is None + assert section["component"] == "" + + +def test_an_empty_component_with_empty_params_describes_as_custom(): + section = _service()._describe_retriever({"component": "", "params": {}}) + + assert section["preset_key"] is None + + +def test_an_empty_chunking_reference_describes_without_a_summary(): + section = _service()._describe_chunking({"component": "", "params": {}}) + + assert section["preset_key"] is None + assert "summary" not in section + + +@pytest.mark.parametrize( + "reference", + [{"params": {"top_k": 3}}, {"component": None, "params": {}}, {"component": 7}], + ids=["missing-component", "null-component", "numeric-component"], +) +def test_a_malformed_retriever_reference_raises(reference): + with pytest.raises(ValueError, match="component"): + _service()._describe_retriever(reference) + + +def test_a_malformed_chunking_reference_raises(): + with pytest.raises(ValueError, match="component"): + _service()._describe_chunking({"params": {"chunk_size": 10}}) + + +def test_a_malformed_generation_reference_raises(): + with pytest.raises(ValueError, match="component"): + _service()._describe_generation({"params": {}}) + + +def test_a_malformed_transformation_reference_raises(): + with pytest.raises(ValueError, match="component"): + _service()._describe_transformation({"params": {}}) + + +def test_an_absent_transformation_reference_is_disabled(): + section = _service()._describe_transformation({}) + + assert section["enabled"] is False + + +def test_a_retriever_contract_error_is_not_swallowed(): + """A malformed ``children`` list reaches the caller from preset matching.""" + reference = {"component": "ParallelRetriever", "params": {"children": "nope"}} + + with pytest.raises(ValueError, match="children"): + _service()._describe_retriever(reference) From cb4c6a8def672f71fa52bec9ec91a97f2dfd90ba Mon Sep 17 00:00:00 2001 From: Cristian Tamblay Date: Fri, 27 Nov 2026 12:11:33 -0300 Subject: [PATCH 8/8] fix(rag): complete the hybrid preset's children with their defaults The startup backfill that translates retrievers stored by v0.11.0 completes every level of a composite with its schema defaults, so converted hybrid sessions store enable_retrieve_then_expand and expand_window in each child. The hybrid preset was completed only at the top level, and with the strict preset match every upgraded hybrid session showed as a custom configuration. The preset now completes its children too; new sessions still round-trip. --- DashAI/back/services/RAG/retriever_presets.py | 51 +++++++++- tests/back/RAG/test_retriever_presets.py | 95 +++++++++++++++++++ 2 files changed, 144 insertions(+), 2 deletions(-) diff --git a/DashAI/back/services/RAG/retriever_presets.py b/DashAI/back/services/RAG/retriever_presets.py index a0c893c20..692bd009a 100644 --- a/DashAI/back/services/RAG/retriever_presets.py +++ b/DashAI/back/services/RAG/retriever_presets.py @@ -18,7 +18,11 @@ default_keyword_retriever, default_semantic_retriever, ) -from DashAI.back.models.RAG.retrievers.ref_utils import CHILDREN_KEY, PARAMS_KEY +from DashAI.back.models.RAG.retrievers.ref_utils import ( + CHILDREN_KEY, + COMPONENT_KEY, + PARAMS_KEY, +) from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( ENABLE_FIELD, TOP_K_FIELD, @@ -118,9 +122,52 @@ def _semantic_preset(top_k: int, registry) -> Dict[str, Any]: } +def _with_schema_defaults( + component: str, params: Dict[str, Any], registry +) -> Dict[str, Any]: + """Complete a retriever's params with its schema defaults, children included. + + Every child of a composite is completed with its own defaults as well. The + startup backfill that translates retrievers stored by earlier versions + (``translate_legacy_retriever``) completes every level this way, so a + recipe completed only at the top would never equal a converted session. + + Parameters + ---------- + component : str + Retriever class name. + params : Dict[str, Any] + Parameters the recipe sets. They win over the schema defaults. + registry : ComponentRegistry + Registry used to resolve each component's schema defaults. + + Returns + ------- + Dict[str, Any] + A new params dict; ``params`` itself is not modified. + """ + completed = {**resolve_component_defaults(component, registry), **params} + children = completed.get(CHILDREN_KEY) + if isinstance(children, list): + completed[CHILDREN_KEY] = [ + { + **child, + PARAMS_KEY: _with_schema_defaults( + child[COMPONENT_KEY], child[PARAMS_KEY], registry + ), + } + for child in children + ] + return completed + + def _hybrid_preset(top_k: int, registry) -> Dict[str, Any]: """Build the hybrid preset from the centralized parallel default. + Its children carry their schema defaults too, so a hybrid session stored + with them, such as one converted from an earlier version at startup, still + matches the preset. + Parameters ---------- top_k : int @@ -135,7 +182,7 @@ def _hybrid_preset(top_k: int, registry) -> Dict[str, Any]: The hybrid preset recipe with its display metadata. """ ref = default_hybrid_retriever(top_k) - params = {**resolve_component_defaults(ref["component"], registry), **ref["params"]} + params = _with_schema_defaults(ref[COMPONENT_KEY], ref[PARAMS_KEY], registry) return { "key": HYBRID_PRESET_KEY, "display_name": _HYBRID_NAME, diff --git a/tests/back/RAG/test_retriever_presets.py b/tests/back/RAG/test_retriever_presets.py index 40eb39b9b..f01292c6e 100644 --- a/tests/back/RAG/test_retriever_presets.py +++ b/tests/back/RAG/test_retriever_presets.py @@ -1,7 +1,73 @@ """Tests for the retriever-presets endpoint.""" +import copy + +import pytest from fastapi.testclient import TestClient +from DashAI.back.dependencies.config_builder import get_initial_components +from DashAI.back.dependencies.registry import ComponentRegistry +from DashAI.back.services.RAG.legacy_retrievers import translate_legacy_retriever +from DashAI.back.services.RAG.retriever_presets import match_preset_key + +#: Retrievers exactly as v0.11.0 stored them for the keyword and hybrid +#: presets: no retrieve-then-expand options at any level, and the similarity +#: metrics as scikit-learn names. +_V0110_BM25 = { + "component": "BM25Retriever", + "params": { + "vectorizer": { + "component": "BagOfWordsConverter", + "params": { + "max_features": None, + "lowercase": True, + "strip_accents": None, + "analyzer": "word", + "stop_words": None, + "custom_stop_words": None, + "lower_bound_ngrams": 1, + "upper_bound_ngrams": 1, + "min_df": 0.0, + "max_df": 1.0, + "drop_source_columns": False, + }, + }, + "k1": 1.5, + "b": 0.75, + "delta": 0.0, + "similarity_function": "cosine", + "top_k": 10, + }, +} +_V0110_DENSE = { + "component": "DenseEmbeddingRetriever", + "params": { + "embedding_model": { + "component": "ParaphraseMultilingualMiniLML12V2Embedding", + "params": { + "device": "CPU", + "batch_size": 32, + "normalize": True, + "overflow_strategy": "truncate", + }, + }, + "similarity_metric": "cosine", + "top_k": 5, + }, +} +_V0110_HYBRID = { + "component": "ParallelRetriever", + "params": { + "merge_strategy": "round_robin", + "children": [_V0110_BM25, _V0110_DENSE], + }, +} + + +@pytest.fixture(scope="module", name="registry") +def fixture_registry(): + return ComponentRegistry(initial_components=get_initial_components()) + def test_retriever_presets_returns_three_presets(client: TestClient): response = client.get("/api/v1/rag/retriever-presets", params={"top_k": 10}) @@ -43,3 +109,32 @@ def test_hybrid_preset_splits_top_k(client: TestClient): def test_retriever_presets_rejects_invalid_top_k(client: TestClient): response = client.get("/api/v1/rag/retriever-presets", params={"top_k": 0}) assert response.status_code == 422 + + +def test_hybrid_preset_children_carry_their_schema_defaults(client: TestClient): + """Each child is completed with its defaults, like the top level.""" + data = client.get("/api/v1/rag/retriever-presets", params={"top_k": 10}).json() + for child in data[2]["params"]["children"]: + assert child["params"]["enable_retrieve_then_expand"] is False + assert "expand_window" in child["params"] + + +@pytest.mark.parametrize( + ("stored", "preset_key"), + [(_V0110_BM25, "keyword"), (_V0110_HYBRID, "hybrid")], +) +def test_a_retriever_converted_from_v0110_keeps_its_preset( + registry, stored, preset_key +): + """The startup backfill completes every level with its defaults. + + A hybrid preset completed only at the top level never matched the + converted sessions, so every hybrid session showed as a custom + configuration after upgrading from v0.11.0. + """ + translated = translate_legacy_retriever(copy.deepcopy(stored), registry) + + assert ( + match_preset_key(translated["component"], translated["params"], registry) + == preset_key + )