Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

15.2 KB
Raw Blame
"""Research retries preserve files and RAG data until deletion commits."""

from contextlib import contextmanager, nullcontext
import sqlite3

import pytest
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm import Session

from tests.database import test_shared_document_lifetime as shared_lifetime
from tests.database.test_shared_document_lifetime import (
    BODY,
    seed_family,
    call_delete_route,
)

from local_deep_research.database import research_cascade
from local_deep_research.database.models import ResearchHistory
from local_deep_research.database.models.library import (
    Collection,
    Document,
    DocumentChunk,
    DocumentCollection,
    EmbeddingProvider,
)
from local_deep_research.research_library.deletion.services import (
    document_deletion,
)
from local_deep_research.research_library.services import rag_service_factory


# Reuse the two real SQLite FK variants and production-style rollback fixture.
database = shared_lifetime.database
route_session = shared_lifetime.route_session


def observe_actual_purge(monkeypatch, database, events):
    @contextmanager
    def independent_session(_username):
        with Session(database) as session:
            yield session

    class VectorObserver:
        def __enter__(self):
            return self

        def __exit__(self, *_args):
            return False

        def purge_documents_vectors(self, document_ids, collection_id):
            for document_id in document_ids:
                self._check_document(document_id, collection_id)

        def _check_document(self, document_id, collection_id):
            # A fresh connection observes the committed delete and the IDs
            # needed by the real vector operation, not a dirty ORM identity map.
            with Session(database) as verification:
                assert verification.get(ResearchHistory, "owner") is None
                assert verification.get(Document, document_id) is None
                chunk = (
                    verification.query(DocumentChunk)
                    .filter_by(
                        source_id=document_id,
                        collection_name=f"collection_{collection_id}",
                    )
                    .one()
                )
                assert chunk.embedding_id == collection_id
            events.append(("vectors", document_id, collection_id))

        def purge_document_chunks(self, document_id, collection_id):
            events.append(("chunks", document_id, collection_id))
            # Keep rows for the real production residual sweep below.

    monkeypatch.setattr(
        document_deletion, "get_user_db_session", independent_session
    )
    monkeypatch.setattr(
        document_deletion,
        "capture_request_db_password",
        lambda _: "test-password",
    )
    monkeypatch.setattr(
        rag_service_factory,
        "get_rag_service",
        lambda *args, **kwargs: VectorObserver(),
    )


@pytest.mark.parametrize("batch", [False, True], ids=["single", "history"])
@pytest.mark.parametrize(
    "persistent", [False, True], ids=["transient", "exhausted"]
)
def test_combined_retry_never_purges_before_commit(
    database, route_session, monkeypatch, tmp_path, batch, persistent
):
    from local_deep_research.config import paths

    seed_family(database, references=False)
    report = tmp_path / "report.md"
    report.write_text("Persist this file until the deletion commits.")
    monkeypatch.setattr(
        paths, "get_research_outputs_directory", lambda: tmp_path
    )
    with Session(database) as writer:
        writer.get(ResearchHistory, "owner").report_path = str(report)
        writer.commit()
    events = []
    observe_actual_purge(monkeypatch, database, events)
    original_commit = route_session.commit
    attempts = 0

    def conflicting_commit():
        nonlocal attempts
        attempts += 1
        assert report.is_file()
        assert events == []
        with Session(database) as verification:
            assert verification.get(ResearchHistory, "owner") is not None
            assert (
                verification.query(DocumentChunk)
                .filter_by(source_id="canonical")
                .count()
                == 2
            )
        if persistent or attempts == 1:
            raise OperationalError(
                "COMMIT", None, sqlite3.OperationalError("database is locked")
            )
        original_commit()

    monkeypatch.setattr(route_session, "commit", conflicting_commit)
    response = call_delete_route(batch)
    with Session(database) as verification:
        if persistent:
            assert response.status_code == 500
            assert attempts == 3
            assert report.is_file()
            assert events == []
            assert verification.get(ResearchHistory, "owner") is not None
            assert verification.get(Document, "canonical") is not None
            assert (
                verification.query(DocumentChunk)
                .filter_by(source_id="canonical")
                .count()
                == 2
            )
        else:
            assert response == {"status": "success"}
            assert attempts == 2
            assert not report.exists()
            assert verification.get(ResearchHistory, "owner") is None
            assert verification.get(Document, "canonical") is None
            assert (
                verification.query(DocumentChunk)
                .filter_by(source_id="canonical")
                .count()
                == 0
            )
            assert events == [
                (kind, "canonical", collection)
                for collection in ("library", "selected")
                for kind in ("vectors",)
            ]


@pytest.mark.parametrize("batch", [False, True], ids=["single", "history"])
def test_combined_retry_refreshes_collection_targets(
    database, route_session, monkeypatch, batch
):
    seed_family(database, references=False)
    events = []
    observe_actual_purge(monkeypatch, database, events)
    original_lookup = research_cascade._shared_document_replacements
    lookups = 0

    def add_collection_after_lookup(*args):
        nonlocal lookups
        found = original_lookup(*args)
        lookups += 1
        if lookups == 1:
            with Session(database) as writer:
                writer.add(Collection(id="added", name="Added during deletion"))
                writer.flush()
                writer.add(
                    DocumentCollection(
                        document_id="canonical",
                        collection_id="added",
                        indexed=True,
                        chunk_count=1,
                    )
                )
                writer.add(
                    DocumentChunk(
                        chunk_hash="added",
                        source_type="document",
                        source_id="canonical",
                        collection_name="collection_added",
                        chunk_text=BODY,
                        chunk_index=0,
                        start_char=0,
                        end_char=len(BODY),
                        word_count=len(BODY.split()),
                        embedding_id="added",
                        embedding_model="test",
                        embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
                    )
                )
                writer.commit()
        return found

    monkeypatch.setattr(
        research_cascade,
        "_shared_document_replacements",
        add_collection_after_lookup,
    )
    assert call_delete_route(batch) == {"status": "success"}
    assert lookups == 2
    assert events == [
        (kind, "canonical", collection)
        for collection in ("added", "library", "selected")
        for kind in ("vectors",)
    ]
    with Session(database) as verification:
        assert verification.get(ResearchHistory, "owner") is None
        assert verification.get(Document, "canonical") is None
        assert (
            verification.query(DocumentChunk)
            .filter_by(source_id="canonical")
            .count()
            == 0
        )


@pytest.mark.parametrize("batch", [False, True], ids=["single", "history"])
def test_target_discovery_shares_the_cascade_snapshot(
    database, route_session, monkeypatch, batch
):
    """A document committed after target discovery must not escape its purge.

    Legacy SQLite SELECTs do not start a database transaction. If discovery
    runs before BEGIN, the cascade can see and delete a newer document while
    cleanup still has the older target list. A shared snapshot forces the
    existing lock retry to rediscover the new document and its vector IDs.
    """
    from local_deep_research.web.routers import research

    seed_family(database, references=False)
    events = []
    observe_actual_purge(monkeypatch, database, events)
    collect = research.collect_research_document_rag_targets
    snapshot_calls = 0

    def collect_then_insert(*args):
        nonlocal snapshot_calls
        targets = collect(*args)
        snapshot_calls += 1
        if snapshot_calls == 1:
            # A separate WAL writer commits a newly indexed document after
            # the target SELECTs but before the cascade's reference lookup.
            with Session(database) as writer:
                writer.add(Collection(id="late", name="Late collection"))
                writer.flush()
                writer.add(
                    Document(
                        id="late-document",
                        source_type_id="source",
                        research_id="owner",
                        document_hash="late-document-hash",
                        file_type="text",
                        file_size=len(BODY),
                        text_content=BODY,
                    )
                )
                writer.flush()
                writer.add(
                    DocumentChunk(
                        chunk_hash="late-document-chunk",
                        source_type="document",
                        source_id="late-document",
                        collection_name="collection_late",
                        chunk_text=BODY,
                        chunk_index=0,
                        start_char=0,
                        end_char=len(BODY),
                        word_count=len(BODY.split()),
                        embedding_id="late",
                        embedding_model="test",
                        embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
                    )
                )
                writer.commit()
        return targets

    monkeypatch.setattr(
        research, "collect_research_document_rag_targets", collect_then_insert
    )
    assert call_delete_route(batch) == {"status": "success"}
    with Session(database) as verification:
        assert verification.get(ResearchHistory, "owner") is None
        assert verification.get(Document, "late-document") is None
        assert (
            verification.query(DocumentChunk)
            .filter_by(source_id="late-document")
            .count()
            == 0
        ), "Deleted document retained its chunk text and vector ID"
    assert snapshot_calls == 2
    assert events == [
        (kind, document_id, collection)
        for document_id, collection in (
            ("canonical", "library"),
            ("canonical", "selected"),
            ("late-document", "late"),
        )
        for kind in ("vectors",)
    ]


@pytest.mark.parametrize("nested", [False, True], ids=["outer", "savepoint"])
def test_target_discovery_preserves_caller_transaction(database, nested):
    """Discovery must neither restart nor commit an active transaction."""
    seed_family(database, references=False)
    with Session(database) as session:
        session.get(ResearchHistory, "owner").query = "Uncommitted change"
        session.flush()
        with session.begin_nested() if nested else nullcontext():
            session.get(Document, "canonical").title = "Uncommitted title"
            session.flush()
            assert research_cascade.collect_research_document_rag_targets(
                session, "owner"
            ) == [("canonical", ["library", "selected"])]
        session.rollback()
    with Session(database) as verification:
        assert verification.get(ResearchHistory, "owner").query == "q"
        assert verification.get(Document, "canonical").title == "Shared paper"


def test_rag_targets_include_a_linked_collection_with_no_chunk_rows(database):
    """A collection the document is linked to still reaches the collector.

    ``collect_research_document_rag_targets`` unions the ``DocumentCollection``
    links onto the collections named by chunk rows. Without the union a
    linked-but-chunkless collection is silently skipped, and its vectors and
    chunks survive the delete (#7504).
    """
    seed_family(database, references=False)
    with Session(database) as session:
        # "linked" has no chunk rows of its own; only the link to it exists.
        session.add(Collection(id="linked", name="Linked collection"))
        session.add(
            DocumentCollection(document_id="canonical", collection_id="linked")
        )
        session.commit()

        assert research_cascade.collect_research_document_rag_targets(
            session, "owner"
        ) == [("canonical", ["library", "linked", "selected"])]


def test_purge_isolates_per_collection_failures(database, monkeypatch):
    """One collection's vector purge failing must not skip the next one."""
    seed_family(database, references=False)
    # The purge only runs once the research and its document are gone (the
    # observer checks the committed delete from a fresh connection).
    with Session(database) as session:
        session.query(DocumentCollection).filter_by(
            document_id="canonical"
        ).delete()
        session.delete(session.get(Document, "canonical"))
        session.delete(session.get(ResearchHistory, "owner"))
        session.commit()
    events = []
    observe_actual_purge(monkeypatch, database, events)

    # observe_actual_purge installed its own get_rag_service; wrap whatever it
    # returns so the first collection's vector purge raises.
    observed = rag_service_factory.get_rag_service
    seen = []

    def failing_once(*args, **kwargs):
        observer = observed(*args, **kwargs)
        real_vectors = observer.purge_documents_vectors

        def purge(document_ids, collection_id):
            seen.append(collection_id)
            if collection_id == "library":
                raise RuntimeError("vector store unavailable")
            return real_vectors(document_ids, collection_id)

        observer.purge_documents_vectors = purge
        return observer

    monkeypatch.setattr(rag_service_factory, "get_rag_service", failing_once)

    document_deletion.DocumentDeletionService(
        "owner"
    ).purge_deleted_research_documents([("canonical", ["library", "selected"])])

    # The failing collection did not stop the next one.
    assert seen == ["library", "selected"]
    assert events == [("vectors", "canonical", "selected")]
    # The residual sweep removes encrypted text even for the collection
    # whose vector file was unavailable.
    with Session(database) as verification:
        assert (
            verification.query(DocumentChunk)
            .filter_by(source_id="canonical")
            .count()
            == 0
        )