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.

fix(library-deletion): log short ids without a misleading ellipsis on deletion paths (#6896)

LearningCircuit4377bff5f2c4
diff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.py
index 468fcada02..c66d8d9b39 100644
--- a/src/local_deep_research/chat/service.py
+++ b/src/local_deep_research/chat/service.py
@@ -38,6 +38,7 @@ from ..web.routes.globals import (
)
from ..database.research_cascade import delete_research_with_dependents
from ..constants import ResearchStatus
+from ..utilities.formatting import short_id
# Standard exception tuple for service-layer DB operations
DB_EXCEPTIONS = (ValueError, RuntimeError, SQLAlchemyError)
@@ -1047,8 +1048,8 @@ class ChatService:
# delete leaves a forensic trail tying each deletion to an
# account, not just an opaque session id (L_SEC1).
logger.info(
- f"Deleted chat: user={self.username[:8]}... "
- f"session={session_id[:8]}..."
+ f"Deleted chat: user={short_id(self.username)} "
+ f"session={short_id(session_id)}"
)
return True
@@ -1260,8 +1261,9 @@ class ChatService:
cleanup_research(research_id)
logger.info(
- f"Deleted chat attempt: user={self.username[:8]}... "
- f"session={session_id[:8]}... research={research_id[:8]}... "
+ f"Deleted chat attempt: user={short_id(self.username)} "
+ f"session={short_id(session_id)} "
+ f"research={short_id(research_id)} "
f"({removed_messages} messages)"
)
return True
diff --git a/src/local_deep_research/research_library/deletion/services/collection_deletion.py b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
index 1a27867a42..01994cadb9 100644
--- a/src/local_deep_research/research_library/deletion/services/collection_deletion.py
+++ b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
@@ -22,6 +22,7 @@ from ....database.models.library import (
SourceType,
)
from ....database.session_context import get_user_db_session
+from ....utilities.formatting import short_id
from ..utils.cascade_helper import (
CascadeHelper,
RemoteVectorStoreDropError,
@@ -148,7 +149,7 @@ class CollectionDeletionService:
if collection.collection_type in PROTECTED_COLLECTION_TYPES:
logger.warning(
"Refused to delete protected system collection "
- f"{collection_id[:8]}... (type={collection.collection_type})"
+ f"{short_id(collection_id)} (type={collection.collection_type})"
)
return {
"deleted": False,
@@ -273,7 +274,7 @@ class CollectionDeletionService:
== note_source.id
):
logger.info(
- f"Note {doc_id[:8]}... orphaned by "
+ f"Note {short_id(doc_id)} orphaned by "
"collection deletion — skipping orphan "
"delete; use DELETE /api/notes/<id> "
"to remove."
@@ -286,7 +287,7 @@ class CollectionDeletionService:
orphaned_doc_ids.append(doc_id)
result["orphaned_documents_deleted"] += 1
logger.info(
- f"Deleted orphaned document {doc_id[:8]}..."
+ f"Deleted orphaned document {short_id(doc_id)}"
)
session.commit()
@@ -299,7 +300,7 @@ class CollectionDeletionService:
result["deleted"] = True
logger.info(
- f"Deleted collection {collection_id[:8]}... "
+ f"Deleted collection {short_id(collection_id)} "
f"({result['collection_name']}): {result['chunks_deleted']} chunks, "
f"{result['documents_unlinked']} documents unlinked, "
f"{result['orphaned_documents_deleted']} orphaned deleted"
@@ -488,7 +489,7 @@ class CollectionDeletionService:
result["deleted"] = True
logger.info(
- f"Deleted index for collection {collection_id[:8]}...: "
+ f"Deleted index for collection {short_id(collection_id)}: "
f"{result['chunks_deleted']} chunks, "
f"{result['documents_reset']} documents reset"
)
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.py
index 4a44efa6c7..d97ff65aa5 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
@@ -24,6 +24,7 @@ from ....database.models.library import (
)
from ....database.session_context import get_user_db_session
from ....database.session_passwords import capture_request_db_password
+from ....utilities.formatting import short_id
from ..utils.cascade_helper import CascadeHelper
from ...services.pdf_storage_manager import effective_storage_mode
@@ -301,7 +302,7 @@ class DocumentDeletionService:
)
if not actually_deleted:
logger.info(
- f"Document {document_id[:8]}... was already removed "
+ f"Document {short_id(document_id)} was already removed "
"by a concurrent delete request"
)
session.rollback()
@@ -315,7 +316,7 @@ class DocumentDeletionService:
result["deleted"] = True
logger.info(
- f"Deleted document {document_id[:8]}... ({title}): "
+ f"Deleted document {short_id(document_id)} ({title}): "
f"{result['chunks_deleted']} chunks, "
f"{result['blob_size']} bytes blob"
)
@@ -539,7 +540,7 @@ class DocumentDeletionService:
result["deleted"] = True
logger.info(
- f"Deleted blob for document {document_id[:8]}...: "
+ f"Deleted blob for document {short_id(document_id)}: "
f"{result['bytes_freed']} bytes freed"
)
@@ -701,7 +702,7 @@ class DocumentDeletionService:
# The Notes collection itself acts as the persistent
# home for every note via _get_or_create_notes_collection.
logger.info(
- f"Note {document_id[:8]}... orphaned from collection — "
+ f"Note {short_id(document_id)} orphaned from collection — "
"skipping orphan delete; use DELETE /api/notes/<id> to remove."
)
elif remaining_count == 0:
@@ -709,7 +710,7 @@ class DocumentDeletionService:
# Note: We're already in a session, so we need to do this
# directly rather than calling delete_document()
logger.info(
- f"Document {document_id[:8]}... is orphaned, deleting"
+ f"Document {short_id(document_id)} is orphaned, deleting"
)
# Full delete: purge vectors/chunks across EVERY collection
@@ -791,8 +792,8 @@ class DocumentDeletionService:
result["unlinked"] = True
logger.info(
- f"Removed document {document_id[:8]}... from collection "
- f"{collection_id[:8]}... "
+ f"Removed document {short_id(document_id)} from collection "
+ f"{short_id(collection_id)} "
f"(deleted={result['document_deleted']})"
)
diff --git a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
index 84934e10c4..234349c868 100644
--- a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
+++ b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
@@ -23,6 +23,7 @@ from ....database.models.library import (
DocumentCollection,
RAGIndex,
)
+from ....utilities.formatting import short_id
# A <name>.*.tmp younger than this is assumed to be a concurrent writer's live
# persist() temp (not yet os.replace()d into place); deleting it would crash
@@ -241,7 +242,7 @@ class CascadeHelper:
count = query.delete(synchronize_session=False)
logger.debug(
- f"Deleted {count} chunks for document {document_id[:8]}..."
+ f"Deleted {count} chunks for document {short_id(document_id)}"
+ (f" in collection {collection_name}" if collection_name else "")
)
return count
@@ -314,7 +315,7 @@ class CascadeHelper:
size = len(blob.pdf_binary) if blob.pdf_binary else 0
session.delete(blob)
logger.debug(
- f"Deleted blob for document {document_id[:8]}... ({size} bytes)"
+ f"Deleted blob for document {short_id(document_id)} ({size} bytes)"
)
return size
return 0
@@ -694,7 +695,7 @@ class CascadeHelper:
# logger. Only its type name is kept.
raise RemoteVectorStoreDropError(
f"Failed to drop {item.provider} collection for index "
- f"{index_hash[:12]}...: {type(exc).__name__}. The index "
+ f"{short_id(index_hash, 12)}: {type(exc).__name__}. The index "
"record was NOT deleted.",
retryable=_is_transient_drop_failure(exc),
dropped=completed,
@@ -934,7 +935,7 @@ class CascadeHelper:
tracker.is_downloaded = False # type: ignore[assignment]
tracker.file_path = None # type: ignore[assignment]
logger.debug(
- f"Updated DownloadTracker for document {document.id[:8]}..."
+ f"Updated DownloadTracker for document {short_id(document.id)}"
)
return True
except Exception:
@@ -1028,6 +1029,6 @@ class CascadeHelper:
)
if deleted:
- logger.debug(f"Deleted document {document_id[:8]}... completely")
+ logger.debug(f"Deleted document {short_id(document_id)} completely")
return deleted > 0
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index 741ee4d7f0..f719ad5a91 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -31,6 +31,7 @@ from ...database.models.research import ResearchHistory, ResearchResource
from ...database.session_context import get_user_db_session
from ...config.paths import get_library_directory
from ...utilities.db_utils import get_settings_manager
+from ...utilities.formatting import short_id
from ...utilities.resource_utils import safe_close
from ...security import url_authority_without_userinfo
from ...utilities.sql_utils import escape_like as _escape_like
@@ -1364,7 +1365,7 @@ class LibraryService:
)
if note_source and doc.source_type_id == note_source.id:
logger.warning(
- f"Refused to delete note {document_id[:8]}... via the "
+ f"Refused to delete note {short_id(document_id)} via the "
"library document API; use DELETE /api/notes/<id>."
)
return False
diff --git a/src/local_deep_research/utilities/formatting.py b/src/local_deep_research/utilities/formatting.py
index f3362c8526..a29f2d1955 100644
--- a/src/local_deep_research/utilities/formatting.py
+++ b/src/local_deep_research/utilities/formatting.py
@@ -15,3 +15,25 @@ def human_size(size_bytes: float) -> str:
return f"{size_bytes:.1f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.1f} EB"
+
+
+def short_id(value: str, n: int = 8) -> str:
+ """Render an id for log messages without a misleading ellipsis.
+
+ An id longer than ``n`` characters shortens to its first ``n``
+ characters followed by ``...``. An id that is already at most ``n``
+ characters (for example a short test fixture id) renders as-is, so an
+ operator can trust that ``...`` really means truncation (#5583).
+
+ Use this instead of an inline ``f"{some_id[:8]}..."``: the slice alone
+ cannot tell a truncated id from one that was never truncated.
+
+ Args:
+ value: The id to render; it must be a ``str``.
+ n: How many leading characters to keep.
+
+ Returns:
+ ``value`` itself when it has at most ``n`` characters, otherwise its
+ first ``n`` characters followed by ``...``.
+ """
+ return value[:n] + ("..." if len(value) > n else "")
diff --git a/src/local_deep_research/web/auth/session_manager.py b/src/local_deep_research/web/auth/session_manager.py
index 555b542587..03d4528459 100644
--- a/src/local_deep_research/web/auth/session_manager.py
+++ b/src/local_deep_research/web/auth/session_manager.py
@@ -12,6 +12,7 @@ from typing import Dict, Optional, Set
from loguru import logger
from ...security import get_security_default
+from ...utilities.formatting import short_id
class SessionManager:
@@ -135,7 +136,7 @@ class SessionManager:
# about not logging while holding _lock.
if username is not None:
logger.debug(
- f"Destroyed session {session_id[:8]}... for user {username}"
+ f"Destroyed session {short_id(session_id)} for user {username}"
)
def destroy_all_user_sessions(self, username: str) -> int:
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index bb729d536e..07d0368b0c 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -48,6 +48,7 @@ from ...database.models import (
from ...database.session_context import get_user_db_session
from ...exceptions import DuplicateResearchError, SystemAtCapacityError
from ...settings.manager import SettingsManager
+from ...utilities.formatting import short_id
from ..auth.password_utils import get_user_password, resolve_user_password
from ..routes.globals import (
cleanup_research,
@@ -265,8 +266,8 @@ def _cleanup_chat_send_rows(
except DB_EXCEPTIONS:
logger.exception(
f"Cleanup after {reason} chat-send rejection FAILED "
- f"for research {research_id[:8]}... in chat "
- f"{session_id[:8]}...; orphan rows + inflated "
+ f"for research {short_id(research_id)} in chat "
+ f"{short_id(session_id)}; orphan rows + inflated "
f"message_count may persist until next sweep."
)
diff --git a/tests/research_library/deletion/services/test_document_deletion.py b/tests/research_library/deletion/services/test_document_deletion.py
index 449be2751a..45b3b9edc9 100644
--- a/tests/research_library/deletion/services/test_document_deletion.py
+++ b/tests/research_library/deletion/services/test_document_deletion.py
@@ -147,6 +147,46 @@ class TestDocumentDeletionServiceDeleteDocument:
assert mock_info_log.call_count == 1
assert "doc-race..." in mock_info_log.call_args.args[0]
+ def test_short_id_logs_without_misleading_ellipsis(self):
+ """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")
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+
+ mock_doc = MagicMock()
+ mock_doc.title = "Short Id Document"
+ mock_doc.filename = "short.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"),
+ 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
+ mock_helper.delete_document_completely.return_value = False
+
+ service.delete_document("dockey")
+
+ logged = mock_info_log.call_args.args[0]
+ assert "dockey" in logged
+ assert "dockey..." not in logged
+
def test_document_delete_lock_is_non_reentrant(self):
"""The same thread must not acquire a document delete lock twice."""
from local_deep_research.research_library.deletion.services.document_deletion import (
diff --git a/tests/research_library/deletion/test_log_id_ellipsis.py b/tests/research_library/deletion/test_log_id_ellipsis.py
new file mode 100644
index 0000000000..00be83cd99
--- /dev/null
+++ b/tests/research_library/deletion/test_log_id_ellipsis.py
@@ -0,0 +1,396 @@
+"""Deletion-path log lines must not print ``...`` after an untruncated id.
+
+``f"{some_id[:8]}..."`` renders ``dockey...`` for a six-character id, so an
+operator cannot tell a shortened id from a complete one (#5583). Every such
+site on a deletion path renders its ids through ``short_id`` instead.
+
+This module does two things:
+
+* a tree-wide static guard that fails when the inline ``<id>[:N]`` plus
+ ``...`` shape comes back, in the whole deletion package and in any
+ deletion-named function elsewhere in ``src``, so reverting any single
+ site is caught and not only the one that has a log assertion;
+* behavioural pins for the cascade helper, which runs inside every document
+ delete.
+"""
+
+import ast
+import re
+from pathlib import Path
+from typing import NamedTuple
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+import local_deep_research
+from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+)
+
+SRC_ROOT = Path(local_deep_research.__file__).resolve().parent
+DELETION_PACKAGE = ("research_library", "deletion")
+# Functions whose name says they delete or clean something up. Code in them
+# is a deletion path wherever it lives (chat, sessions, the library service).
+DELETION_FUNCTION = re.compile(
+ r"delet|remov|purg|destroy|cleanup|clean_up", re.IGNORECASE
+)
+ELLIPSES = ("...", "…")
+
+
+class Hit(NamedTuple):
+ lineno: int
+ scope: tuple # enclosing classes and functions, outermost first
+ functions: tuple # the enclosing functions only
+ expression: str
+
+
+def _is_prefix_slice(node):
+ """True for ``expr[:n]`` and ``expr[0:n]``, whatever the bound."""
+ if not isinstance(node, ast.Subscript) or not isinstance(
+ node.slice, ast.Slice
+ ):
+ return False
+ lower, upper, step = node.slice.lower, node.slice.upper, node.slice.step
+ starts_at_zero = lower is None or (
+ isinstance(lower, ast.Constant) and lower.value == 0
+ )
+ return starts_at_zero and upper is not None and step is None
+
+
+def _starts_with_ellipsis(node):
+ return (
+ isinstance(node, ast.Constant)
+ and isinstance(node.value, str)
+ and node.value.startswith(ELLIPSES)
+ )
+
+
+def _last_operand(node):
+ """The right-most operand of a ``+`` chain (``a + b + c`` gives ``c``)."""
+ while isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
+ node = node.right
+ return node
+
+
+class _EllipsisFinder(ast.NodeVisitor):
+ """Collect ``<expr>[:n]`` immediately followed by an ellipsis literal.
+
+ Two shapes are flagged: an f-string replacement field holding the slice
+ whose next literal part starts with ``...``, and ``slice + "..."``. A
+ ``slice + "..."`` that is a branch of a conditional expression is not
+ flagged, because that is the explicitly guarded (correct) inline form.
+ """
+
+ def __init__(self):
+ self.scope = []
+ self.functions = []
+ self.hits = []
+ self._guarded = set()
+
+ def _enter_function(self, node):
+ self.scope.append(node.name)
+ self.functions.append(node.name)
+ self.generic_visit(node)
+ self.functions.pop()
+ self.scope.pop()
+
+ def visit_ClassDef(self, node):
+ self.scope.append(node.name)
+ self.generic_visit(node)
+ self.scope.pop()
+
+ visit_FunctionDef = _enter_function
+ visit_AsyncFunctionDef = _enter_function
+
+ def _hit(self, sliced):
+ self.hits.append(
+ Hit(
+ sliced.lineno,
+ tuple(self.scope),
+ tuple(self.functions),
+ ast.unparse(sliced),
+ )
+ )
+
+ def visit_JoinedStr(self, node):
+ for part, following in zip(node.values, node.values[1:]):
+ if (
+ isinstance(part, ast.FormattedValue)
+ and _is_prefix_slice(part.value)
+ and _starts_with_ellipsis(following)
+ ):
+ self._hit(part.value)
+ self.generic_visit(node)
+
+ def visit_IfExp(self, node):
+ for branch in (node.body, node.orelse):
+ if isinstance(branch, ast.BinOp):
+ self._guarded.add(id(branch))
+ self.generic_visit(node)
+
+ def visit_BinOp(self, node):
+ if (
+ isinstance(node.op, ast.Add)
+ and id(node) not in self._guarded
+ and _starts_with_ellipsis(node.right)
+ ):
+ sliced = _last_operand(node.left)
+ if _is_prefix_slice(sliced):
+ self._hit(sliced)
+ self.generic_visit(node)
+
+
+def find_ellipsis_hits(source):
+ """Every ``<expr>[:n]`` in ``source`` that is followed by an ellipsis."""
+ finder = _EllipsisFinder()
+ finder.visit(ast.parse(source))
+ return finder.hits
+
+
+def find_violations(src_root):
+ """Flagged expressions on deletion paths under ``src_root``."""
+ violations = []
+ for path in sorted(Path(src_root).rglob("*.py")):
+ relative = path.relative_to(src_root)
+ in_deletion_package = relative.parts[:2] == DELETION_PACKAGE
+ for hit in find_ellipsis_hits(path.read_text(encoding="utf-8")):
+ if in_deletion_package or any(
+ DELETION_FUNCTION.search(name) for name in hit.functions
+ ):
+ where = ".".join(hit.scope) or "<module>"
+ violations.append(
+ f"{relative.as_posix()}:{hit.lineno} in {where}: "
+ f"{hit.expression} is followed by a literal ellipsis"
+ )
+ return violations
+
+
+class TestDeletionPathsNeverAppendEllipsisToAnIdSlice:
+ """The guard over the real source tree."""
+
+ def test_no_site_prints_an_unconditional_ellipsis_after_an_id_slice(self):
+ violations = find_violations(SRC_ROOT)
+ assert not violations, (
+ "A deletion path logs a sliced value followed by a hard-coded "
+ "'...', so ids that were never truncated read as truncated "
+ "(#5583). Render it with short_id(value, n) from "
+ "local_deep_research.utilities.formatting instead:\n "
+ + "\n ".join(violations)
+ )
+
+ def test_guard_is_not_vacuous(self):
+ """The deletion package is where the guard expects it to be."""
+ package = SRC_ROOT.joinpath(*DELETION_PACKAGE)
+ modules = {path.name for path in package.rglob("*.py")}
+ assert {
+ "cascade_helper.py",
+ "collection_deletion.py",
+ "document_deletion.py",
+ } <= modules
+
+
+class TestFinderRecognisesTheShape:
+ """The guard itself: what it flags and what it must leave alone."""
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ pytest.param('f"gone {doc_id[:8]}..."', id="fstring"),
+ pytest.param('f"gone {doc_id[:8]}...: ok"', id="fstring-then-text"),
+ pytest.param('f"gone {doc_id[:8]}…"', id="unicode-ellipsis"),
+ pytest.param('f"gone {doc_id[0:8]}..."', id="explicit-zero-start"),
+ pytest.param('f"gone {doc_id[:12]}..."', id="other-width"),
+ pytest.param('f"gone {doc_id[:WIDTH]}..."', id="named-width"),
+ pytest.param('f"gone {doc.id[:8]}..."', id="attribute-id"),
+ pytest.param('f"gone {str(doc_id)[:8]}..."', id="call-result"),
+ pytest.param('f"gone {doc_id[:8]!r}..."', id="conversion"),
+ pytest.param('doc_id[:8] + "..."', id="concatenation"),
+ pytest.param(
+ '"gone " + doc_id[:8] + "..."', id="chained-concatenation"
+ ),
+ pytest.param('doc_id[:8] + "…"', id="concatenation-unicode"),
+ pytest.param(
+ 'f"gone {a[:8]}... and {b[:8]}..."', id="two-in-one-message"
+ ),
+ ],
+ )
+ def test_flags_an_inline_slice_followed_by_an_ellipsis(self, source):
+ assert find_ellipsis_hits(f"def delete_it(doc_id):\n {source}\n")
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ pytest.param('f"gone {short_id(doc_id)}"', id="helper"),
+ pytest.param('f"gone {doc_id[:8]}"', id="slice-without-ellipsis"),
+ pytest.param('f"gone {doc_id}..."', id="ellipsis-without-slice"),
+ pytest.param('f"gone {doc_id[2:8]}..."', id="not-a-prefix-slice"),
+ pytest.param('f"gone {doc_id[:8]} ..."', id="space-before-dots"),
+ pytest.param(
+ "f\"gone {doc_id[:8]}{'...' if len(doc_id) > 8 else ''}\"",
+ id="conditional-inside-the-field",
+ ),
+ pytest.param(
+ 'doc_id[:8] + "..." if len(doc_id) > 8 else doc_id',
+ id="guarded-concatenation",
+ ),
+ pytest.param('doc_id[:8] + "-gone"', id="other-suffix"),
+ pytest.param(
+ '"gone " + doc_id[:8] + "-done"', id="chained-other-suffix"
+ ),
+ ],
+ )
+ def test_leaves_correct_code_alone(self, source):
+ assert not find_ellipsis_hits(f"def delete_it(doc_id):\n {source}\n")
+
+ def test_reports_the_scope_and_expression(self):
+ source = (
+ "class Svc:\n"
+ " def delete_it(self, doc_id):\n"
+ ' return f"gone {doc_id[:8]}..."\n'
+ )
+ (hit,) = find_ellipsis_hits(source)
+ assert hit.scope == ("Svc", "delete_it")
+ assert hit.functions == ("delete_it",)
+ assert hit.expression == "doc_id[:8]"
+
+
+class TestFindViolationsScope:
+ """Which code the guard treats as a deletion path."""
+
+ SNIPPET = 'def {name}(doc_id):\n return f"gone {{doc_id[:8]}}..."\n'
+
+ @staticmethod
+ def _tree(tmp_path, files):
+ for relative, source in files.items():
+ target = tmp_path / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(source, encoding="utf-8")
+ return tmp_path
+
+ def test_everything_in_the_deletion_package_is_scanned(self, tmp_path):
+ root = self._tree(
+ tmp_path,
+ {
+ "research_library/deletion/utils/helper.py": (
+ self.SNIPPET.format(name="anything")
+ ),
+ "research_library/deletion/module_level.py": (
+ 'MESSAGE = f"gone {doc_id[:8]}..."\n'
+ ),
+ },
+ )
+ found = find_violations(root)
+ assert len(found) == 2
+ assert any(
+ "helper.py:" in line and " in anything:" in line for line in found
+ )
+ assert any("module_level.py:1 in <module>:" in line for line in found)
+
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "delete_session",
+ "_delete_document_locked",
+ "remove_from_collection",
+ "purge_old_rows",
+ "destroy_session",
+ "_cleanup_chat_send_rows",
+ "clean_up_after_failure",
+ ],
+ )
+ def test_deletion_named_functions_elsewhere_are_scanned(
+ self, tmp_path, name
+ ):
+ root = self._tree(
+ tmp_path, {"chat/service.py": self.SNIPPET.format(name=name)}
+ )
+ assert len(find_violations(root)) == 1
+
+ def test_a_closure_inside_a_deletion_named_function_is_scanned(
+ self, tmp_path
+ ):
+ source = (
+ "def delete_session(doc_id):\n"
+ " def _impl():\n"
+ ' return f"gone {doc_id[:8]}..."\n'
+ " return _impl\n"
+ )
+ root = self._tree(tmp_path, {"web/routers/chat.py": source})
+ assert len(find_violations(root)) == 1
+
+ @pytest.mark.parametrize(
+ "name", ["create_session", "send_message", "get_session", "_impl"]
+ )
+ def test_other_functions_elsewhere_are_left_alone(self, tmp_path, name):
+ root = self._tree(
+ tmp_path, {"chat/service.py": self.SNIPPET.format(name=name)}
+ )
+ assert find_violations(root) == []
+
+ def test_a_deletion_named_class_alone_does_not_make_a_path(self, tmp_path):
+ source = (
+ "class DeletionRecord:\n"
+ " def describe(self, doc_id):\n"
+ ' return f"gone {doc_id[:8]}..."\n'
+ )
+ root = self._tree(tmp_path, {"models/record.py": source})
+ assert find_violations(root) == []
+
+
+CASCADE_MODULE = (
+ "local_deep_research.research_library.deletion.utils.cascade_helper"
+)
+
+
+def _debug_message(call):
+ """Run ``call`` and return the one debug message the helper logged."""
+ with patch(f"{CASCADE_MODULE}.logger") as mock_logger:
+ call()
+ assert mock_logger.debug.call_count == 1
+ return mock_logger.debug.call_args.args[0]
+
+
+def _delete_chunks(doc_id):
+ session = MagicMock()
+ session.query.return_value.filter.return_value.delete.return_value = 3
+ return lambda: CascadeHelper.delete_document_chunks(session, doc_id)
+
+
+def _delete_blob(doc_id):
+ session = MagicMock()
+ blob = MagicMock()
+ blob.pdf_binary = b"1234"
+ session.query.return_value.filter_by.return_value.first.return_value = blob
+ return lambda: CascadeHelper.delete_document_blob(session, doc_id)
+
+
+def _delete_completely(doc_id):
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.delete.return_value = 1
+ return lambda: CascadeHelper.delete_document_completely(session, doc_id)
+
+
+CASCADE_LOGGING_CALLS = [
+ pytest.param(_delete_chunks, id="delete_document_chunks"),
+ pytest.param(_delete_blob, id="delete_document_blob"),
+ pytest.param(_delete_completely, id="delete_document_completely"),
+]
+
+
+class TestCascadeHelperLogsIdsWithoutMisleadingEllipsis:
+ """CascadeHelper runs inside every document delete (#5583)."""
+
+ @pytest.mark.parametrize("make_call", CASCADE_LOGGING_CALLS)
+ @pytest.mark.parametrize("doc_id", ["dockey", "12345678"])
+ def test_an_id_that_was_never_truncated_gets_no_ellipsis(
+ self, make_call, doc_id
+ ):
+ message = _debug_message(make_call(doc_id))
+ assert doc_id in message
+ assert f"{doc_id}..." not in message
+
+ @pytest.mark.parametrize("make_call", CASCADE_LOGGING_CALLS)
+ def test_a_truncated_id_still_ends_in_an_ellipsis(self, make_call):
+ message = _debug_message(make_call("0123456789abcdef"))
+ assert "01234567..." in message
+ assert "0123456789abcdef" not in message
diff --git a/tests/research_library/deletion/test_provider_aware_vector_cleanup.py b/tests/research_library/deletion/test_provider_aware_vector_cleanup.py
index 0b1758b568..da298c60bb 100644
--- a/tests/research_library/deletion/test_provider_aware_vector_cleanup.py
+++ b/tests/research_library/deletion/test_provider_aware_vector_cleanup.py
@@ -255,6 +255,33 @@ class TestRemoteDropFailureAborts:
assert excinfo.value.retryable is True
assert excinfo.value.cause_type == "ConnectionError"
+ @pytest.mark.parametrize(
+ "index_hash, rendered",
+ [
+ ("hash-one", "hash-one"),
+ ("0123456789ab", "0123456789ab"),
+ ("0123456789abcdef", "0123456789ab..."),
+ ],
+ )
+ def test_failure_message_ellipsis_only_marks_a_truncated_hash(
+ self, index_hash, rendered
+ ):
+ """``...`` after the hash must mean the hash was cut (#5583)."""
+ events = []
+ session = _session_returning([_fake_index(index_hash)], events)
+ stub = _make_remote_stub(events, error=ConnectionError("no route"))
+
+ with _registered_as_default(stub):
+ with pytest.raises(RemoteVectorStoreDropError) as excinfo:
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ assert f"for index {rendered}: ConnectionError" in str(excinfo.value)
+
def test_missing_username_refuses_rather_than_orphaning(self):
"""Half the derived collection name is the username.
diff --git a/tests/utilities/test_formatting.py b/tests/utilities/test_formatting.py
new file mode 100644
index 0000000000..e7e7581937
--- /dev/null
+++ b/tests/utilities/test_formatting.py
@@ -0,0 +1,48 @@
+"""Tests for the shared formatting helpers."""
+
+import pytest
+
+from local_deep_research.utilities.formatting import short_id
+
+
+class TestShortId:
+ """short_id renders ids without a misleading ellipsis (#5583)."""
+
+ def test_long_id_truncates_with_ellipsis(self):
+ assert short_id("doc-raced-long") == "doc-race..."
+
+ def test_short_id_renders_as_is(self):
+ assert short_id("dockey") == "dockey"
+
+ def test_exactly_eight_chars_gets_no_ellipsis(self):
+ assert short_id("12345678") == "12345678"
+
+ def test_nine_chars_truncates(self):
+ assert short_id("123456789") == "12345678..."
+
+ def test_empty_id_renders_as_empty(self):
+ assert short_id("") == ""
+
+ def test_uuid_shortens_to_its_first_group(self):
+ assert short_id("550e8400-e29b-41d4-a716-446655440000") == (
+ "550e8400..."
+ )
+
+ def test_length_counts_characters_not_bytes(self):
+ assert short_id("é" * 8) == "é" * 8
+ assert short_id("é" * 9) == "é" * 8 + "..."
+
+ def test_custom_width(self):
+ digest = "a" * 64
+ assert short_id(digest, 12) == "a" * 12 + "..."
+ assert short_id("a" * 12, 12) == "a" * 12
+
+ @pytest.mark.parametrize("length", range(0, 20))
+ def test_ellipsis_appears_exactly_when_the_id_was_cut(self, length):
+ """``...`` must mean truncation, whatever the id length."""
+ value = "x" * length
+ rendered = short_id(value)
+ if length <= 8:
+ assert rendered == value
+ else:
+ assert rendered == "x" * 8 + "..."