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/api/api_v1/endpoints/rag.py b/DashAI/back/api/api_v1/endpoints/rag.py index c17f83ce3..21b0f83bf 100644 --- a/DashAI/back/api/api_v1/endpoints/rag.py +++ b/DashAI/back/api/api_v1/endpoints/rag.py @@ -15,6 +15,7 @@ from DashAI.back.core.utils import localize from DashAI.back.dependencies.database.models import GenerativeSession from DashAI.back.job.RAG_index_job import RAGIndexJob +from DashAI.back.models.RAG.exceptions import RAGPipelineConfigError from DashAI.back.models.RAG.RAG_constants import RAG_PARAM_KEYS from DashAI.back.services.RAG.chunking_presets import ( get_chunking_presets as resolve_chunking_presets, @@ -31,6 +32,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 +167,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, RAGPipelineConfigError) 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/converters/hugging_face/text_embedding/base.py b/DashAI/back/converters/hugging_face/text_embedding/base.py index be109ab78..404844c55 100644 --- a/DashAI/back/converters/hugging_face/text_embedding/base.py +++ b/DashAI/back/converters/hugging_face/text_embedding/base.py @@ -36,6 +36,10 @@ TRUNCATE = "truncate" 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 @@ -245,6 +249,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 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 pretrained(self) -> Any: """Return the loaded checkpoint, using the model cache inside a job. diff --git a/DashAI/back/job/RAG_index_job.py b/DashAI/back/job/RAG_index_job.py index 355b14231..5e8c33cd2 100644 --- a/DashAI/back/job/RAG_index_job.py +++ b/DashAI/back/job/RAG_index_job.py @@ -12,20 +12,78 @@ from typing import Dict from kink import di, inject +from sqlalchemy.orm import Session from DashAI.back.dependencies.database.models import GenerativeSession +from DashAI.back.dependencies.registry.component_registry import ComponentRegistry 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, ) -from DashAI.back.services.RAG.setup_service import SetupService +from DashAI.back.services.RAG.setup_service import IndexResult, SetupService log = logging.getLogger(__name__) +def _cleanup_and_summarize( + db: Session, + component_registry: ComponentRegistry, + session_id: int, + result: IndexResult, + rag_path: str, +) -> Dict[str, int]: + """Run the post-index cleanup of a built index, then summarise it. + + The ids are read before the cleanup, which may roll the session back. A + cleanup failure is logged by :func:`run_post_index_cleanup` and never fails + the job, since the index is complete by now. + + Parameters + ---------- + db : Session + Session the cleanup runs in. + component_registry : ComponentRegistry + Component registry, passed through to the cleanup. + session_id : int + The session that was just indexed. + result : IndexResult + The index the build returned, before it is released. + rag_path : str + The RAG storage root (``RAG_PATH``). + + Returns + ------- + Dict[str, int] + ``{"chunk_set_id": int, "total_chunks": int}`` of the index. + """ + chunk_set_id = result.chunk_set_id + total_chunks = result.total_chunks + root_bridge_id = result.retriever.db_record_id + reranker_bridge_id: int | None = None + if result.reranker is not None: + reranker_bridge_id = result.reranker.db_record_id + run_post_index_cleanup( + db, + component_registry, + session_id, + root_bridge_id, + rag_path, + reranker_bridge_id, + ) + log.debug( + "Indexed session %d: chunk set %d, %d chunks", + session_id, + chunk_set_id, + total_chunks, + ) + return {"chunk_set_id": chunk_set_id, "total_chunks": total_chunks} + + class RAGIndexJob(BaseJob): """Chunks, embeds and fits the retriever for one RAG session. @@ -96,6 +154,8 @@ def run(self) -> Dict[str, int]: session = db.get(GenerativeSession, session_id) if not session: raise JobError(f"Session {session_id} not found in DB.") + if session.parameters is None: + raise JobError(f"Session {session_id} has no stored parameters.") # Whitelist-only, same as RAGJob: session parameters may carry # keys the pipeline config would reject. Prompts are stored in @@ -104,11 +164,9 @@ def run(self) -> Dict[str, int]: db, component_registry ).materialize_session_parameters( session_id, - dict(session.parameters or {}), + dict(session.parameters), ) - 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.") @@ -136,16 +194,13 @@ def run(self) -> Dict[str, int]: progress=self.report_progress, ) try: - log.debug( - "Indexed session %d: chunk set %d, %d chunks", + return _cleanup_and_summarize( + db, + component_registry, session_id, - result.chunk_set_id, - result.total_chunks, + result, + config["RAG_PATH"], ) - return { - "chunk_set_id": result.chunk_set_id, - "total_chunks": result.total_chunks, - } finally: SetupService.release_index(result) except JobError: diff --git a/DashAI/back/job/RAG_job.py b/DashAI/back/job/RAG_job.py index eacd43789..6e75d863e 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,388 @@ 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 and its reranker, if + any, are 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, component_registry + ): + return + run_post_index_cleanup( + db, + component_registry, + session_id, + model.retriever.get_id(), + rag_path, + _reranker_root_id(model), + ) + + +def _reranker_root_id(model: RAGPipeline) -> int | None: + """Return the bridge id of the reranker a built pipeline holds. + + Parameters + ---------- + model : RAGPipeline + The pipeline the build returned. + + Returns + ------- + int | None + The reranker's bridge id, or ``None`` when the transformation stage is + disabled or carries no reranker. + """ + transformation = model.query_transformation + if transformation is None or transformation.reranker is None: + return None + return transformation.reranker.get_id() + + +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.""" @@ -252,6 +652,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. @@ -285,185 +811,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/models/RAG/retrievers/base_retriever.py b/DashAI/back/models/RAG/retrievers/base_retriever.py index 77d552176..1c96d0149 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 268cb483b..03077577d 100644 --- a/DashAI/back/models/RAG/retrievers/composite/agentic_reranker_retriever.py +++ b/DashAI/back/models/RAG/retrievers/composite/agentic_reranker_retriever.py @@ -321,6 +321,16 @@ class AgenticRerankerRetriever(CompositeRetriever, ChunkScorer): "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 b5a265d98..cdd1cf860 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 @@ -25,6 +25,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 @@ -32,6 +33,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`. @@ -121,6 +126,13 @@ class MMRRerankerRetriever(CompositeRetriever, ChunkScorer): 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 84cfa4303..153469b16 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 @@ -16,6 +16,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 @@ -47,6 +48,10 @@ class CrossEncoderRetriever(CompositeRetriever, ChunkScorer, 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 b5c738d30..251720ca8 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 @@ -17,6 +17,7 @@ from DashAI.back.models.RAG.documents import Chunk from DashAI.back.models.RAG.retrievers.capabilities import ChunkScorer from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( + TOP_K_FIELD, RetrievalExpansionSchema, ) from DashAI.back.models.RAG.retrievers.similarity import ( @@ -27,6 +28,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`. @@ -89,6 +93,13 @@ class DenseEmbeddingRetriever(UnitRetriever, ChunkScorer): 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..3c9ad9b5f 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 @@ -74,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/models/RAG/retrievers/sparse/bm25_retriever.py b/DashAI/back/models/RAG/retrievers/sparse/bm25_retriever.py index 70525ba61..15c1f9667 100644 --- a/DashAI/back/models/RAG/retrievers/sparse/bm25_retriever.py +++ b/DashAI/back/models/RAG/retrievers/sparse/bm25_retriever.py @@ -17,6 +17,7 @@ from DashAI.back.models.RAG.documents import Chunk from DashAI.back.models.RAG.retrievers.capabilities import ChunkScorer from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( + TOP_K_FIELD, RetrievalExpansionSchema, ) from DashAI.back.models.RAG.retrievers.similarity import ( @@ -24,7 +25,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__) @@ -153,6 +157,13 @@ class BM25Retriever(SparseRetriever, ChunkScorer): 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 ce249efba..8ef8e25d4 100644 --- a/DashAI/back/models/RAG/retrievers/sparse/tfidf_retriever.py +++ b/DashAI/back/models/RAG/retrievers/sparse/tfidf_retriever.py @@ -15,6 +15,7 @@ from DashAI.back.models.RAG.documents import Chunk from DashAI.back.models.RAG.retrievers.capabilities import ChunkScorer from DashAI.back.models.RAG.retrievers.retrieval_expansion import ( + TOP_K_FIELD, RetrievalExpansionSchema, ) from DashAI.back.models.RAG.retrievers.similarity import ( @@ -22,7 +23,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__) @@ -81,6 +85,13 @@ class TFIDFRetriever(SparseRetriever, ChunkScorer): 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", 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/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 9dc218886..2156843f4 100644 --- a/DashAI/back/services/RAG/cleanup_service.py +++ b/DashAI/back/services/RAG/cleanup_service.py @@ -1,11 +1,16 @@ import logging +import os +from collections.abc import Iterable +from dataclasses import dataclass from pathlib import Path -from typing import Any, Dict, List, Optional, Sequence, Set +from typing import Any, Sequence +from sqlalchemy import select from sqlalchemy.orm import Session from DashAI.back.core.schema_fields.utils import normalize_payload from DashAI.back.dependencies.database.models import ( + GenerativeSession, RAGChunkingModel, RAGChunkSet, RAGChunkSetDocument, @@ -17,146 +22,435 @@ RAGRetrieverChild, RAGSparseRetriever, ) -from DashAI.back.models.RAG.exceptions import RAGPipelineConfigError +from DashAI.back.dependencies.registry.component_registry import ComponentRegistry +from DashAI.back.models.RAG.exceptions import ( + RAGComponentNotFoundError, + RAGPipelineConfigError, +) from DashAI.back.models.RAG.RAG_constants import ( - CHILDREN_KEY, - COMPONENT_KEY, COMPOSITE_RETRIEVER_NAMES, - PARAMS_KEY, + RAG_PARAM_CHUNKING_MODEL, RAG_PARAM_QUERY_TRANSFORMATION, RAG_PARAM_RETRIEVER_MODEL, RERANKER_KEY, ) -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 ( + CHILDREN_KEY, + COMPONENT_KEY, + PARAMS_KEY, ) +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__) -def _retriever_identity(reference: Any) -> Any: - """Return a retriever reference without its expansion options. +@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_ids : frozenset[int] + The retriever's root, and the reranker's root when the session has one: + the root the reindex built, or the session's current reranker rows when + the reindex built none. Each roots a 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_ids: frozenset[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)) - 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. + +def _model_ids_of(pairs: Iterable[tuple[int, int]]) -> set[int]: + """Return the embedding model ids of ``(chunk set id, model id)`` pairs. Parameters ---------- - reference : Any - A ``{"component", "params"}`` retriever reference, or any other value. + pairs : Iterable[tuple[int, int]] + Pairs of a chunk set id and an embedding model id. Returns ------- - Any - The reference with ``params`` stripped of the two options, or the value - unchanged when it is not a retriever reference. + set[int] + The model ids, without repeats. """ - if not isinstance(reference, dict): - return reference - params = reference.get(PARAMS_KEY) - if not isinstance(params, dict): - return reference - identity = dict(reference) - identity[PARAMS_KEY] = strip_expansion_options(params) - return identity + model_ids: set[int] = set() + for _chunk_set_id, model_id in pairs: + model_ids.add(model_id) + return model_ids -def _reranker_reference( - parameters: Optional[Dict[str, Any]], -) -> Optional[Dict[str, Any]]: - """Return the query-transformation reranker reference of session parameters. +@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. + + 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 ---------- - parameters : Optional[Dict[str, Any]] - A session's parameters dict, or ``None``. + reference : Any + A ``{"component", "params"}`` retriever reference, or any other value. + registry : ComponentRegistry | None + Registry used to resolve the retriever classes. Returns ------- - Optional[Dict[str, Any]] - The ``reranker`` reference nested in ``query_transformation``, or - ``None`` when the stage, its params or the reranker is absent (the - stage is optional and so is its reranker). + Any + The reference with ``params`` reduced to its persistence signature, or + the value unchanged when it is not a component reference. A minimal + ``{component}`` reference is completed with empty params first, so it + has the identity of its explicit form. Raises ------ + ValueError + If *reference* is a retriever reference and no registry was given. RAGPipelineConfigError - If a reranker is stored but is not a component reference. + If *reference* names a component that is malformed. """ - if not parameters: - return None - transformation = parameters.get(RAG_PARAM_QUERY_TRANSFORMATION) - if not transformation: - return None - params = transformation.get(PARAMS_KEY) - if not params: - return None - reranker = params.get(RERANKER_KEY) - if reranker is None: - return None - return _require_reference(reranker, "the query transformation reranker") + canonical = normalize_payload(reference) + if not _names_component(canonical): + return canonical + if registry is None: + raise ValueError( + "CleanupService needs a component registry to compare retriever " + "configurations." + ) + return reference_signature(_component_reference(canonical), registry) -def _require_reference(value: Any, what: str) -> Dict[str, Any]: - """Return ``value`` when it is a component reference, or raise. +def _names_component(value: Any) -> bool: + """Whether a value is an object that carries a ``component`` key. Parameters ---------- value : Any - A stored reference. - what : str - What the reference is, for the error message. + A normalised configuration value. + + Returns + ------- + bool + ``True`` for an object with a ``component`` key, minimal or complete. + """ + return isinstance(value, dict) and COMPONENT_KEY in value + + +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 reference, unchanged. + dict[str, Any] + The stored reference, or ``{}`` when the parameter is absent or null. Raises ------ RAGPipelineConfigError - If ``value`` is not a dict carrying a ``component``. + If the stored value is neither null nor an object. """ - if not isinstance(value, dict) or COMPONENT_KEY not in value: + reference = parameters.get(key) + if reference is None: + return {} + if not isinstance(reference, dict): raise RAGPipelineConfigError( - f"Stored configuration of {what} is not a component reference." + f"Stored parameter {key!r} must be a component reference object." ) - return value + return reference -def _reference_params(reference: Dict[str, Any]) -> Dict[str, Any]: - """Return a reference's normalized ``params``. +def _reranker_reference(parameters: dict[str, Any] | None) -> dict[str, Any]: + """Return the query-transformation reranker reference of session parameters. - A reference without ``params`` is the minimal ``{"component": name}`` the - form stores for a component chosen by name alone, so it has no parameters. + The stage is optional and so is its reranker, so ``{}`` says there is none. Parameters ---------- - reference : Dict[str, Any] - A component reference. + parameters : dict[str, Any] | None + A session's parameters, or ``None`` for a session without any. Returns ------- - Dict[str, Any] - The normalized parameters, empty for the minimal reference. + dict[str, Any] + The ``reranker`` reference nested in ``query_transformation``, or ``{}``. Raises ------ RAGPipelineConfigError - If ``params`` is present and not a dict. + If the stage's params are not an object, or a stored reranker is not an + object. """ - params = reference.get(PARAMS_KEY) + if not parameters: + return {} + transformation = _stored_reference(parameters, RAG_PARAM_QUERY_TRANSFORMATION) + if not transformation: + return {} + params = transformation.get(PARAMS_KEY) if params is None: return {} if not isinstance(params, dict): raise RAGPipelineConfigError( - f"'params' of stored component '{reference[COMPONENT_KEY]}' is not a dict." + "Stored params of the query transformation must be an object." + ) + return _stored_reference(params, RERANKER_KEY) + + +def _component_reference(reference: Any) -> dict[str, Any]: + """Return a stored reference with its ``params`` present. + + A reference stored without ``params`` is the minimal ``{"component": name}`` + the form saves for a component chosen by name alone, so it has no + parameters and is completed with an empty mapping. + + Parameters + ---------- + reference : Any + A stored ``{component, params}`` reference, possibly the minimal form. + + Returns + ------- + dict[str, Any] + The reference with ``params``. + + Raises + ------ + RAGPipelineConfigError + If the value is not an object naming its component, or its ``params`` + is present and not an object. + """ + if not isinstance(reference, dict) or not isinstance( + reference.get(COMPONENT_KEY), str + ): + raise RAGPipelineConfigError( + f"Stored configuration {reference!r} is not a component reference." + ) + if PARAMS_KEY not in reference: + return {**reference, PARAMS_KEY: {}} + params = reference[PARAMS_KEY] + if not isinstance(params, dict): + raise RAGPipelineConfigError( + f"'params' of stored component '{reference[COMPONENT_KEY]}' must be a " + f"dict, got {type(params).__name__}." + ) + 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 normalize_payload(params) + 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: @@ -166,17 +460,65 @@ 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. + + 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 + SQLAlchemy session. + 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): + 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[str, Any], - new_parameters: Optional[Dict[str, Any]] = None, + old_parameters: dict[str, Any], + new_parameters: dict[str, Any] | None = None, *, commit: bool = True, ) -> None: @@ -199,65 +541,20 @@ def cleanup_orphaned_resources( if not old_parameters: return - def _component_changed(key: str) -> bool: - if new_parameters is None: - return True - old_value = old_parameters.get(key) - new_value = new_parameters.get(key) - if key != RAG_PARAM_RETRIEVER_MODEL: - return old_value != new_value - return _retriever_identity(old_value) != _retriever_identity(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", "") - - # 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. - should_cleanup_retriever = bool(retriever_model_params) and ( - _component_changed("retriever_model") + self._release_retriever_and_reranker( + session_id, old_parameters, new_parameters ) - # The retriever stage and the query-transformation reranker store - # their rows under the same pipeline, and one row can serve both - # when they share a configuration. Whatever the new parameters still - # reference must survive the cleanup of the other stage. - protected = self._protected_bridge_ids(session_id, new_parameters) - - if should_cleanup_retriever: - if retriever_component_name in COMPOSITE_RETRIEVER_NAMES: - self._cleanup_composite_retriever( - old_parameters, session_id, protected - ) - else: - self._cleanup_unit_retriever( - old_parameters, - documents_ids, - retriever_model_params, - session_id, - protected, - ) - - old_reranker = _reranker_reference(old_parameters) - if old_reranker is not None and ( - new_parameters is None - or _retriever_identity(old_reranker) - != _retriever_identity(_reranker_reference(new_parameters)) - ): - self._cleanup_reranker( - old_reranker, documents_ids, session_id, protected - ) - # ── 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") + self._component_changed( + RAG_PARAM_CHUNKING_MODEL, old_parameters, new_parameters + ) ) if should_cleanup_chunking: @@ -276,6 +573,124 @@ def _component_changed(key: str) -> bool: # ── Private helpers ── + def _component_changed( + self, + key: str, + old_parameters: dict[str, Any], + new_parameters: dict[str, Any] | None, + ) -> bool: + """Whether one parameter of the session really changed. + + Parameters + ---------- + key : str + Session parameter name, such as ``retriever_model``. + old_parameters : dict[str, Any] + The session's parameters before the change. + new_parameters : dict[str, Any] | None + The parameters after the change, or ``None`` on full session deletion. + + 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 configs_equal(old_value, new_value): + return False + if key != RAG_PARAM_RETRIEVER_MODEL: + return True + return self._retriever_changed(old_value, new_value) + + def _release_retriever_and_reranker( + self, + session_id: int, + old_parameters: dict[str, Any], + new_parameters: dict[str, Any] | None, + ) -> None: + """Release the retriever and reranker rows a parameter change replaces. + + The retriever rows deleted here 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 _release_dense_storage -- *are* shared, and are guarded where they + are deleted. + + The retriever stage and the query-transformation reranker store their rows + under the same pipeline, and one row can serve both when their + configurations are equal. Whatever the new parameters still reference must + survive the cleanup of the other stage. + + Parameters + ---------- + session_id : int + Generative session identifier. + old_parameters : dict[str, Any] + The session's parameters before the change, not empty. + new_parameters : dict[str, Any] | None + The parameters after the change, or ``None`` on full session deletion. + """ + retriever_model_params = _stored_reference( + old_parameters, RAG_PARAM_RETRIEVER_MODEL + ) + should_cleanup_retriever = bool(retriever_model_params) and ( + self._component_changed( + RAG_PARAM_RETRIEVER_MODEL, old_parameters, new_parameters + ) + ) + old_reranker = _reranker_reference(old_parameters) + should_cleanup_reranker = bool(old_reranker) and self._reranker_changed( + old_reranker, new_parameters + ) + protected: set[int] = set() + if should_cleanup_retriever or should_cleanup_reranker: + protected = self._protected_bridge_ids(session_id, new_parameters) + if should_cleanup_retriever: + self._cleanup_retriever(old_parameters, session_id, protected) + if should_cleanup_reranker: + self._cleanup_reranker(old_reranker, session_id, protected) + + 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 + 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. @@ -310,6 +725,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: @@ -333,12 +785,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] = () @@ -362,24 +809,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() ) - if exclude_ids: - query = query.filter(RAGEmbeddingMatrix.id.notin_(list(exclude_ids))) - return bool(query.count()) + 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) + ) + 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 ------- @@ -388,10 +913,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( @@ -400,454 +921,406 @@ def _embedding_model_in_use( .count() ) - def _select_unit_bridge( - self, pipeline_id: int, reference: Dict[str, Any], protected: Set[int] - ) -> Optional[RAGRetriever]: - """Pick the bridge row that realizes a unit retriever reference. - - The row whose stored parameters equal the reference is preferred. A - pipeline also holds the reranker's rows, which can share the class name, - so a lookup by class name alone could return the wrong one; it is only - the fallback for rows whose parameters no longer match, and it never - returns a protected row. + def _find_pipeline_id(self, session_id: int) -> int | None: + """Find pipeline DB record ID for a session. Args: - pipeline_id: The owning pipeline. - reference: The ``{component, params}`` retriever reference. - protected: Bridge ids that must not be selected. + session_id: Generative session identifier. Returns: - The bridge to delete, or ``None`` when there is none. + The pipeline record id, or ``None`` if no pipeline exists. """ - for bridge in self._matching_bridges(pipeline_id, reference): - if bridge.id not in protected: - return bridge - candidates = ( - self.db.query(RAGRetriever) - .filter( - RAGRetriever.pipeline_id == pipeline_id, - RAGRetriever.class_name == reference[COMPONENT_KEY], - ) - .order_by(RAGRetriever.id) - .all() - ) - for bridge in candidates: - if bridge.id not in protected: - return bridge - return None + pipeline = self.db.query(RAGPipeline).filter_by(session_id=session_id).first() + return pipeline.id if pipeline else None - def _matching_bridges( - self, pipeline_id: int, reference: Dict[str, Any] - ) -> List[RAGRetriever]: - """Return the bridges that realize a retriever reference exactly. + def _cleanup_retriever( + self, + old_parameters: dict[str, Any], + session_id: int, + protected: set[int], + ) -> None: + """Release the retriever bridges that a session's parameter update replaces. + + 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, and so is every protected bridge (the trees the new parameters + still reference, such as a reranker that shares the class). The matrices + and models of the dense leaves that were deleted are released by + :meth:`_release_dense_storage`. - Args: - pipeline_id: The owning pipeline. - reference: A ``{component, params}`` retriever reference. + Parameters + ---------- + old_parameters : dict[str, Any] + Session parameters before the update, holding the old retriever. + session_id : int + Generative session identifier. + protected : set[int] + Bridge ids the session's new parameters still reference. + """ + 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, protected) - Returns: - Bridges of the referenced class whose stored parameters (unit) or - ordered children (composite) match the reference. + def _release_class_bridges( + self, session_id: int, class_name: str, protected: set[int] + ) -> None: + """Release every bridge of one class in a session's pipeline. - Raises: - RAGPipelineConfigError: If the reference or one of its children is - malformed. + Parameters + ---------- + session_id : int + Generative session identifier. + class_name : str + The class whose bridges are released, composite or unit. + protected : set[int] + Bridge ids that survive, even when they share the class. """ - component = reference[COMPONENT_KEY] - params = _reference_params(reference) - candidates = ( - self.db.query(RAGRetriever) - .filter( - RAGRetriever.pipeline_id == pipeline_id, - RAGRetriever.class_name == component, - ) - .all() + 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. 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._keep_roots(pipeline_id, bridge_ids, protected), + frozenset(), ) - matches: List[RAGRetriever] = [] - for bridge in candidates: - if self._bridge_matches(bridge, component, params): - matches.append(bridge) - return matches + self._release_dense_storage(release) - def _bridge_matches( - self, bridge: RAGRetriever, component: str, params: Dict[str, Any] - ) -> bool: - """Check whether a bridge row realizes a component with these params. + def _keep_roots( + self, pipeline_id: int, released: Sequence[int], protected: set[int] + ) -> list[int]: + """List the roots whose trees must survive a release of ``released``. - Args: - bridge: The candidate bridge row. - component: The referenced component name. - params: The referenced, normalized parameters. + Parameters + ---------- + pipeline_id : int + The pipeline being released. + released : Sequence[int] + Bridge ids being released, whose roots are not kept. + protected : set[int] + Bridge ids the session's new parameters still reference. - Returns: - ``True`` when a unit's stored parameters equal the reference - (ignoring the expansion options), or when a composite's ordered - children match the referenced children recursively. - - Raises: - RAGPipelineConfigError: If a composite reference has no list of - children, or one of its children is not a component reference. - """ - if component in COMPOSITE_RETRIEVER_NAMES: - child_refs = params.get(CHILDREN_KEY) - if not isinstance(child_refs, list): - raise RAGPipelineConfigError( - f"Stored composite retriever '{component}' has no list of children." - ) - links = sorted(bridge.children, key=lambda link: link.child_order) - if len(links) != len(child_refs): - return False - for link, child_ref in zip(links, child_refs, strict=True): - child_ref = _require_reference( - child_ref, f"a child of the composite retriever '{component}'" - ) - child = self.db.get(RAGRetriever, link.child_id) - child_name = child_ref[COMPONENT_KEY] - if child is None or child.class_name != child_name: - return False - child_params = _reference_params(child_ref) - if not self._bridge_matches(child, child_name, child_params): - return False - return True - detail = bridge.dense_detail or bridge.sparse_detail - if detail is None: - return False - identity = dict(sorted(strip_expansion_options(params).items())) - return detail.parameters == identity + Returns + ------- + list[int] + The other pipeline roots, then the protected bridges in ascending order. + """ + return [ + *self._other_roots(pipeline_id, released), + *sorted(protected), + ] - def _tree_ids(self, bridge: RAGRetriever) -> Set[int]: - """Return the id of a bridge and of every descendant child bridge. + def _reranker_changed( + self, old_reference: dict[str, Any], new_parameters: dict[str, Any] | None + ) -> bool: + """Whether the query-transformation reranker of a session changed. - Args: - bridge: The root bridge row. + Parameters + ---------- + old_reference : dict[str, Any] + The reranker reference before the update, not empty. + new_parameters : dict[str, Any] | None + The parameters after the update, or ``None`` on session deletion. - Returns: - The ids of the whole retriever tree. + Returns + ------- + bool + ``True`` when the reranker was removed or its persistence identity + differs. Identical raw references are never a change. """ - ids = {bridge.id} - for link in bridge.children: - child = self.db.get(RAGRetriever, link.child_id) - if child is not None: - ids |= self._tree_ids(child) - return ids + if new_parameters is None: + return True + new_reference = _reranker_reference(new_parameters) + if configs_equal(old_reference, new_reference): + return False + return self._retriever_changed(old_reference, new_reference) def _protected_bridge_ids( - self, session_id: int, new_parameters: Optional[Dict[str, Any]] - ) -> Set[int]: - """Collect the bridge rows the session's new parameters still use. + self, session_id: int, new_parameters: dict[str, Any] | None + ) -> set[int]: + """Collect the bridge rows the session's new parameters still reference. - The retriever stage and the reranker keep their rows under one - pipeline, and a row serves both when their configurations are equal. - Deleting the old rows of one stage must not take the other stage's. - - Args: - session_id: Generative session identifier. - new_parameters: The parameters after the change, or ``None`` when - the session is being deleted (nothing is protected). + Matching is by stored shape: a bridge is protected when its fitted + parameters, or its ordered children, equal the persistence signature of + a reference the new parameters carry. Both the retriever and the + reranker are protected. - Returns: - The ids of every bridge in the trees the new parameters reference. + Parameters + ---------- + session_id : int + Generative session identifier. + new_parameters : dict[str, Any] | None + The parameters after the change, or ``None`` when the session is + being deleted (nothing is protected). - Raises: - RAGPipelineConfigError: If a stored reference is malformed. + Returns + ------- + set[int] + The ids of the bridges that realize a reference of the new parameters. + + Raises + ------ + RAGPipelineConfigError + If a stored reference is malformed. + ValueError + If a reference must be compared and no registry was given. """ if new_parameters is None: return set() pipeline_id = self._find_pipeline_id(session_id) if pipeline_id is None: return set() - retriever = new_parameters.get(RAG_PARAM_RETRIEVER_MODEL) - references: List[Dict[str, Any]] = [] - if retriever is not None: - references.append(_require_reference(retriever, "the retriever")) - reranker = _reranker_reference(new_parameters) - if reranker is not None: - references.append(reranker) - protected: Set[int] = set() + references = [ + _stored_reference(new_parameters, RAG_PARAM_RETRIEVER_MODEL), + _reranker_reference(new_parameters), + ] + protected: set[int] = set() for reference in references: for bridge in self._matching_bridges(pipeline_id, reference): - protected |= self._tree_ids(bridge) + protected.add(bridge.id) return protected - def _cleanup_reranker( - self, - reference: Dict[str, Any], - documents_ids: List[int], - session_id: int, - protected: Set[int], - ) -> None: - """Delete the rows the query-transformation reranker owned. - - Only rows that match the old reranker reference exactly are removed, so - the retriever stage's rows are never swept by class name. - - Args: - reference: The old ``{component, params}`` reranker reference. - documents_ids: Document ids whose embeddings to delete. - session_id: Generative session identifier. - protected: Bridge ids the session's new parameters still use. - """ - pipeline_id = self._find_pipeline_id(session_id) - if pipeline_id is None: - return - for bridge in self._matching_bridges(pipeline_id, reference): - if bridge.id not in protected: - self._delete_bridge_tree(bridge, documents_ids, protected) - - def _delete_bridge_tree( - self, bridge: RAGRetriever, documents_ids: List[int], protected: Set[int] - ) -> None: - """Delete a bridge, its descendants and the resources they own. + def _matching_bridges( + self, pipeline_id: int, reference: dict[str, Any] + ) -> list[RAGRetriever]: + """Return the bridges that realize a retriever reference exactly. - Args: - bridge: The root bridge row. - documents_ids: Document ids whose embeddings to delete. - protected: Bridge ids that must survive. - """ - for link in list(bridge.children): - child = self.db.get(RAGRetriever, link.child_id) - if child is not None and child.id not in protected: - self._delete_bridge_tree(child, documents_ids, protected) - if bridge.dense_detail is not None: - self._cleanup_dense_retriever(bridge, documents_ids, protected) - elif bridge.sparse_detail is not None: - self._cleanup_sparse_retriever(bridge) - self.db.delete(bridge) + The reference is reduced to its persistence signature, the same identity + the bridges were stored under. A unit bridge matches when its fitted + parameters equal that signature; a composite matches when its ordered + children match the signature's children recursively. - def _find_pipeline_id(self, session_id: int) -> Optional[int]: - """Find pipeline DB record ID for a session. + Parameters + ---------- + pipeline_id : int + The owning pipeline. + reference : dict[str, Any] + A ``{component, params}`` reference, or ``{}`` for none. - Args: - session_id: Generative session identifier. + Returns + ------- + list[RAGRetriever] + The matching bridges, empty for ``{}``. - Returns: - The pipeline record id, or ``None`` if no pipeline exists. + Raises + ------ + RAGPipelineConfigError + If the reference or one of its children is malformed. """ - 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[str, Any], - session_id: int, - protected: Set[int], - ) -> None: - """Cascade-delete a composite retriever and its children. + if not reference: + return [] + identity = _retriever_identity(_component_reference(reference), self._registry) + component = identity[COMPONENT_KEY] + candidates = ( + self.db.query(RAGRetriever) + .filter( + RAGRetriever.pipeline_id == pipeline_id, + RAGRetriever.class_name == component, + ) + .order_by(RAGRetriever.id) + .all() + ) + matches: list[RAGRetriever] = [] + for bridge in candidates: + if self._bridge_matches(bridge, identity): + matches.append(bridge) + return matches - The composite is found by its stored shape, like a unit retriever: the - bridges of the old reference's class whose ordered children match the - reference. Only when none matches does the cleanup fall back to - sweeping every unprotected bridge of that class. That fallback exists - for rows whose stored children no longer equal the saved reference (for - example the duplicates the setup inserted every turn before composite - rows were reused), and its limit is that it cannot tell such a row from - another stage's row of the same class; protected rows are never swept. + def _bridge_matches(self, bridge: RAGRetriever, identity: dict[str, Any]) -> bool: + """Check whether a bridge row realizes a reference's persistence signature. - Then recursively deletes child retrievers (sparse detail storage - folders, dense detail records) and removes the parent bridge record. + Parameters + ---------- + bridge : RAGRetriever + The candidate bridge row, of the reference's class. + identity : dict[str, Any] + A ``{component, params}`` reference reduced to its signature. - Args: - old_parameters: Session parameters containing the retriever - reference. - session_id: Generative session identifier. - protected: Bridge ids the session's new parameters still use; they - are never deleted, even when they share this class name. + Returns + ------- + bool + ``True`` when a unit's fitted parameters equal the signature, or when + a composite's ordered children match its child references. - Raises: - RAGPipelineConfigError: If the stored retriever reference is - malformed. + Raises + ------ + RAGPipelineConfigError + If a composite has no list of children, or a child is malformed. """ - pipeline_id = self._find_pipeline_id(session_id) - if pipeline_id is None: - return - - reference = _require_reference( - old_parameters[RAG_PARAM_RETRIEVER_MODEL], "the retriever" - ) - - composite_bridges = [ - bridge - for bridge in self._matching_bridges(pipeline_id, reference) - if bridge.id not in protected - ] - if not composite_bridges: - composite_bridges = ( - self.db.query(RAGRetriever) - .filter( - RAGRetriever.pipeline_id == pipeline_id, - RAGRetriever.class_name == reference[COMPONENT_KEY], - RAGRetriever.id.notin_(list(protected)), - ) - .order_by(RAGRetriever.id) - .all() + if bridge.class_name != identity[COMPONENT_KEY]: + return False + params = identity[PARAMS_KEY] + if identity[COMPONENT_KEY] not in COMPOSITE_RETRIEVER_NAMES: + if bridge.dense_detail is not None: + detail = bridge.dense_detail + else: + detail = bridge.sparse_detail + return detail is not None and configs_equal(detail.parameters, params) + child_refs = params.get(CHILDREN_KEY) + if not isinstance(child_refs, list): + raise RAGPipelineConfigError( + f"Stored composite retriever '{identity[COMPONENT_KEY]}' has no " + "list of children." ) + links = sorted(bridge.children, key=lambda link: link.child_order) + if len(links) != len(child_refs): + return False + for link, child_ref in zip(links, child_refs, strict=True): + child = self.db.get(RAGRetriever, link.child_id) + if child is None or not self._bridge_matches( + child, _component_reference(child_ref) + ): + return False + return True - 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 or child_bridge.id in protected: - 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) - - def _cleanup_unit_retriever( + def _cleanup_reranker( self, - old_parameters: Dict[str, Any], - documents_ids: List[int], - retriever_model_params: Dict[str, Any], + reference: dict[str, Any], session_id: int, - protected: Set[int], + protected: set[int], ) -> None: - """Cascade-delete a unit retriever (dense or sparse). + """Release the rows the query-transformation reranker owned. - Determines retriever type by inspecting the bridge relationship - (``dense_detail`` vs ``sparse_detail``) rather than parameter heuristics. + The reranker is released like a retriever, but its rows are matched by + the stored shape of its old reference, never by class name, so the + retriever stage's rows of the same class are not swept. A matched tree + is released top-down, except for what a surviving or protected tree + still reads. Its dense matrices and models go through + :meth:`_release_dense_storage`, which keeps any pair a surviving dense + leaf reads. - 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. - protected: Bridge ids the session's new parameters still use. + Parameters + ---------- + reference : dict[str, Any] + The old ``{component, params}`` reranker reference. + session_id : int + Generative session identifier. + protected : set[int] + Bridge ids the session's new parameters still reference. """ pipeline_id = self._find_pipeline_id(session_id) if pipeline_id is None: return - - bridge = self._select_unit_bridge( - pipeline_id, retriever_model_params, protected - ) - if bridge is None: + bridge_ids = [ + bridge.id for bridge in self._matching_bridges(pipeline_id, reference) + ] + if not bridge_ids: return + release = self._release_bridge_trees( + bridge_ids, + self._keep_roots(pipeline_id, bridge_ids, protected), + frozenset(), + ) + self._release_dense_storage(release) - if bridge.dense_detail is not None: - self._cleanup_dense_retriever(bridge, documents_ids, protected) - elif bridge.sparse_detail is not None: - self._cleanup_sparse_retriever(bridge) - self.db.delete(bridge) - - def _matrices_used_by_protected( - self, dense_retriever: RAGDenseRetriever, protected: Set[int] - ) -> bool: - """Whether a protected dense retriever shares this one's matrices. - - Embedding matrices are keyed by chunk set, embedding model and document, - not by retriever, so two dense retrievers with the same embedding over - the same chunks (a retriever and a reranker that differ only in - ``top_k``) read the same matrices. + 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. - Args: - dense_retriever: The dense detail being deleted. - protected: Bridge ids the session's new parameters still use. + Parameters + ---------- + pipeline_id : int + The pipeline whose bridges are listed. + class_name : str + The retriever class to match. - Returns: - ``True`` when a protected dense retriever uses the same chunk set and - embedding model, so the matrices must stay. + Returns + ------- + list[int] + The matching bridge ids, ascending. """ - if not protected: - return False - return bool( - self.db.query(RAGDenseRetriever) + rows = ( + self.db.query(RAGRetriever.id) .filter( - RAGDenseRetriever.bridge_id.in_(list(protected)), - RAGDenseRetriever.id != dense_retriever.id, - RAGDenseRetriever.chunk_set_id == dense_retriever.chunk_set_id, - RAGDenseRetriever.embedding_model_id - == dense_retriever.embedding_model_id, + RAGRetriever.pipeline_id == pipeline_id, + RAGRetriever.class_name == class_name, ) - .count() + .order_by(RAGRetriever.id) + .all() ) + return [row[0] for row in rows] - def _cleanup_dense_retriever( - self, - bridge: RAGRetriever, - documents_ids: List[int], - protected: Set[int], - ) -> None: - """Cascade-delete a dense retriever and its embedding resources. + def _release_dense_storage(self, release: _BridgeRelease) -> None: + """Release the matrices and embedding models that deleted dense leaves used. - Removes embedding matrix storage folders, deletes matrix DB records, - the embedding model record, and the dense detail record. The matrices - stay when a protected dense retriever still reads them (see - :meth:`_matrices_used_by_protected`). + 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. - Args: - bridge: The bridge record for the dense retriever. - documents_ids: Document ids whose embeddings to delete. - protected: Bridge ids the session's new parameters still use. + Parameters + ---------- + release : _BridgeRelease + The release whose dense leaves were deleted. """ - dense_retriever = bridge.dense_detail - chunk_set_id = dense_retriever.chunk_set_id - embedding_model_id = dense_retriever.embedding_model_id - - if self._matrices_used_by_protected(dense_retriever, protected): - embedding_matrices: List[RAGEmbeddingMatrix] = [] - else: - embedding_matrices = ( + 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 == embedding_model_id, - RAGEmbeddingMatrix.document_id.in_(documents_ids), + RAGEmbeddingMatrix.embedding_model_id == model_id, ) .all() ) + model_ids |= self._drop_matrices(matrices) + self.db.flush() + self._release_unused_models(model_ids) - matrix_ids = [matrix.id for matrix in embedding_matrices] - for matrix in embedding_matrices: - if not self._embedding_folder_in_use( - matrix.storage_folder, exclude_ids=matrix_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) + 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. - self.db.delete(dense_retriever) + Parameters + ---------- + chunk_set_id : int + embedding_model_id : int - def _cleanup_sparse_retriever( - self, - bridge: RAGRetriever, - ) -> None: - """Cascade-delete a sparse retriever and its storage folder. + Returns + ------- + bool + """ + readers = ( + self.db.query(RAGDenseRetriever) + .filter( + RAGDenseRetriever.chunk_set_id == chunk_set_id, + RAGDenseRetriever.embedding_model_id == embedding_model_id, + ) + .count() + ) + return readers > 0 - 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 _delete_bridge_row(self, bridge: RAGRetriever) -> None: + """Delete a bridge row and every child link that points at it. - Args: - bridge: The bridge record for the sparse retriever. + 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. + + Every deletion of a bridge goes through here, the composites and the + leaves of :meth:`_release_bridge_trees` alike. + + Parameters + ---------- + bridge : RAGRetriever + The bridge row to delete. """ - 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) + self.db.query(RAGRetrieverChild).filter( + RAGRetrieverChild.child_id == bridge.id + ).delete(synchronize_session="fetch") + self.db.delete(bridge) def invalidate_session_artifacts( self, session_id: int, *, commit: bool = True @@ -864,12 +1337,12 @@ def invalidate_session_artifacts( commit : bool When ``False`` the caller owns the transaction and commits it. """ - chunk_set_ids = [ - row[0] - for row in self.db.query(RAGChunkSet.id) - .filter(RAGChunkSet.session_id == session_id) - .all() - ] + rows = self.db.query(RAGChunkSet.id).filter( + RAGChunkSet.session_id == session_id + ) + 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: @@ -893,12 +1366,10 @@ def invalidate_legacy_artifacts(self, *, commit: bool = True) -> int: int Number of chunk sets deleted. """ - chunk_set_ids = [ - row[0] - for row in self.db.query(RAGChunkSet.id) - .filter(RAGChunkSet.session_id.is_(None)) - .all() - ] + 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: @@ -909,103 +1380,1152 @@ 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, 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. + 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. """ - 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) + 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() ) - dense_links = ( - self.db.query(RAGDenseRetriever, RAGRetriever) - .join(RAGRetriever, RAGDenseRetriever.bridge_id == RAGRetriever.id) + 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) - 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_chunk_set_trees(self, doomed: frozenset[int]) -> _BridgeRelease: + """Release the pipeline trees that hold doomed leaves. - sparse_ids = [detail.id for detail, _bridge in sparse_links] + 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. - 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) + Parameters + ---------- + doomed : frozenset[int] + Bridge ids of the leaves that read the chunk set being invalidated. - 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() - ) - doomed_matrix_ids = [ - matrix.id for matrices in dense_matrices.values() for matrix in matrices - ] + 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) - 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) + 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 stray_root_ids(self, session_id: int) -> list[int]: + """List the pipeline roots that match neither the retriever nor the reranker. + + A healthy session has the retriever's tree and, when its stored parameters + carry a reranker stored as its own tree, the reranker's tree. A pipeline + with one root has no stray one, since its retriever and reranker share it + or the reranker has no row. With more roots, a root is stray when neither + stored reference realizes it, by stored shape. A session without stored + parameters names neither, so every root of its pipeline is stray. + + Parameters + ---------- + session_id : int + Generative session identifier. + + Returns + ------- + list[int] + The stray root bridge ids, ascending. Empty for a healthy session. + + Raises + ------ + RAGPipelineConfigError + If a stored reference is malformed. + ValueError + If a reference must be compared and no registry was given. + """ + pipeline_id = self._find_pipeline_id(session_id) + if pipeline_id is None: + return [] + roots = self._pipeline_root_ids(pipeline_id) + if len(roots) <= 1: + return [] + session = self.db.get(GenerativeSession, session_id) + parameters: dict[str, Any] = {} + if session is not None and session.parameters is not None: + parameters = session.parameters + expected: set[int] = set() + references = [ + _stored_reference(parameters, RAG_PARAM_RETRIEVER_MODEL), + _reranker_reference(parameters), + ] + for reference in references: + for bridge in self._matching_bridges(pipeline_id, reference): + expected.add(bridge.id) + stray: list[int] = [] + for root_id in roots: + if root_id not in expected: + stray.append(root_id) + return stray + + 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) - self.db.delete(bridge) + for bridge in leaves: + self._delete_bridge_row(bridge) + return dense_pairs - 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 _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. + + 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=doomed_ids + ): + 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, + live_reranker_root_bridge_id: int | None, + ) -> IndexCleanupSummary: + """Release what a session's reindex left behind, in one transaction. + + The live index is the tree under ``live_root_bridge_id`` together with + the tree under ``live_reranker_root_bridge_id`` when the session has a + query-transformation reranker. The reranker shares the index's chunk set + and may share rows with the retriever, so both trees are live: a stale + release never takes a row either of them reaches. Each root's tree + holds every bridge reached through the child links. The 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. + + 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. + live_reranker_root_bridge_id : int | None + Bridge id of the root of the reranker the reindex built. ``None`` when + the reindex built none, which is normal for a session whose reranker + the index job does not build: the session's current reranker rows, the + ones matching its stored reranker on the live chunk set, are then live. + + 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, a root is unknown or belongs to another pipeline, a reranker + root was built although the session's parameters name no reranker, 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, + self._live_root_ids( + session_id, live_root_bridge_id, live_reranker_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, + ) + + def _live_root_ids( + self, + session_id: int, + root_id: int, + reranker_root_id: int | None, + ) -> list[int]: + """List the live roots: the retriever's, and the reranker's current one. + + A reranker root the index built is live as it is. An index that built no + reranker does not mean the session has none: the index job leaves the + query transformation out, so a session with a reranker is usually indexed + this way. Then the session's current reranker rows are live instead (see + :meth:`_current_reranker_roots`), so they are neither released as stale + nor reported as a violation. When nothing matches, nothing is protected. + + A built reranker root that the stored parameters do not name is the + opposite inconsistency, and is refused. + + Parameters + ---------- + session_id : int + The generative session that was just indexed. + root_id : int + Bridge id of the retriever's root. + reranker_root_id : int | None + Bridge id of the reranker's root the index built, or ``None``. + + Returns + ------- + list[int] + The retriever root, then the reranker root or roots when there are any. + + Raises + ------ + ValueError + If the session has no record, or a reranker root was built although + the session's stored parameters name none. + RAGPipelineConfigError + If the stored reranker reference is malformed. + """ + session = self.db.get(GenerativeSession, session_id) + if session is None: + raise ValueError(f"Session {session_id} does not exist.") + stored_reranker = _reranker_reference(session.parameters) + if reranker_root_id is not None: + if not stored_reranker: + raise ValueError( + f"The reranker built for session {session_id} does not match its " + "stored parameters; the index is kept and nothing is released." + ) + return [root_id, reranker_root_id] + if not stored_reranker: + return [root_id] + current = self._current_reranker_roots(session_id, root_id, stored_reranker) + return [root_id, *current] + + def _current_reranker_roots( + self, session_id: int, root_id: int, reference: dict[str, Any] + ) -> list[int]: + """List the bridges that realize the stored reranker on the live chunk set. + + A bridge is current when it matches the stored reranker reference by + shape and every leaf under it reads the chunk set the retriever's live + tree reads. A matching tree over an older chunk set is not current: it + is stale, and the next build recreates the reranker on the live chunk set. + + Parameters + ---------- + session_id : int + The generative session that was just indexed. + root_id : int + Bridge id of the retriever's root, which fixes the live chunk set. + reference : dict[str, Any] + The stored ``{component, params}`` reranker reference, not empty. + + Returns + ------- + list[int] + The current reranker bridge ids, ascending. Empty when none matches. + """ + pipeline_id = self._find_pipeline_id(session_id) + if pipeline_id is None: + return [] + live_chunk_sets = self._tree_chunk_sets([root_id]) + current: list[int] = [] + for bridge in self._matching_bridges(pipeline_id, reference): + if self._tree_chunk_sets([bridge.id]) == live_chunk_sets: + current.append(bridge.id) + return current + + def _tree_chunk_sets(self, root_ids: Sequence[int]) -> set[int]: + """List the chunk sets that every leaf under the given roots reads. + + Parameters + ---------- + root_ids : Sequence[int] + The roots whose trees are read. + + Returns + ------- + set[int] + The chunk set ids of the sparse and dense leaves of the trees. + """ + bridge_ids = self._tree_order(root_ids) + sparse_rows = ( + self.db.query(RAGSparseRetriever.chunk_set_id) + .filter(RAGSparseRetriever.bridge_id.in_(bridge_ids)) + .all() + ) + dense_rows = ( + self.db.query(RAGDenseRetriever.chunk_set_id) + .filter(RAGDenseRetriever.bridge_id.in_(bridge_ids)) + .all() + ) + chunk_sets: set[int] = set() + for row in sparse_rows + dense_rows: + chunk_sets.add(row[0]) + return chunk_sets + + def _live_index(self, session_id: int, root_ids: Sequence[int]) -> _LiveIndex: + """Resolve and validate the live index rooted at ``root_ids``. + + Parameters + ---------- + session_id : int + The generative session that owns the index. + root_ids : Sequence[int] + The root bridges of the index, the retriever and the reranker. Each + must belong to the session's pipeline. + + Returns + ------- + _LiveIndex + + Raises + ------ + ValueError + If the session has no pipeline, or a root is unknown or belongs to + another pipeline. + """ + 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.") + bridge_ids: set[int] = set() + for root_id in root_ids: + 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_ids=frozenset(root_ids), + chunk_set_id=leaves.chunk_set_id, + dense_model_ids=leaves.dense_model_ids, + ) + + def _assert_same_pipeline( + self, session_id: int, bridge_ids: set[int], pipeline_id: int + ) -> None: + """Refuse a live tree that reaches a bridge of another pipeline. + + 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 + 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. + """ + ids = list(bridge_ids) + sparse = ( + self.db.query(RAGSparseRetriever) + .filter(RAGSparseRetriever.bridge_id.in_(ids)) + .all() + ) + 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 _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. + + 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 + ---------- + session_id : int + live_chunk_set_id : int + The chunk set the live retriever reads, which is kept. + + Returns + ------- + int + Number of chunk sets invalidated. + """ + 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) + return len(stale_ids) + + def _release_stale_bridges(self, live: _LiveIndex) -> _BridgeRelease: + """Release every pipeline tree other than the live one. + + The roots of the other trees are torn down top-down, so composites nested + at any depth go with their children. The live roots are kept, and with + them every bridge the live trees reach, the reranker's included. A dense + detail is deleted, but its embedding model is left to the caller to + release. + + Parameters + ---------- + live : _LiveIndex + The validated live index, whose trees must survive. + + Returns + ------- + _BridgeRelease + The number of bridges released, and the embedding models their + dense details used. + """ + live_roots = sorted(live.root_ids) + roots = self._other_roots(live.pipeline_id, live_roots) + return self._release_bridge_trees(roots, live_roots, 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) + ) + + 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 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) + ) + for matrix in matrices: + if matrix.embedding_model_id not in live.dense_model_ids: + stale.append(matrix) + return stale + + def _release_unused_models(self, model_ids: set[int]) -> int: + """Delete each given embedding model that no row references any more. + + Parameters + ---------- + model_ids : set[int] + Candidate embedding model ids. + + 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 + + +@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] + ) + ).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), + ) + + +def has_stale_index_rows( + db: Session, session_id: int, registry: ComponentRegistry +) -> bool: + """Whether a session holds rows that a cleanup would release, without a rebuild. + + A healthy session owns one chunk set, the live one. Its pipeline has the + retriever's root and, when the session has a query-transformation reranker + stored as its own tree, the reranker's root as well. Anything beyond those is + left over from a cleanup that failed: a second chunk set, or a root that + neither stored reference realizes. A build that reused its index would never + retry that cleanup, so the chat path asks this as well. It reads two counts + and, only when the pipeline has more than one root, matches the stored + references, so it is cheap enough to ask on every turn. + + Parameters + ---------- + db : Session + SQLAlchemy session. + session_id : int + The generative session to check. + registry : ComponentRegistry + Registry used to match the stored references against the pipeline's rows. + + Returns + ------- + bool + ``True`` when the session owns more than one chunk set, or its pipeline + has a root bridge that neither stored reference realizes. + """ + 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() + ) + if root_count <= 1: + return False + return bool(CleanupService(db, registry).stray_root_ids(session_id)) + + +def run_post_index_cleanup( + db: Session, + registry: ComponentRegistry, + session_id: int, + live_root_bridge_id: int | None, + rag_path: str | Path, + live_reranker_root_bridge_id: int | None, +) -> 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. + live_reranker_root_bridge_id : int | None + Bridge id of the root of the reranker the index built, or ``None`` when + the index built none. A built root must agree with the session's + parameters; with ``None`` the session's current reranker rows are kept. + """ + 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." + ) + summary = CleanupService(db, registry, rag_path=rag_path).cleanup_after_reindex( + session_id, live_root_bridge_id, live_reranker_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/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/embedding_storage_service.py b/DashAI/back/services/RAG/embedding_storage_service.py index d1f092a6a..a2cea5564 100644 --- a/DashAI/back/services/RAG/embedding_storage_service.py +++ b/DashAI/back/services/RAG/embedding_storage_service.py @@ -5,10 +5,10 @@ import shutil 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/index_status_service.py b/DashAI/back/services/RAG/index_status_service.py index 45a14792b..7e4c3d608 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,12 @@ ) 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, + RAGPipelineConfigError, +) from DashAI.back.models.RAG.RAG_constants import ( + COMPOSITE_RETRIEVER_NAMES, RAG_PARAM_CHUNKING_MODEL, RAG_PARAM_DOCUMENTS, RAG_PARAM_RETRIEVER_MODEL, @@ -36,11 +42,17 @@ 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 +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 @@ -162,9 +174,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 {} @@ -238,10 +251,16 @@ def _pipeline_config(self, parameters: Dict[str, Any]) -> Optional[Dict[str, Any chunking = parameters.get(RAG_PARAM_CHUNKING_MODEL) if not isinstance(chunking, dict) or not chunking.get("component"): return None + params = chunking.get(PARAMS_KEY, {}) + if not isinstance(params, dict): + raise RAGPipelineConfigError( + "Stored 'params' of the chunking model is not a dict, got " + f"{type(params).__name__}." + ) return { RAG_PARAM_CHUNKING_MODEL: { "component": chunking["component"], - "params": chunking.get("params") or {}, + "params": params, } } @@ -298,11 +317,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 @@ -366,36 +386,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_db_service.py b/DashAI/back/services/RAG/retriever_db_service.py index d2da2a088..37176d613 100644 --- a/DashAI/back/services/RAG/retriever_db_service.py +++ b/DashAI/back/services/RAG/retriever_db_service.py @@ -255,39 +255,6 @@ def save_dense( # ── Composite retriever ──────────────────────────────────────────── - def find_composite( - self, - class_name: str, - pipeline_id: int, - child_bridge_ids: List[int], - ) -> Optional[RetrieverDBModel]: - """Look up a composite bridge by class, pipeline and ordered children. - - Parameters - ---------- - class_name : str - Composite retriever class name. - pipeline_id : int - Owning pipeline. - child_bridge_ids : list[int] - Ordered child bridge ids (``RAG_retriever.id``). - - Returns - ------- - RetrieverDBModel or None - The matching bridge record, or ``None`` when there is none. - """ - candidates = ( - self.db.query(RetrieverDBModel) - .filter_by(class_name=class_name, pipeline_id=pipeline_id) - .all() - ) - for candidate in candidates: - links = sorted(candidate.children, key=lambda link: link.child_order) - if [link.child_id for link in links] == list(child_bridge_ids): - return candidate - return None - def save_composite( self, class_name: str, @@ -341,6 +308,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_presets.py b/DashAI/back/services/RAG/retriever_presets.py index ebaea0933..692bd009a 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,11 +18,17 @@ default_keyword_retriever, default_semantic_retriever, ) +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, WINDOW_FIELD, - strip_expansion_options, ) +from DashAI.back.services.RAG.config_equality import configs_equal _SEMANTIC_MODEL_SHORT = DEFAULT_SEMANTIC_MODEL_NAME.rsplit("/", 1)[-1] @@ -23,10 +36,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 @@ -108,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 @@ -125,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, @@ -172,33 +229,64 @@ def get_default_retriever(registry, top_k: int = DEFAULT_TOP_K) -> Dict[str, Any ------- Dict[str, Any] The default retriever configuration. + + Raises + ------ + ValueError + If no preset carries the default key. """ - recipe = next( - preset - for preset in get_retriever_presets(top_k, registry) - if preset["key"] == DEFAULT_PRESET_KEY - ) - 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. - - 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). + for preset in get_retriever_presets(top_k, registry): + if preset["key"] == DEFAULT_PRESET_KEY: + return {"component": preset["component"], "params": preset["params"]} + raise ValueError(f"No retriever preset is keyed {DEFAULT_PRESET_KEY!r}.") + + +def _check_children(params: Dict[str, Any]) -> None: + """Check that every composite ``children`` entry is a well-formed ref. + + Nested children are checked too, through each child's own ``params``. + + Parameters + ---------- + params : Dict[str, Any] + Retriever parameters, possibly holding ``children``. + + Raises + ------ + ValueError + If ``children`` is present but is not a list of dicts that each hold a + ``params`` dict. """ - return strip_expansion_options(value, _IGNORED_MATCH_KEYS) + 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__}" + ) + 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}" + ) + _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. - ``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. + 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. + + 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 +301,20 @@ 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, + 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. """ - stripped = _strip_match_ignored_keys(params) + _check_children(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 configs_equal(preset["params"], params, _MATCH_IGNORED_KEYS): return preset["key"] return None @@ -229,6 +325,7 @@ def effective_top_k(component: str, params: Dict[str, Any]) -> int: A composite retriever's own ``top_k`` (when it has one) bounds the result; otherwise the children's values add up. """ + _check_children(params) if "top_k" in params and isinstance(params["top_k"], int): return params["top_k"] if "max_chunks" in params and isinstance(params["max_chunks"], int): @@ -236,9 +333,8 @@ def effective_top_k(component: str, params: Dict[str, Any]) -> int: children = params.get("children") if isinstance(children, list) and children: return sum( - effective_top_k(child.get("component", ""), child.get("params", {}) or {}) + effective_top_k(child.get("component", ""), child[PARAMS_KEY]) for child in children - if isinstance(child, dict) ) return 0 @@ -284,14 +380,13 @@ def max_expansion_factor(params: Dict[str, Any]) -> int: int The maximum ``_expansion_factor`` over this node and its descendants. """ + _check_children(params) factor = _expansion_factor(params) children = params.get("children") if not isinstance(children, list): return factor for child in children: - if not isinstance(child, dict): - continue - child_factor = max_expansion_factor(child.get("params", {}) or {}) + child_factor = max_expansion_factor(child[PARAMS_KEY]) if child_factor > factor: factor = child_factor return factor @@ -346,6 +441,7 @@ def effective_chunk_count(component: str, params: Dict[str, Any]) -> int: int The context cost of this retriever in chunks, expansion included. """ + _check_children(params) cap = _own_chunk_cap(params) if cap is not None: return cap * max_expansion_factor(params) @@ -353,10 +449,6 @@ def effective_chunk_count(component: str, params: Dict[str, Any]) -> int: if isinstance(children, list) and children: base = 0 for child in children: - if not isinstance(child, dict): - continue - base += effective_chunk_count( - child.get("component", ""), child.get("params", {}) or {} - ) + base += effective_chunk_count(child.get("component", ""), child[PARAMS_KEY]) return base * _expansion_factor(params) return effective_top_k(component, params) * _expansion_factor(params) diff --git a/DashAI/back/services/RAG/retriever_setup_service.py b/DashAI/back/services/RAG/retriever_setup_service.py index 98e189320..096509070 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 @@ -40,9 +41,11 @@ 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, + reference_signature, ) +from DashAI.back.models.RAG.retrievers.ref_utils import CHILDREN_KEY, PARAMS_KEY from DashAI.back.models.RAG.retrievers.retriever_factory import ( RetrieverFactory, resolve_component_params, @@ -55,6 +58,10 @@ RetrievalLLMServiceResult, ) 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__) @@ -81,9 +88,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__( @@ -187,7 +196,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 ) @@ -222,15 +231,19 @@ def _setup_composite( Raises: RAGRetrieverEmptyChildrenError: If ``children`` is empty. """ - children_configs = params.get("children", []) + children_configs = params.get(CHILDREN_KEY, []) if not children_configs: raise RAGRetrieverEmptyChildrenError( "Composite retriever must have at least one child" ) children = [self._setup_child(c) for c in children_configs] + own_params: dict[str, Any] = {} + for key, value in params.items(): + if key != CHILDREN_KEY: + own_params[key] = value resolved_params = resolve_component_params( model_class, - {k: v for k, v in params.items() if k != "children"}, + own_params, self._registry, llm_resolver=self._resolve_retrieval_llm, ) @@ -240,20 +253,43 @@ 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, and :meth:`RetrieverDBService.save_composite` returns the existing + root when there is one. Creating a new root on every setup would make an + unchanged index look rebuilt, so the existing root is reused. + + 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. + """ 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( @@ -458,10 +494,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: @@ -480,11 +519,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. @@ -493,9 +532,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( { @@ -509,7 +546,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) @@ -549,7 +586,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, ) @@ -581,7 +618,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 54433bad7..4a1c916be 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 @@ -37,8 +36,6 @@ RAG_MAX_TOKENS, ) -log = logging.getLogger(__name__) - #: Characters per token, for turning prompt text into a token estimate. CHARS_PER_TOKEN = 4 @@ -93,39 +90,6 @@ def _stage_params(transformation: Dict[str, Any]) -> Dict[str, Any]: return params -def _reference_params(reference: Dict[str, Any], what: str) -> Dict[str, Any]: - """Return a stored component reference's ``params``. - - A reference without ``params`` is the minimal ``{"component": name}`` the - form stores for a component chosen by name alone, so it has no parameters. - - Parameters - ---------- - reference : Dict[str, Any] - A stored component reference. - what : str - What the reference is, for the error message. - - Returns - ------- - Dict[str, Any] - The parameters, empty for the minimal reference. - - Raises - ------ - RAGPipelineConfigError - If ``params`` is present and not a dict. - """ - params = reference.get(PARAMS_KEY) - if params is None: - return {} - if not isinstance(params, dict): - raise RAGPipelineConfigError( - f"Stored 'params' of {what} is not a dict, got {type(params).__name__}." - ) - return params - - _SECTION_NAMES = { RAG_PARAM_CHUNKING_MODEL: MultilingualString( en="Chunking", @@ -165,6 +129,121 @@ def _reference_params(reference: Dict[str, Any], what: str) -> Dict[str, Any]: } +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 may omit ``params``: the minimal ``{"component": name}`` + the form stores for a component chosen by name alone has none, and it is not + malformed. When the ``params`` key is present its value must be a dict, so + any other value raises rather than being read as an empty configuration. + + Parameters + ---------- + ref : Dict[str, Any] + A ``{"component", "params"}`` reference, the minimal + ``{"component"}`` reference, or an empty ``{}``. + + Returns + ------- + Dict[str, Any] + The parameters, or an empty dict when the reference carries none. + + Raises + ------ + ValueError + If the reference is not empty and does not name its component as a + string (see :func:`_reference_component`). + RAGPipelineConfigError + If the ``params`` key is present and its value is not a dict. + """ + if not ref: + return {} + component = _reference_component(ref) + if PARAMS_KEY not in ref: + return {} + params = ref[PARAMS_KEY] + if not isinstance(params, dict): + raise RAGPipelineConfigError( + f"Stored 'params' of component {component!r} is not a dict, " + f"got {type(params).__name__}." + ) + 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.""" @@ -200,12 +279,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 @@ -234,9 +317,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") @@ -247,15 +332,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) @@ -273,7 +354,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 @@ -324,8 +405,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, @@ -355,8 +435,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: @@ -398,7 +478,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 @@ -455,11 +535,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) @@ -490,9 +570,9 @@ def _retrieval_chunk_count( The number of chunks the prompt can hold, expansion and reranker cap included. """ - retriever_params = _reference_params(retriever, "the retriever") + retriever_params = _reference_params(retriever) retrieved = retriever_presets.effective_chunk_count( - retriever[COMPONENT_KEY], retriever_params + _reference_component(retriever), retriever_params ) queries = self._query_count(transformation) if queries <= SINGLE_QUERY: @@ -645,7 +725,7 @@ def _pool_cap(self, transformation: Optional[Dict[str, Any]]) -> Optional[int]: "reference." ) return retriever_presets.effective_top_k( - reranker[COMPONENT_KEY], _reference_params(reranker, "the reranker") + reranker[COMPONENT_KEY], _reference_params(reranker) ) def _context_budget( @@ -684,7 +764,7 @@ def _context_budget( The window, the tokens already committed and what is left, plus whether the configuration fits. """ - 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 @@ -695,8 +775,7 @@ def _context_budget( chunk_count = self._retrieval_chunk_count(retriever, transformation) 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/DashAI/back/services/workflows/RAG_workflow_session_service.py b/DashAI/back/services/workflows/RAG_workflow_session_service.py index 0f74b2e90..fdb5ca1ba 100644 --- a/DashAI/back/services/workflows/RAG_workflow_session_service.py +++ b/DashAI/back/services/workflows/RAG_workflow_session_service.py @@ -16,6 +16,7 @@ RAG_PARAM_GENERATION_MODEL, ) from DashAI.back.services.RAG.cleanup_service import CleanupService +from DashAI.back.services.RAG.config_equality import configs_equal from DashAI.back.services.RAG.index_job_service import cancel_live_index_job from DashAI.back.services.RAG.prompt_service import ( PromptConflictError, @@ -445,7 +446,14 @@ def is_unchanged( bool True when the save would record nothing new. """ - if updated_parameters != old_parameters: + try: + same_configuration = configs_equal(old_parameters, updated_parameters) + except (TypeError, ValueError): + # A value outside the comparison contract, such as an integer beyond + # the safe range, cannot be shown equal. The save then proceeds as a + # change instead of failing the request. + same_configuration = False + if not same_configuration: return False with self._write_errors(): preview = self.prompts.preview_session_bindings( @@ -492,7 +500,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/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 a0487c712..8205ea5a2 100644 --- a/DashAI/front/src/components/generative/RAG/RAGConfigPanel.jsx +++ b/DashAI/front/src/components/generative/RAG/RAGConfigPanel.jsx @@ -43,6 +43,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 @@ -57,6 +63,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. * @@ -143,6 +214,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. @@ -155,18 +233,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: "", @@ -193,8 +272,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) @@ -225,12 +302,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; @@ -251,7 +327,7 @@ export default function RAGConfigPanel({ clearTimeout(timer); unsubscribe(); }; - }, [retrieverKey]); + }, [retrieverModel]); const retrieverDownloadMessage = missingRetrieverDownloads.length > 0 ? t("common:componentDownload.mustDownloadNested", { @@ -262,7 +338,7 @@ export default function RAGConfigPanel({ : null; const dirty = useMemo( - () => JSON.stringify(draft) !== JSON.stringify(savedDraft), + () => !sameDraftValue(draft, savedDraft), [draft, savedDraft], ); @@ -272,7 +348,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]); @@ -301,8 +377,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; @@ -414,23 +492,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); }; /** @@ -446,13 +527,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; @@ -466,6 +543,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 ""; @@ -484,8 +570,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/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/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/pages/generative/RAGSession/advanced/CompositeRetrieverBuilder.jsx b/DashAI/front/src/pages/generative/RAGSession/advanced/CompositeRetrieverBuilder.jsx index 57b222021..e864c87c4 100644 --- a/DashAI/front/src/pages/generative/RAGSession/advanced/CompositeRetrieverBuilder.jsx +++ b/DashAI/front/src/pages/generative/RAGSession/advanced/CompositeRetrieverBuilder.jsx @@ -84,13 +84,14 @@ export default function CompositeRetrieverBuilder({ const renderCaption = ({ node, info, findComponent, i18n }) => { const translateLabel = (label) => t(`rag.schemaSummary.labels.${label}`, { defaultValue: label }); + const renderComponentName = buildComponentNameRenderer(findComponent, i18n); return ( resolveRetrieverSchemaSummary( info, node.params, findComponent, translateLabel, - buildComponentNameRenderer(findComponent, i18n), + renderComponentName, ) || resolveRetrieverRepresentation(info, node.params, i18n, findComponent) || resolveLocalizedText(info?.description, i18n) diff --git a/DashAI/front/src/pages/generative/RAGSession/advanced/QueryTransformationAdvancedModal.jsx b/DashAI/front/src/pages/generative/RAGSession/advanced/QueryTransformationAdvancedModal.jsx index c90c31f45..f42bbe3d8 100644 --- a/DashAI/front/src/pages/generative/RAGSession/advanced/QueryTransformationAdvancedModal.jsx +++ b/DashAI/front/src/pages/generative/RAGSession/advanced/QueryTransformationAdvancedModal.jsx @@ -14,6 +14,7 @@ import { MAX_SUBQUERIES_KEY, RERANKER_KEY, } from "../../../../constants/rag"; +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"; @@ -69,7 +70,7 @@ function llmParamsToPersist(carriedParams, seedDefaults, values) { const wasCarried = Object.prototype.hasOwnProperty.call(carriedParams, key); const isUntouchedDefault = - JSON.stringify(value) === JSON.stringify(seedDefaults[key]); + seedDefaults[key] !== undefined && deepEqual(value, seedDefaults[key]); if (!wasCarried && isUntouchedDefault) continue; result[key] = value; diff --git a/tests/back/RAG/test_RAG_indexing.py b/tests/back/RAG/test_RAG_indexing.py index a7d17d5d4..e68c8fee8 100644 --- a/tests/back/RAG/test_RAG_indexing.py +++ b/tests/back/RAG/test_RAG_indexing.py @@ -257,8 +257,8 @@ def close(self): index = SimpleNamespace( chunk_set_id=1, total_chunks=1, - retriever=SimpleNamespace(model=retriever), - reranker=SimpleNamespace(model=reranker), + retriever=SimpleNamespace(model=retriever, db_record_id=None), + reranker=SimpleNamespace(model=reranker, db_record_id=None), ) monkeypatch.setattr( SetupService, "build_index", lambda self, config, progress=None: index diff --git a/tests/back/RAG/test_RAG_session_configuration_api.py b/tests/back/RAG/test_RAG_session_configuration_api.py index f1fd1eea0..7f91d50bb 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,31 @@ 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", + "params": "not a dict", + } + 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 +347,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 +367,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 +383,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 +407,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 +459,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_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_cleanup_session_scope.py b/tests/back/RAG/test_cleanup_session_scope.py index 6c2907940..fe7e4ae53 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. @@ -165,8 +191,8 @@ def test_composite_cleanup_keeps_a_shared_sparse_folder(orm_db, tmp_path): "children": [{"component": detail.class_name, "params": detail.parameters}] }, } - CleanupService(orm_db)._cleanup_composite_retriever( - {"retriever_model": reference}, first.id, set() + CleanupService(orm_db).cleanup_orphaned_resources( + first.id, {RAG_PARAM_RETRIEVER_MODEL: reference}, None ) orm_db.flush() @@ -175,7 +201,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_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/back/RAG/test_index_cleanup.py b/tests/back/RAG/test_index_cleanup.py new file mode 100644 index 000000000..5fb47c24f --- /dev/null +++ b/tests/back/RAG/test_index_cleanup.py @@ -0,0 +1,1585 @@ +"""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.models.RAG.RAG_constants import ( + RAG_PARAM_KEYS, + RAG_PARAM_QUERY_TRANSFORMATION, +) +from DashAI.back.models.RAG.RAG_pipeline import RAGPipelineConfig +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.prompt_service import PromptService +from DashAI.back.services.RAG.session_params import filter_pipeline_params +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 +RERANKER_K1 = 2.73 +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, None) + + +# =================================================================== +# 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, None + ) + + 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, None) + state = _counts(orm_db) + + second = service.cleanup_after_reindex(index.session_id, index.root_id, None) + + 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, None + ) + + 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, None + ) + + +# =================================================================== +# 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, live_reranker_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), None + ) + assert any(record.exc_info for record in caplog.records) + + def cancel(self, session_id, live_root_bridge_id, live_reranker_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), None + ) + + +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), None + ) + + 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, live_reranker_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 + + +class _ClosableModel: + """A model stand-in that records whether the index job released it.""" + + def __init__(self) -> None: + self.closed = 0 + + def close(self) -> None: + self.closed += 1 + + +@pytest.mark.usefixtures("_register_stub_llm") +def test_index_job_hands_the_reranker_root_to_the_cleanup( + client: TestClient, document_files: list[str], monkeypatch +): + """The index job passes the reranker's bridge id, so its rows count as live.""" + session_id, _ = _create_session_with_document( + client, "index_reranker_root", document_files + ) + retriever_model, reranker_model = _ClosableModel(), _ClosableModel() + index = SimpleNamespace( + chunk_set_id=1, + total_chunks=1, + retriever=SimpleNamespace(db_record_id=11, model=retriever_model), + reranker=SimpleNamespace(db_record_id=22, model=reranker_model), + ) + calls: list[tuple] = [] + monkeypatch.setattr( + SetupService, "build_index", lambda self, config, progress=None: 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, 11, rag_path, 22)] + assert retriever_model.closed == 1 + assert reranker_model.closed == 1 + + +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), + reranker=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, None)] + + +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, None) + + +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, live_reranker_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, None) + + +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(client: TestClient, orm_db, tmp_path): + """The probe is false for a clean index and true once a stale root or set exists.""" + registry = client.app.container["component_registry"] + 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, registry) is True + + _cleanup(orm_db, index) + assert cleanup_service.has_stale_index_rows(orm_db, session.id, registry) 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, registry) is True + + +def test_stale_row_probe_is_false_for_a_session_without_rows( + client: TestClient, orm_db +): + """A session that never indexed has nothing to clean.""" + registry = client.app.container["component_registry"] + session = _insert_rag_session(orm_db, f"probe_empty_{uuid.uuid4().hex[:8]}") + + assert cleanup_service.has_stale_index_rows(orm_db, session.id, registry) 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" + + +# =================================================================== +# The index job against a reranker it does not build +# =================================================================== + + +def _store_reranked_parameters(client: TestClient, session_id: int) -> None: + """Store a BM25 retriever and a query transformation whose reranker is BM25.""" + session_factory = client.app.container["session_factory"] + with session_factory() as db: + session = db.get(GenerativeSession, session_id) + parameters = dict(session.parameters or {}) + parameters["retriever_model"] = { + "component": SPARSE_CLASS, + "params": {**bm25_retriever_params(), "k1": LIVE_K1}, + } + reranker = { + "component": SPARSE_CLASS, + "params": {**bm25_retriever_params(), "k1": RERANKER_K1}, + } + parameters["query_transformation"] = { + "component": "LLMQueryExpander", + "params": {"n_queries": 2, "reranker": reranker}, + } + session.parameters = parameters + db.commit() + + +def _build_with_transformation(client: TestClient, session_id: int) -> int: + """Build the session's index with its query transformation, as a chat turn does. + + The index job never builds the transformation, so the reranker rows this + build leaves are the reranker's current rows. + + Returns + ------- + int + The bridge id of the reranker the build created. + """ + container = client.app.container + registry = container["component_registry"] + rag_path = container["config"]["RAG_PATH"] + with container["session_factory"]() as db: + session = db.get(GenerativeSession, session_id) + materialized = PromptService(db, registry).materialize_session_parameters( + session_id, dict(session.parameters) + ) + clean = filter_pipeline_params( + materialized, {*RAG_PARAM_KEYS, RAG_PARAM_QUERY_TRANSFORMATION} + ) + config = RAGPipelineConfig.from_kwargs( + db=db, + component_registry=registry, + session_id=session_id, + env_RAG_path=rag_path, + **clean, + ) + result = SetupService(db, registry, rag_path).build_index(config) + try: + return result.reranker.db_record_id + finally: + SetupService.release_index(result) + + +@pytest.mark.usefixtures("_register_stub_llm") +def test_index_job_keeps_a_reranker_it_did_not_build( + client: TestClient, document_files: list[str], caplog +): + """The reranker built with the transformation survives an index-job rebuild. + + The index job filters out the query transformation, so it builds no + reranker. The rows built with the transformation are still the session's + current reranker, so the post-index cleanup keeps them and logs no error. + """ + session_id, _ = _create_session_with_document( + client, "index_unbuilt_reranker", document_files + ) + _store_reranked_parameters(client, session_id) + reranker_root = _build_with_transformation(client, session_id) + + with caplog.at_level(logging.ERROR, logger=cleanup_service.__name__): + RAGIndexJob(session_id=session_id).run() + + session_factory = client.app.container["session_factory"] + with session_factory() as db: + assert db.get(RAGRetriever, reranker_root) is not None + reranker_row = db.query(RAGSparseRetriever).filter_by(bridge_id=reranker_root) + assert os.path.isdir(reranker_row.one().storage_folder) + cleanup_errors = [ + r + for r in caplog.records + if r.name == cleanup_service.__name__ and r.levelno >= logging.ERROR + ] + assert not cleanup_errors + + +def test_index_job_refuses_a_session_without_stored_parameters( + client: TestClient, document_files: list[str] +): + """A session with no stored parameters is refused, as the chat job refuses it.""" + session_id, _ = _create_session_with_document( + client, "index_no_params", document_files + ) + session_factory = client.app.container["session_factory"] + with session_factory() as db: + db.get(GenerativeSession, session_id).parameters = None + db.commit() + + with pytest.raises(JobError, match="no stored parameters"): + RAGIndexJob(session_id=session_id).run() diff --git a/tests/back/RAG/test_reranker_cleanup_combinations.py b/tests/back/RAG/test_reranker_cleanup_combinations.py new file mode 100644 index 000000000..1d8332fbd --- /dev/null +++ b/tests/back/RAG/test_reranker_cleanup_combinations.py @@ -0,0 +1,720 @@ +"""The retriever stage and the reranker share one pipeline's rows during cleanup. + +The reranker keeps its rows under the retriever's pipeline, and one row serves +both stages when their persistence identities are equal. These tests cover the +combinations the release must get right: the post-index release, a change to +one stage only, a nested reranker composite, and dense matrices read by both. +""" + +import logging +import uuid +from dataclasses import dataclass +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy.orm import Session + +import DashAI.back.job.RAG_job as rag_job_module +from DashAI.back.dependencies.database.models import ( + GenerativeSession, + RAGChunkSet, + RAGDenseRetriever, + RAGEmbeddingMatrix, + RAGEmbeddingModel, + RAGRetriever, + RAGRetrieverChild, + RAGSparseRetriever, +) +from DashAI.back.models.RAG.retrievers.persistence_signature import ( + reference_signature, +) +from DashAI.back.services.RAG import cleanup_service +from DashAI.back.services.RAG.cleanup_service import ( + CleanupService, + _retriever_identity, + capture_index_footprint, + has_stale_index_rows, + run_post_index_cleanup, +) +from tests.back.RAG.conftest import _insert_data_document, _insert_rag_session +from tests.back.RAG.test_bridge_tree_cleanup import _assert_sound +from tests.back.RAG.test_index_cleanup import ( + EMBEDDINGS_DIR, + SPARSE_DIR, + _chunk_set, + _embedding_model, + _matrix, + _pipeline, + _rag, + _sparse_bridge, +) +from tests.back.RAG.test_retriever_identity import _registry + +BM25 = "BM25Retriever" +DENSE = "DenseEmbeddingRetriever" +EMBEDDING = "AllMiniLML6V2Embedding" +PARALLEL = "ParallelRetriever" +SEQUENTIAL = "SequentialRetriever" +#: Fitted weightings of the sparse rows. ``k1`` is persistent; ``top_k`` is not. +MAIN_K1 = 2.0 +RETRIEVER_K1 = 2.5 +RERANK_A_K1 = 3.1 +RERANK_B_K1 = 3.2 +RERANK_C_K1 = 3.3 +STALE_K1 = 4.4 + + +@dataclass(frozen=True) +class _Stage: + """A session's pipeline with one chunk set of a document. + + Attributes + ---------- + session_id : int + pipeline_id : int + document_id : int + chunk_set_id : int + rag : Path + The RAG storage root the fitted folders live under. + """ + + session_id: int + pipeline_id: int + document_id: int + chunk_set_id: int + rag: Path + + +def _sparse_ref(k1: float) -> dict[str, Any]: + """Return a BM25 reference, with ``top_k`` left out as it is query-time.""" + return {"component": BM25, "params": {"k1": k1}} + + +def _composite_ref(component: str, children: list[dict[str, Any]]) -> dict[str, Any]: + """Return a composite reference over the given child references, in order.""" + return {"component": component, "params": {"children": children}} + + +def _dense_ref(label: str) -> dict[str, Any]: + """Return a dense reference whose ``label`` tells two rows of one model apart.""" + return { + "component": DENSE, + "params": { + "embedding_model": {"component": EMBEDDING, "params": {}}, + "label": label, + }, + } + + +def _parameters( + retriever: dict[str, Any], reranker: dict[str, Any] | None +) -> dict[str, Any]: + """Return session parameters with a retriever and an optional reranker.""" + transformation: dict[str, Any] = {"component": "LLMQueryExpander", "params": {}} + if reranker is not None: + transformation["params"]["reranker"] = reranker + return { + "documents": [], + "retriever_model": retriever, + "query_transformation": transformation, + } + + +def _stage(db: Session, tmp_path: Path, label: str) -> _Stage: + """Insert a session with a pipeline and one chunk set of a document.""" + session = _insert_rag_session(db, f"combo_{label}_{uuid.uuid4().hex[:8]}") + document = _insert_data_document( + db, tmp_path / "docs", f"{label}_{uuid.uuid4().hex[:6]}.txt", ["t"] + ) + rag = _rag(tmp_path) + pipeline_id = _pipeline(db, session.id) + chunk_set_id = _chunk_set(db, session.id, document.id, rag) + db.commit() + return _Stage( + session_id=session.id, + pipeline_id=pipeline_id, + document_id=document.id, + chunk_set_id=chunk_set_id, + rag=rag, + ) + + +def _leaf(db: Session, stage: _Stage, k1: float, label: str) -> int: + """Insert a sparse leaf over the stage's chunk set and return its bridge id.""" + return _sparse_bridge( + db, + stage.pipeline_id, + stage.chunk_set_id, + stage.rag / SPARSE_DIR / f"{label}_{uuid.uuid4().hex[:6]}", + k1, + ) + + +def _bridge(db: Session, pipeline_id: int, class_name: str, children: list[int]) -> int: + """Insert a composite of the given class over the children, in order.""" + parent = RAGRetriever(class_name=class_name, pipeline_id=pipeline_id) + db.add(parent) + db.flush() + for order, child_id in enumerate(children): + db.add( + RAGRetrieverChild(parent_id=parent.id, child_id=child_id, child_order=order) + ) + db.flush() + return parent.id + + +def _dense_leaf(db: Session, stage: _Stage, label: str, model_id: int) -> int: + """Insert a dense leaf whose stored parameters are its reference's signature.""" + bridge = RAGRetriever(class_name=DENSE, pipeline_id=stage.pipeline_id) + db.add(bridge) + db.flush() + db.add( + RAGDenseRetriever( + bridge_id=bridge.id, + chunk_set_id=stage.chunk_set_id, + class_name=DENSE, + parameters=_dense_ref(label)["params"], + embedding_model_id=model_id, + ) + ) + db.flush() + return bridge.id + + +def _set_parameters(db: Session, session_id: int, parameters: dict[str, Any]) -> None: + """Store the session's parameters, as the post-index cleanup reads them.""" + session = db.get(GenerativeSession, session_id) + session.parameters = parameters + db.commit() + + +def _exists(db: Session, bridge_id: int) -> bool: + """Whether a bridge row is still in the database.""" + return db.get(RAGRetriever, bridge_id) is not None + + +# ── Post-index release ─────────────────────────────────────────────────────── + + +def test_post_index_release_keeps_a_row_shared_by_retriever_and_reranker( + orm_db, tmp_path +): + """The live reranker root is kept with the retriever's row it shares.""" + stage = _stage(orm_db, tmp_path, "post_shared") + shared = _leaf(orm_db, stage, RERANK_A_K1, "shared") + other = _leaf(orm_db, stage, RERANK_B_K1, "other") + live_root = _bridge(orm_db, stage.pipeline_id, PARALLEL, [shared, other]) + stale_root = _leaf(orm_db, stage, STALE_K1, "stale") + orm_db.commit() + _set_parameters( + orm_db, + stage.session_id, + _parameters( + _composite_ref( + PARALLEL, [_sparse_ref(RERANK_A_K1), _sparse_ref(RERANK_B_K1)] + ), + _sparse_ref(RERANK_A_K1), + ), + ) + + CleanupService(orm_db, rag_path=stage.rag).cleanup_after_reindex( + stage.session_id, live_root, shared + ) + + assert _exists(orm_db, live_root) + assert _exists(orm_db, shared) + assert _exists(orm_db, other) + assert not _exists(orm_db, stale_root) + _assert_sound(orm_db) + + +def test_post_index_release_without_a_built_reranker_protects_nothing( + client: TestClient, orm_db, tmp_path +): + """A stored reranker with no rows protects nothing; the stale root is released.""" + stage = _stage(orm_db, tmp_path, "post_unbuilt") + live_root = _leaf(orm_db, stage, MAIN_K1, "live") + stale_root = _leaf(orm_db, stage, STALE_K1, "stale") + orm_db.commit() + _set_parameters( + orm_db, + stage.session_id, + _parameters(_sparse_ref(MAIN_K1), _sparse_ref(RERANK_A_K1)), + ) + + CleanupService(orm_db, _registry(client), rag_path=stage.rag).cleanup_after_reindex( + stage.session_id, live_root, None + ) + + assert _exists(orm_db, live_root) + assert not _exists(orm_db, stale_root) + _assert_sound(orm_db) + + +def test_post_index_release_refuses_an_unexpected_reranker_root(orm_db, tmp_path): + """A reranker root the session's parameters do not name is refused as well.""" + stage = _stage(orm_db, tmp_path, "post_unexpected") + live_root = _leaf(orm_db, stage, MAIN_K1, "live") + reranker_root = _leaf(orm_db, stage, RERANK_A_K1, "reranker") + stale_root = _leaf(orm_db, stage, STALE_K1, "stale") + orm_db.commit() + _set_parameters(orm_db, stage.session_id, _parameters(_sparse_ref(MAIN_K1), None)) + + with pytest.raises(ValueError, match="does not match"): + CleanupService(orm_db, rag_path=stage.rag).cleanup_after_reindex( + stage.session_id, live_root, reranker_root + ) + + assert _exists(orm_db, stale_root) + + +# ── One stage changes ──────────────────────────────────────────────────────── + + +def test_removing_a_nested_reranker_composite_releases_it_top_down( + client: TestClient, orm_db, tmp_path +): + """A reranker composite nested in a composite goes with its exclusive leaves.""" + stage = _stage(orm_db, tmp_path, "nested_reranker") + retriever_leaf = _leaf(orm_db, stage, MAIN_K1, "retriever") + leaf_a = _leaf(orm_db, stage, RERANK_A_K1, "rerank_a") + leaf_b = _leaf(orm_db, stage, RERANK_B_K1, "rerank_b") + leaf_c = _leaf(orm_db, stage, RERANK_C_K1, "rerank_c") + inner = _bridge(orm_db, stage.pipeline_id, PARALLEL, [leaf_a, leaf_b]) + outer = _bridge(orm_db, stage.pipeline_id, SEQUENTIAL, [inner, leaf_c]) + orm_db.commit() + reranker = _composite_ref( + SEQUENTIAL, + [ + _composite_ref( + PARALLEL, [_sparse_ref(RERANK_A_K1), _sparse_ref(RERANK_B_K1)] + ), + _sparse_ref(RERANK_C_K1), + ], + ) + old = _parameters(_sparse_ref(MAIN_K1), reranker) + new = _parameters(_sparse_ref(MAIN_K1), None) + + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + stage.session_id, old, new + ) + + for bridge_id in (outer, inner, leaf_a, leaf_b, leaf_c): + assert not _exists(orm_db, bridge_id), f"bridge {bridge_id} remains" + assert _exists(orm_db, retriever_leaf) + assert orm_db.query(RAGSparseRetriever).count() == 1 + _assert_sound(orm_db) + + +def test_a_retriever_change_keeps_the_rows_the_reranker_still_uses( + client: TestClient, orm_db, tmp_path +): + """The old retriever's row survives when the reranker's composite reads it.""" + stage = _stage(orm_db, tmp_path, "retriever_change") + shared = _leaf(orm_db, stage, RERANK_A_K1, "shared") + other = _leaf(orm_db, stage, RERANK_B_K1, "other") + reranker_root = _bridge(orm_db, stage.pipeline_id, PARALLEL, [shared, other]) + orm_db.commit() + reranker = _composite_ref( + PARALLEL, [_sparse_ref(RERANK_A_K1), _sparse_ref(RERANK_B_K1)] + ) + old = _parameters(_sparse_ref(RERANK_A_K1), reranker) + new = _parameters(_sparse_ref(RETRIEVER_K1), reranker) + + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + stage.session_id, old, new + ) + + assert _exists(orm_db, reranker_root) + assert _exists(orm_db, shared) + assert _exists(orm_db, other) + _assert_sound(orm_db) + + +def test_changing_only_the_reranker_keeps_the_retriever_leaf( + client: TestClient, orm_db, tmp_path +): + """Only the reranker's exclusive rows go; the retriever's own leaf stays.""" + stage = _stage(orm_db, tmp_path, "reranker_only") + retriever_leaf = _leaf(orm_db, stage, MAIN_K1, "retriever") + reranker_leaf = _leaf(orm_db, stage, RERANK_A_K1, "reranker") + orm_db.commit() + old = _parameters(_sparse_ref(MAIN_K1), _sparse_ref(RERANK_A_K1)) + new = _parameters(_sparse_ref(MAIN_K1), _sparse_ref(RERANK_B_K1)) + + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + stage.session_id, old, new + ) + + assert _exists(orm_db, retriever_leaf) + assert not _exists(orm_db, reranker_leaf) + assert orm_db.query(RAGSparseRetriever).count() == 1 + + +# ── Dense matrices read by both stages ─────────────────────────────────────── + + +def test_a_retriever_change_keeps_the_matrices_the_reranker_reads( + client: TestClient, orm_db, tmp_path +): + """A dense retriever that is replaced leaves the matrices its reranker reads.""" + stage = _stage(orm_db, tmp_path, "dense_retriever_change") + model = _embedding_model(orm_db, "shared_dense") + old_retriever = _dense_leaf(orm_db, stage, "retriever", model) + reranker = _dense_leaf(orm_db, stage, "reranker", model) + folder = stage.rag / EMBEDDINGS_DIR / "shared_dense" + _matrix(orm_db, stage.document_id, stage.chunk_set_id, model, folder) + orm_db.commit() + old = _parameters(_dense_ref("retriever"), _dense_ref("reranker")) + new = _parameters(_sparse_ref(RETRIEVER_K1), _dense_ref("reranker")) + + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + stage.session_id, old, new + ) + + assert not _exists(orm_db, old_retriever) + assert _exists(orm_db, reranker) + assert orm_db.query(RAGEmbeddingMatrix).count() == 1 + assert folder.exists() + assert orm_db.get(RAGEmbeddingModel, model) is not None + + +def test_a_reranker_removal_keeps_the_matrices_the_retriever_reads( + client: TestClient, orm_db, tmp_path +): + """Removing the reranker releases its rows, not the matrices the retriever reads.""" + stage = _stage(orm_db, tmp_path, "dense_reranker_removed") + model = _embedding_model(orm_db, "retriever_dense") + retriever = _dense_leaf(orm_db, stage, "retriever", model) + reranker = _dense_leaf(orm_db, stage, "reranker", model) + folder = stage.rag / EMBEDDINGS_DIR / "retriever_dense" + _matrix(orm_db, stage.document_id, stage.chunk_set_id, model, folder) + orm_db.commit() + old = _parameters(_dense_ref("retriever"), _dense_ref("reranker")) + new = _parameters(_dense_ref("retriever"), None) + + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + stage.session_id, old, new + ) + + assert _exists(orm_db, retriever) + assert not _exists(orm_db, reranker) + assert orm_db.query(RAGEmbeddingMatrix).count() == 1 + assert folder.exists() + _assert_sound(orm_db) + + +# ── The session's reranker, which this index did not build ─────────────────── + + +def _signed_dense_leaf( + db: Session, stage: _Stage, label: str, model_id: int, registry: Any +) -> int: + """Insert a dense leaf stored under its reference's persistence signature.""" + signature = reference_signature(_dense_ref(label), registry) + bridge = RAGRetriever(class_name=DENSE, pipeline_id=stage.pipeline_id) + db.add(bridge) + db.flush() + db.add( + RAGDenseRetriever( + bridge_id=bridge.id, + chunk_set_id=stage.chunk_set_id, + class_name=DENSE, + parameters=signature["params"], + embedding_model_id=model_id, + ) + ) + db.flush() + return bridge.id + + +def _error_records(caplog: pytest.LogCaptureFixture) -> list[logging.LogRecord]: + """Return the error records the post-index cleanup logged during a test.""" + return [ + record + for record in caplog.records + if record.name == cleanup_service.__name__ and record.levelno >= logging.ERROR + ] + + +def test_an_unbuilt_reranker_keeps_its_rows_without_an_error( + client: TestClient, orm_db, tmp_path, caplog +): + """A reranker this index did not build keeps its current rows, silently.""" + stage = _stage(orm_db, tmp_path, "unbuilt_reranker") + live_root = _leaf(orm_db, stage, MAIN_K1, "live") + reranker_root = _leaf(orm_db, stage, RERANK_A_K1, "reranker") + orm_db.commit() + _set_parameters( + orm_db, + stage.session_id, + _parameters(_sparse_ref(MAIN_K1), _sparse_ref(RERANK_A_K1)), + ) + + with caplog.at_level(logging.ERROR, logger=cleanup_service.__name__): + run_post_index_cleanup( + orm_db, _registry(client), stage.session_id, live_root, stage.rag, None + ) + + assert _exists(orm_db, live_root) + assert _exists(orm_db, reranker_root) + assert not _error_records(caplog) + _assert_sound(orm_db) + + +def test_an_unbuilt_dense_reranker_keeps_the_matrix_it_reads( + client: TestClient, orm_db, tmp_path, caplog +): + """A dense reranker this index did not rebuild keeps the matrix it reads.""" + stage = _stage(orm_db, tmp_path, "unbuilt_dense_reranker") + model = _embedding_model(orm_db, "unbuilt_reranker_dense") + live_root = _leaf(orm_db, stage, MAIN_K1, "live") + reranker = _signed_dense_leaf(orm_db, stage, "reranker", model, _registry(client)) + folder = stage.rag / EMBEDDINGS_DIR / "unbuilt_reranker_dense" + _matrix(orm_db, stage.document_id, stage.chunk_set_id, model, folder) + orm_db.commit() + _set_parameters( + orm_db, + stage.session_id, + _parameters(_sparse_ref(MAIN_K1), _dense_ref("reranker")), + ) + + with caplog.at_level(logging.ERROR, logger=cleanup_service.__name__): + run_post_index_cleanup( + orm_db, _registry(client), stage.session_id, live_root, stage.rag, None + ) + + assert _exists(orm_db, reranker) + assert orm_db.query(RAGEmbeddingMatrix).count() == 1 + assert folder.exists() + assert not _error_records(caplog) + _assert_sound(orm_db) + + +def test_a_reranker_row_the_session_no_longer_names_is_released( + client: TestClient, orm_db, tmp_path +): + """Stale reranker rows of another shape go; the named reranker's row stays.""" + stage = _stage(orm_db, tmp_path, "stale_reranker_rows") + live_root = _leaf(orm_db, stage, MAIN_K1, "live") + current = _leaf(orm_db, stage, RERANK_B_K1, "current") + stale = _leaf(orm_db, stage, RERANK_A_K1, "stale") + orm_db.commit() + _set_parameters( + orm_db, + stage.session_id, + _parameters(_sparse_ref(MAIN_K1), _sparse_ref(RERANK_B_K1)), + ) + + CleanupService(orm_db, _registry(client), rag_path=stage.rag).cleanup_after_reindex( + stage.session_id, live_root, None + ) + + assert _exists(orm_db, live_root) + assert _exists(orm_db, current) + assert not _exists(orm_db, stale) + _assert_sound(orm_db) + + +def test_a_matching_reranker_on_an_older_chunk_set_is_released( + client: TestClient, orm_db, tmp_path, caplog +): + """A reranker tree over an older chunk set is stale, not a violation. + + The reranker is rebuilt on the live chunk set by the next build, so its old + tree is released with its chunk set rather than kept beside it. + """ + stage = _stage(orm_db, tmp_path, "older_chunk_reranker") + live_root = _leaf(orm_db, stage, MAIN_K1, "live") + older = _chunk_set(orm_db, stage.session_id, stage.document_id, stage.rag) + older_reranker = _sparse_bridge( + orm_db, + stage.pipeline_id, + older, + stage.rag / SPARSE_DIR / f"older_reranker_{uuid.uuid4().hex[:6]}", + RERANK_B_K1, + ) + orm_db.commit() + _set_parameters( + orm_db, + stage.session_id, + _parameters(_sparse_ref(MAIN_K1), _sparse_ref(RERANK_B_K1)), + ) + + with caplog.at_level(logging.ERROR, logger=cleanup_service.__name__): + run_post_index_cleanup( + orm_db, _registry(client), stage.session_id, live_root, stage.rag, None + ) + + assert _exists(orm_db, live_root) + assert not _exists(orm_db, older_reranker) + assert orm_db.get(RAGChunkSet, older) is None + assert not _error_records(caplog) + _assert_sound(orm_db) + + +# ── Stale-row probe and the chat cleanup of a reranker session ─────────────── + + +def _built_pipeline(retriever_id: int, reranker_id: int | None) -> SimpleNamespace: + """Return the part of a built pipeline the chat cleanup reads.""" + reranker = None + if reranker_id is not None: + reranker = SimpleNamespace(get_id=lambda: reranker_id) + return SimpleNamespace( + retriever=SimpleNamespace(get_id=lambda: retriever_id), + query_transformation=SimpleNamespace(reranker=reranker), + ) + + +def _healthy_reranker_session(client: TestClient, orm_db, tmp_path, label: str): + """Return a stage whose retriever and reranker each own one root.""" + stage = _stage(orm_db, tmp_path, label) + retriever_root = _leaf(orm_db, stage, MAIN_K1, "retriever") + reranker_root = _leaf(orm_db, stage, RERANK_A_K1, "reranker") + orm_db.commit() + _set_parameters( + orm_db, + stage.session_id, + _parameters(_sparse_ref(MAIN_K1), _sparse_ref(RERANK_A_K1)), + ) + return stage, retriever_root, reranker_root + + +def test_a_healthy_reranker_session_has_no_stale_rows(client, orm_db, tmp_path): + """The retriever's root and the reranker's root are both expected.""" + stage, _, _ = _healthy_reranker_session(client, orm_db, tmp_path, "probe_ok") + + assert has_stale_index_rows(orm_db, stage.session_id, _registry(client)) is False + + +def test_a_stray_root_makes_a_reranker_session_stale(client, orm_db, tmp_path): + """A root that is neither the retriever's nor the reranker's is stale.""" + stage, _, _ = _healthy_reranker_session(client, orm_db, tmp_path, "probe_stray") + _leaf(orm_db, stage, STALE_K1, "stray") + orm_db.commit() + + assert has_stale_index_rows(orm_db, stage.session_id, _registry(client)) is True + + +def test_a_healthy_reranker_session_skips_the_chat_cleanup( + client, orm_db, tmp_path, monkeypatch +): + """A chat turn that reuses its index does not clean up a healthy reranker.""" + stage, retriever_root, reranker_root = _healthy_reranker_session( + client, orm_db, tmp_path, "chat_ok" + ) + calls: list[tuple] = [] + monkeypatch.setattr( + rag_job_module, "run_post_index_cleanup", lambda *args: calls.append(args) + ) + footprint = capture_index_footprint(orm_db, stage.session_id) + + rag_job_module._run_cleanup_if_rebuilt( + orm_db, + _registry(client), + stage.session_id, + footprint, + _built_pipeline(retriever_root, reranker_root), + stage.rag, + ) + + assert calls == [] + + +def test_a_stray_root_makes_the_chat_turn_clean_up( + client, orm_db, tmp_path, monkeypatch +): + """A stray root left by a failed cleanup is released by the next chat turn.""" + stage, retriever_root, reranker_root = _healthy_reranker_session( + client, orm_db, tmp_path, "chat_stray" + ) + _leaf(orm_db, stage, STALE_K1, "stray") + orm_db.commit() + calls: list[tuple] = [] + monkeypatch.setattr( + rag_job_module, "run_post_index_cleanup", lambda *args: calls.append(args) + ) + footprint = capture_index_footprint(orm_db, stage.session_id) + + rag_job_module._run_cleanup_if_rebuilt( + orm_db, + _registry(client), + stage.session_id, + footprint, + _built_pipeline(retriever_root, reranker_root), + stage.rag, + ) + + assert len(calls) == 1 + + +# ── Configuration comparisons ──────────────────────────────────────────────── + + +def _signed_sparse_leaf( + db: Session, stage: _Stage, reference: dict[str, Any], registry: Any, label: str +) -> int: + """Insert a sparse leaf stored under its reference's persistence signature.""" + bridge_id = _sparse_bridge( + db, stage.pipeline_id, stage.chunk_set_id, stage.rag / SPARSE_DIR / label, 1.0 + ) + detail = ( + db.query(RAGSparseRetriever) + .filter(RAGSparseRetriever.bridge_id == bridge_id) + .one() + ) + detail.parameters = reference_signature(reference, registry)["params"] + db.flush() + return bridge_id + + +def test_a_minimal_reference_has_the_identity_of_its_explicit_form(client): + """``{component}`` and ``{component, params: {}}`` name the same retriever.""" + registry = _registry(client) + + assert _retriever_identity({"component": BM25}, registry) == _retriever_identity( + {"component": BM25, "params": {}}, registry + ) + + +def test_saving_the_explicit_form_of_a_minimal_reference_keeps_the_retriever( + client, orm_db, tmp_path +): + """An update that only spells out the defaults does not release the retriever.""" + registry = _registry(client) + stage = _stage(orm_db, tmp_path, "minimal_identity") + explicit = {"component": BM25, "params": {}} + leaf = _signed_sparse_leaf(orm_db, stage, explicit, registry, "defaults") + orm_db.commit() + old = _parameters({"component": BM25}, None) + new = _parameters(explicit, None) + + CleanupService(orm_db, registry).cleanup_orphaned_resources( + stage.session_id, old, new + ) + + assert _exists(orm_db, leaf) + + +def test_a_boolean_fitted_parameter_does_not_match_a_number(orm_db, tmp_path): + """Configuration equality is strict, so a fitted ``true`` is not ``1``.""" + stage = _stage(orm_db, tmp_path, "strict_match") + bridge_id = _leaf(orm_db, stage, MAIN_K1, "flag") + detail = ( + orm_db.query(RAGSparseRetriever) + .filter(RAGSparseRetriever.bridge_id == bridge_id) + .one() + ) + detail.parameters = {"k1": True} + orm_db.commit() + bridge = orm_db.get(RAGRetriever, bridge_id) + + matches = CleanupService(orm_db)._bridge_matches( + bridge, {"component": BM25, "params": {"k1": 1}} + ) + + assert matches is False diff --git a/tests/back/RAG/test_reranker_review_followups.py b/tests/back/RAG/test_reranker_review_followups.py index 0cdb601bd..c933c1383 100644 --- a/tests/back/RAG/test_reranker_review_followups.py +++ b/tests/back/RAG/test_reranker_review_followups.py @@ -30,6 +30,7 @@ SessionConfigurationService, ) from tests.back.RAG.conftest import _insert_rag_session +from tests.back.RAG.test_retriever_identity import _registry BM25 = "BM25Retriever" TFIDF = "TFIDFRetriever" @@ -37,8 +38,8 @@ SEQUENTIAL = "SequentialRetriever" -def _bm25(top_k: int) -> Dict[str, Any]: - return {"component": BM25, "params": {"top_k": top_k}} +def _bm25(k1: int) -> Dict[str, Any]: + return {"component": BM25, "params": {"k1": k1}} def _parameters( @@ -156,66 +157,76 @@ def _index(orm_db, tmp_path, name: str): class TestCleanupDoesNotMixTheTwoStages: """The retriever stage and the reranker keep their rows in one pipeline.""" - def test_changing_the_retriever_keeps_a_same_class_reranker(self, orm_db, tmp_path): + def test_changing_the_retriever_keeps_a_same_class_reranker( + self, client, orm_db, tmp_path + ): session, index = _index(orm_db, tmp_path, "mix_a") # The reranker's row is the lowest id, so a lookup by class name alone # would return it instead of the retriever's own row. - reranker_bridge = index.sparse(BM25, {"top_k": 3}) - main_bridge = index.sparse(BM25, {"top_k": 5}) + reranker_bridge = index.sparse(BM25, {"k1": 3}) + main_bridge = index.sparse(BM25, {"k1": 5}) old = _parameters(_bm25(5), _bm25(3)) - new = _parameters({"component": TFIDF, "params": {"top_k": 5}}, _bm25(3)) + new = _parameters({"component": TFIDF, "params": {"k1": 5}}, _bm25(3)) - CleanupService(orm_db).cleanup_orphaned_resources(session.id, old, new) + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + session.id, old, new + ) assert not index.exists(main_bridge) assert index.exists(reranker_bridge) def test_a_row_shared_by_both_stages_survives_a_retriever_change( - self, orm_db, tmp_path + self, client, orm_db, tmp_path ): session, index = _index(orm_db, tmp_path, "mix_shared") - shared = index.sparse(BM25, {"top_k": 5}) + shared = index.sparse(BM25, {"k1": 5}) old = _parameters(_bm25(5), _bm25(5)) - new = _parameters({"component": TFIDF, "params": {"top_k": 5}}, _bm25(5)) + new = _parameters({"component": TFIDF, "params": {"k1": 5}}, _bm25(5)) - CleanupService(orm_db).cleanup_orphaned_resources(session.id, old, new) + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + session.id, old, new + ) assert index.exists(shared) def test_changing_only_the_reranker_deletes_its_rows_and_not_the_retrievers( - self, orm_db, tmp_path + self, client, orm_db, tmp_path ): session, index = _index(orm_db, tmp_path, "mix_rerank_only") - main_bridge = index.sparse(BM25, {"top_k": 5}) - reranker_bridge = index.sparse(BM25, {"top_k": 3}) + main_bridge = index.sparse(BM25, {"k1": 5}) + reranker_bridge = index.sparse(BM25, {"k1": 3}) old = _parameters(_bm25(5), _bm25(3)) new = _parameters(_bm25(5), None) - CleanupService(orm_db).cleanup_orphaned_resources(session.id, old, new) + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + session.id, old, new + ) assert index.exists(main_bridge) assert not index.exists(reranker_bridge) assert orm_db.query(RAGSparseRetriever).count() == 1 - def test_an_unchanged_reranker_is_left_alone(self, orm_db, tmp_path): + def test_an_unchanged_reranker_is_left_alone(self, client, orm_db, tmp_path): session, index = _index(orm_db, tmp_path, "mix_unchanged") - main_bridge = index.sparse(BM25, {"top_k": 5}) - reranker_bridge = index.sparse(BM25, {"top_k": 3}) + main_bridge = index.sparse(BM25, {"k1": 5}) + reranker_bridge = index.sparse(BM25, {"k1": 3}) parameters = _parameters(_bm25(5), _bm25(3)) - CleanupService(orm_db).cleanup_orphaned_resources( + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( session.id, parameters, _parameters(_bm25(5), _bm25(3)) ) assert index.exists(main_bridge) assert index.exists(reranker_bridge) - def test_deleting_the_session_removes_the_reranker_rows_too(self, orm_db, tmp_path): + def test_deleting_the_session_removes_the_reranker_rows_too( + self, client, orm_db, tmp_path + ): session, index = _index(orm_db, tmp_path, "mix_delete") - main_bridge = index.sparse(BM25, {"top_k": 5}) - reranker_bridge = index.sparse(BM25, {"top_k": 3}) + main_bridge = index.sparse(BM25, {"k1": 5}) + reranker_bridge = index.sparse(BM25, {"k1": 3}) - CleanupService(orm_db).cleanup_orphaned_resources( + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( session.id, _parameters(_bm25(5), _bm25(3)), None ) @@ -223,25 +234,45 @@ def test_deleting_the_session_removes_the_reranker_rows_too(self, orm_db, tmp_pa assert not index.exists(reranker_bridge) -def _dense(top_k: int) -> Dict[str, Any]: - return {"component": DENSE, "params": {"top_k": top_k}} +#: Embedding component of the dense references, registered in the application. +DENSE_EMBEDDING = "AllMiniLML6V2Embedding" +#: A second registered embedding, for a reranker that embeds differently. +OTHER_EMBEDDING = "ParaphraseMultilingualMiniLML12V2Embedding" + + +def _dense(label: str, embedding: str = DENSE_EMBEDDING) -> Dict[str, Any]: + """Return a dense reference over one embedding, told apart by ``label``. + + ``top_k`` is query-time and no longer separates two rows, so ``label`` + stands in for a second persistent parameter: two rows over one chunk set + and embedding model must still be two rows. + """ + return { + "component": DENSE, + "params": { + "embedding_model": {"component": embedding, "params": {}}, + "label": label, + }, + } class TestCleanupKeepsSharedDenseMatrices: - """Dense retrievers with one embedding over one chunk set share matrices.""" + """Dense retrievers over one chunk set and embedding model share matrices.""" def test_dropping_the_reranker_keeps_the_matrices_the_retriever_reads( - self, orm_db, tmp_path + self, client, orm_db, tmp_path ): session, index = _index(orm_db, tmp_path, "dense_shared") embedding = index.embedding_model("E") - main_bridge = index.dense({"top_k": 5}, embedding) - reranker_bridge = index.dense({"top_k": 3}, embedding) + main_bridge = index.dense(_dense("main")["params"], embedding) + reranker_bridge = index.dense(_dense("rerank")["params"], embedding) folder = index.matrix(1, embedding) - old = _parameters(_dense(5), _dense(3), documents=[1]) - new = _parameters(_dense(5), None, documents=[1]) + old = _parameters(_dense("main"), _dense("rerank"), documents=[1]) + new = _parameters(_dense("main"), None, documents=[1]) - CleanupService(orm_db).cleanup_orphaned_resources(session.id, old, new) + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + session.id, old, new + ) assert index.exists(main_bridge) assert not index.exists(reranker_bridge) @@ -249,33 +280,41 @@ def test_dropping_the_reranker_keeps_the_matrices_the_retriever_reads( assert os.path.isdir(folder) def test_a_reranker_with_its_own_embedding_takes_its_matrices_with_it( - self, orm_db, tmp_path + self, client, orm_db, tmp_path ): session, index = _index(orm_db, tmp_path, "dense_own") main_embedding = index.embedding_model("E_main") reranker_embedding = index.embedding_model("E_rerank") - index.dense({"top_k": 5}, main_embedding) - index.dense({"top_k": 3}, reranker_embedding) + index.dense(_dense("main")["params"], main_embedding) + index.dense(_dense("rerank", OTHER_EMBEDDING)["params"], reranker_embedding) main_folder = index.matrix(1, main_embedding) reranker_folder = index.matrix(1, reranker_embedding) - old = _parameters(_dense(5), _dense(3), documents=[1]) - new = _parameters(_dense(5), None, documents=[1]) + old = _parameters( + _dense("main"), _dense("rerank", OTHER_EMBEDDING), documents=[1] + ) + new = _parameters(_dense("main"), None, documents=[1]) - CleanupService(orm_db).cleanup_orphaned_resources(session.id, old, new) + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + session.id, old, new + ) assert orm_db.query(RAGEmbeddingMatrix).count() == 1 assert os.path.isdir(main_folder) assert not os.path.isdir(reranker_folder) - def test_deleting_the_session_removes_the_shared_matrices(self, orm_db, tmp_path): + def test_deleting_the_session_removes_the_shared_matrices( + self, client, orm_db, tmp_path + ): session, index = _index(orm_db, tmp_path, "dense_delete") embedding = index.embedding_model("E") - index.dense({"top_k": 5}, embedding) - index.dense({"top_k": 3}, embedding) + index.dense(_dense("main")["params"], embedding) + index.dense(_dense("rerank")["params"], embedding) folder = index.matrix(1, embedding) - old = _parameters(_dense(5), _dense(3), documents=[1]) + old = _parameters(_dense("main"), _dense("rerank"), documents=[1]) - CleanupService(orm_db).cleanup_orphaned_resources(session.id, old, None) + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( + session.id, old, None + ) assert orm_db.query(RAGEmbeddingMatrix).count() == 0 assert not os.path.isdir(folder) @@ -285,22 +324,29 @@ class TestCompositeCleanupMatchesByStoredShape: """A composite is found by its ordered children, not by class alone.""" def test_only_the_composite_with_the_old_children_is_deleted( - self, orm_db, tmp_path + self, client, orm_db, tmp_path ): session, index = _index(orm_db, tmp_path, "composite_match") - bm25_child = index.sparse(BM25, {"top_k": 5}) - tfidf_child = index.sparse(TFIDF, {"top_k": 5}) + bm25_child = index.sparse(BM25, {"k1": 5}) + tfidf_child = index.sparse(TFIDF, {"k1": 5}) old_composite = index.composite(SEQUENTIAL, [bm25_child, tfidf_child]) other_composite = index.composite(SEQUENTIAL, [tfidf_child, bm25_child]) old_reference = { "component": SEQUENTIAL, "params": { - "children": [_bm25(5), {"component": TFIDF, "params": {"top_k": 5}}] + "children": [_bm25(5), {"component": TFIDF, "params": {"k1": 5}}] + }, + } + # The new retriever is the other composite's shape, so only that row is + # protected; the same class's composite with the old children goes. + new_reference = { + "component": SEQUENTIAL, + "params": { + "children": [{"component": TFIDF, "params": {"k1": 5}}, _bm25(5)] }, } - new_reference = {"component": TFIDF, "params": {"top_k": 5}} - CleanupService(orm_db).cleanup_orphaned_resources( + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( session.id, _parameters(old_reference, None), _parameters(new_reference, None), @@ -308,20 +354,24 @@ def test_only_the_composite_with_the_old_children_is_deleted( assert not index.exists(old_composite) assert index.exists(other_composite) + assert index.exists(bm25_child) + assert index.exists(tfidf_child) - def test_a_composite_that_matches_no_row_is_swept_by_class(self, orm_db, tmp_path): + def test_a_composite_that_matches_no_row_is_swept_by_class( + self, client, orm_db, tmp_path + ): session, index = _index(orm_db, tmp_path, "composite_sweep") - child = index.sparse(BM25, {"top_k": 9}) + child = index.sparse(BM25, {"k1": 9}) stale = index.composite(SEQUENTIAL, [child]) old_reference = { "component": SEQUENTIAL, "params": {"children": [_bm25(5), _bm25(3)]}, } - CleanupService(orm_db).cleanup_orphaned_resources( + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( session.id, _parameters(old_reference, None), - _parameters({"component": TFIDF, "params": {"top_k": 5}}, None), + _parameters({"component": TFIDF, "params": {"k1": 5}}, None), ) assert not index.exists(stale) @@ -330,40 +380,44 @@ def test_a_composite_that_matches_no_row_is_swept_by_class(self, orm_db, tmp_pat class TestCleanupRejectsMalformedStoredStructure: """A stored reference of the wrong shape fails instead of matching nothing.""" - def test_a_composite_reference_without_children_is_rejected(self, orm_db, tmp_path): + def test_a_composite_reference_without_children_is_rejected( + self, client, orm_db, tmp_path + ): _, index = _index(orm_db, tmp_path, "malformed_composite") index.composite(SEQUENTIAL, []) with pytest.raises(RAGPipelineConfigError, match="no list of children"): - CleanupService(orm_db)._matching_bridges( + CleanupService(orm_db, _registry(client))._matching_bridges( index.pipeline_id, {"component": SEQUENTIAL, "params": {}} ) - def test_non_dict_params_are_rejected(self, orm_db, tmp_path): + def test_non_dict_params_are_rejected(self, client, orm_db, tmp_path): _, index = _index(orm_db, tmp_path, "malformed_params") - with pytest.raises(RAGPipelineConfigError, match="not a dict"): - CleanupService(orm_db)._matching_bridges( + with pytest.raises(RAGPipelineConfigError, match="must be a dict"): + CleanupService(orm_db, _registry(client))._matching_bridges( index.pipeline_id, {"component": BM25, "params": "abc"} ) - def test_a_reranker_that_is_not_a_reference_is_rejected(self, orm_db, tmp_path): + def test_a_reranker_that_is_not_a_reference_is_rejected( + self, client, orm_db, tmp_path + ): session, _ = _index(orm_db, tmp_path, "malformed_reranker") old = _parameters(_bm25(5), None) old["query_transformation"]["params"]["reranker"] = "BM25Retriever" with pytest.raises(RAGPipelineConfigError, match="reranker"): - CleanupService(orm_db).cleanup_orphaned_resources( + CleanupService(orm_db, _registry(client)).cleanup_orphaned_resources( session.id, old, _parameters(_bm25(5), None) ) def test_a_reference_without_params_is_the_minimal_reference( - self, orm_db, tmp_path + self, client, orm_db, tmp_path ): _, index = _index(orm_db, tmp_path, "minimal_reference") bridge = index.sparse(BM25, {}) - matches = CleanupService(orm_db)._matching_bridges( + matches = CleanupService(orm_db, _registry(client))._matching_bridges( index.pipeline_id, {"component": BM25} ) @@ -375,8 +429,8 @@ class TestCompositeRowsAreReused: def test_same_children_reuse_the_composite_row(self, orm_db, tmp_path): _, index = _index(orm_db, tmp_path, "composite_reuse") - first_child = index.sparse(BM25, {"top_k": 5}) - second_child = index.sparse(TFIDF, {"top_k": 5}) + first_child = index.sparse(BM25, {"k1": 5}) + second_child = index.sparse(TFIDF, {"k1": 5}) service = RetrieverDBService(orm_db) first = service.save_composite( @@ -391,8 +445,8 @@ def test_same_children_reuse_the_composite_row(self, orm_db, tmp_path): def test_other_children_or_order_create_a_new_composite(self, orm_db, tmp_path): _, index = _index(orm_db, tmp_path, "composite_new") - first_child = index.sparse(BM25, {"top_k": 5}) - second_child = index.sparse(TFIDF, {"top_k": 5}) + first_child = index.sparse(BM25, {"k1": 5}) + second_child = index.sparse(TFIDF, {"k1": 5}) service = RetrieverDBService(orm_db) first = service.save_composite( diff --git a/tests/back/RAG/test_retriever_identity.py b/tests/back/RAG/test_retriever_identity.py index d347b65ab..97f8185f7 100644 --- a/tests/back/RAG/test_retriever_identity.py +++ b/tests/back/RAG/test_retriever_identity.py @@ -2,12 +2,16 @@ 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 +import json +import logging import uuid from pathlib import Path from typing import Any, Dict @@ -15,19 +19,52 @@ 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, +) +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, 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.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, ) +from DashAI.back.models.RAG.retrievers.similarity import CosineSimilarity from DashAI.back.models.RAG.retrievers.sparse.bm25_retriever import BM25Retriever from DashAI.back.models.RAG.transformation import ( LLMQueryDecomposer, @@ -36,6 +73,7 @@ ) 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, @@ -59,6 +97,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, @@ -69,7 +115,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, @@ -306,7 +352,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 @@ -329,7 +381,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( @@ -362,7 +414,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 ) @@ -394,7 +446,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 ) @@ -441,7 +493,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 ) @@ -453,9 +505,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 @@ -464,14 +520,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( @@ -481,26 +575,128 @@ 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) + ) + == 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) ) - == retriever_presets.HYBRID_PRESET_KEY + 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 + ) + + +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", + [ + "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,3 +1068,857 @@ 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() + + +# ── Embedding batch size ───────────────────────────────────────────────────── + +_EMBEDDING_PARAMS: Dict[str, Any] = { + "device": "cpu", + "batch_size": 32, + "normalize": True, + "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]: + """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 + + +# ── 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 = { + **_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/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 + ) 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) diff --git a/tests/back/services/test_workflow_session_services.py b/tests/back/services/test_workflow_session_services.py index 6780b42e7..86c9fa13c 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, @@ -442,6 +445,13 @@ def test_rag_validate_update_reports_validation_errors(db, session, error): _rag_service(db).validate_update(session, {"prompt": {}}) +def test_rag_is_unchanged_treats_a_boolean_as_different_from_a_number(db, session): + """Strict configuration equality: ``false`` is not the number ``0``.""" + service = _rag_service(db) + + assert service.is_unchanged(session, {"a": 0}, {"a": False}, {}) is False + + def test_rag_apply_update_cancels_the_index_before_cleaning_up(db, session): """A running index is stopped before the rows it writes are deleted, the cleanup stays in the caller's transaction and the prompts are bound.""" 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"] + } + ] +}