~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(library-deletion): bind username to the duplicate-deletion race log (#6509)
LearningCircuit6c28b674542c
diff --git a/changelog.d/5581.bugfix.md b/changelog.d/5581.bugfix.mdnew file mode 100644index 0000000000..6b00fe8dff--- /dev/null+++ b/changelog.d/5581.bugfix.md@@ -0,0 +1 @@+The duplicate-deletion race log ("Document ... was already removed by a concurrent delete request") now carries the acting user's name, so it is written to their `app_logs` table instead of only reaching container/stderr logs. It is not shown in the in-app research log viewer: rows without a research run (research_id is NULL) have no surface that displays them.diff --git a/src/local_deep_research/research_library/deletion/services/document_deletion.py b/src/local_deep_research/research_library/deletion/services/document_deletion.pyindex 075b0f8ee2..af7e0fb69e 100644--- a/src/local_deep_research/research_library/deletion/services/document_deletion.py+++ b/src/local_deep_research/research_library/deletion/services/document_deletion.py@@ -328,7 +328,17 @@ class DocumentDeletionService:session, document_id)if not actually_deleted:- logger.info(+ # Bind the acting user so the record survives the+ # database sink's owner resolution and reaches the+ # user's app_logs — without it the race signal is+ # stderr-only (#5581). The loser just gets an ordinary+ # "not found", so this line is the only trace of the+ # race. The row has no research_id, so neither the+ # research-history cascade nor any retention job ever+ # removes it: bind only a rare event like this one,+ # not per-delete success lines or failures that can+ # repeat for every document of a bulk run.+ logger.bind(username=self.username).info(f"Document {short_id(document_id)} was already removed ""by a concurrent delete request")diff --git a/tests/research_library/deletion/services/test_document_deletion.py b/tests/research_library/deletion/services/test_document_deletion.pyindex 45b3b9edc9..6dea95731c 100644--- a/tests/research_library/deletion/services/test_document_deletion.py+++ b/tests/research_library/deletion/services/test_document_deletion.py@@ -7,6 +7,7 @@ from types import SimpleNamespacefrom unittest.mock import MagicMock, Mock, patchimport pytest+from loguru import loggerfrom local_deep_research.database.models.library import (Document,@@ -21,6 +22,62 @@ from local_deep_research.research_library.deletion.utils.cascade_helper import ()from tests.security.path_max_fixtures import build_path_max_escape+_DELETION_LOGGER_NAME = DocumentDeletionService.__module__+++def deletion_log_records():+ """Real loguru records the deletion service emits during a test.++ Captures the records themselves rather than mocking ``logger.info``: a+ ``logger.bind(...)`` call returns a different logger object, so a patch+ on the module logger never sees it, and only a real record carries the+ ``extra`` fields (the bound ``username``) that the sinks route on. The+ package disables loguru by default; restore that state afterwards (the+ same pairing as ``loguru_caplog`` in tests/conftest.py).+ """+ records = []+ logger.enable("local_deep_research")+ handler_id = logger.add(+ lambda message: records.append(message.record),+ level="INFO",+ filter=lambda record: record["name"] == _DELETION_LOGGER_NAME,+ )+ try:+ yield records+ finally:+ logger.remove(handler_id)+ logger.disable("local_deep_research")+++def database_log_writes():+ """Entries the real ``database_sink`` hands to the app_logs writer.++ Runs the production redaction patcher and the real sink; only the two+ database-facing seams (the queue and the writer) are stubbed, so the+ entries are captured on either dispatch branch whatever thread or event+ loop pytest runs the test on. The per-thread research context is emptied,+ as it is on a deletion request: nothing but a bound ``username`` can give+ such a record an owner.+ """+ from local_deep_research.utilities import log_utils+ from tests.test_utils import restored_loguru_state++ entries = []+ with (+ restored_loguru_state(),+ patch.object(log_utils, "_write_log_to_database", entries.append),+ patch.object(log_utils._log_queue, "put_nowait", entries.append),+ patch.object(+ log_utils, "_get_research_context_fallback", return_value=None+ ),+ ):+ log_utils.install_log_redaction()+ logger.enable("local_deep_research")+ logger.add(log_utils.database_sink, level="INFO", diagnose=False)+ yield entries+class TestDocumentDeletionServiceInit:"""Tests for DocumentDeletionService initialization."""@@ -100,9 +157,17 @@ class TestDocumentDeletionServiceDeleteDocument:assert mock_purge.call_args.kwargs["full_delete"] is Truedef test_zero_row_delete_returns_not_found_without_commit_or_rag_purge(- self,+ self, deletion_log_records):- """A raced DELETE that affects no document row must not report success."""+ """A raced DELETE that affects no document row must not report success.++ The race log must also carry a bound username: database_sink+ resolves the record owner from logger.bind extras first, and an+ unbound record is dropped before _write_log_to_database — hiding+ the race signal from app_logs (#5581). With a username bound the+ record reaches app_logs, though not the in-app research log+ viewer, which only displays rows tied to a research run.+ """service = DocumentDeletionService(username="testuser")mock_session = MagicMock()mock_cm = MagicMock()@@ -126,9 +191,6 @@ class TestDocumentDeletionServiceDeleteDocument:"local_deep_research.research_library.deletion.services.document_deletion.CascadeHelper") as mock_helper,patch.object(service, "_purge_document_rag") as mock_purge,- patch(- "local_deep_research.research_library.deletion.services.document_deletion.logger.info"- ) as mock_info_log,):mock_helper.get_document_collections.return_value = ["col-1"]mock_helper.get_document_blob_size.return_value = 0@@ -144,10 +206,68 @@ class TestDocumentDeletionServiceDeleteDocument:mock_session.rollback.assert_called_once()mock_session.commit.assert_not_called()mock_purge.assert_not_called()- assert mock_info_log.call_count == 1- assert "doc-race..." in mock_info_log.call_args.args[0]+ race_records = [+ r for r in deletion_log_records if "already removed" in r["message"]+ ]+ assert len(race_records) == 1+ assert "doc-race..." in race_records[0]["message"]+ # The binding the database sink needs to route the record into+ # the acting user's app_logs.+ assert race_records[0]["extra"].get("username") == "testuser"++ def test_race_log_reaches_the_database_writer_for_the_acting_user(+ self, database_log_writes+ ):+ """The race record must pass the REAL sink's owner resolution (#5581).++ A deletion request has no research context, and the sink only falls+ back to the request user when a research_id is bound, so an unbound+ record has no owner and never reaches the app_logs writer. The bound+ username is what routes it there. The record belongs to no research+ run, so its row is not shown in the in-app research log viewer.+ """+ service = DocumentDeletionService(username="testuser")+ mock_session = MagicMock()+ mock_cm = MagicMock()+ mock_cm.__enter__ = Mock(return_value=mock_session)+ mock_cm.__exit__ = Mock(return_value=None)- def test_short_id_logs_without_misleading_ellipsis(self):+ mock_doc = MagicMock()+ mock_doc.title = "Raced Document"+ mock_doc.filename = "raced.txt"+ mock_doc.storage_mode = "database"+ mock_doc.file_path = None+ mock_session.get.return_value = mock_doc+ mock_session.query.return_value.filter.return_value.count.return_value = 0++ with (+ patch(+ "local_deep_research.research_library.deletion.services.document_deletion.get_user_db_session",+ return_value=mock_cm,+ ),+ patch(+ "local_deep_research.research_library.deletion.services.document_deletion.CascadeHelper"+ ) as mock_helper,+ patch.object(service, "_purge_document_rag"),+ ):+ mock_helper.get_document_collections.return_value = ["col-1"]+ mock_helper.get_document_blob_size.return_value = 0+ mock_helper.delete_document_completely.return_value = False++ service.delete_document("doc-raced")++ written = [+ e for e in database_log_writes if "already removed" in e["message"]+ ]+ assert len(written) == 1+ assert written[0]["username"] == "testuser"+ assert written[0]["level"] == "INFO"+ assert written[0]["module"] == _DELETION_LOGGER_NAME+ assert written[0]["research_id"] is None++ def test_short_id_logs_without_misleading_ellipsis(+ self, deletion_log_records+ ):"""An id that was never truncated must not gain a ``...`` (#5583):the log line must match the database id exactly for triage."""service = DocumentDeletionService(username="testuser")@@ -173,9 +293,6 @@ class TestDocumentDeletionServiceDeleteDocument:"local_deep_research.research_library.deletion.services.document_deletion.CascadeHelper") as mock_helper,patch.object(service, "_purge_document_rag"),- patch(- "local_deep_research.research_library.deletion.services.document_deletion.logger.info"- ) as mock_info_log,):mock_helper.get_document_collections.return_value = ["col-1"]mock_helper.get_document_blob_size.return_value = 0@@ -183,7 +300,11 @@ class TestDocumentDeletionServiceDeleteDocument:service.delete_document("dockey")- logged = mock_info_log.call_args.args[0]+ race_records = [+ r for r in deletion_log_records if "already removed" in r["message"]+ ]+ assert len(race_records) == 1+ logged = race_records[0]["message"]assert "dockey" in loggedassert "dockey..." not in logged