~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): PDF content-hash dedup (B1) and URL-hash normalization (B2) (#6758) (#6760)
S41a8bc9b278c
diff --git a/changelog.d/6758.bugfix.md b/changelog.d/6758.bugfix.mdnew file mode 100644index 0000000000..b438b531b3--- /dev/null+++ b/changelog.d/6758.bugfix.md@@ -0,0 +1 @@+Deduplicate Library PDF downloads by content hash across different URLs instead of failing on a unique-constraint error, and normalize URLs (tracking params, fragments, default ports) before download-tracker hashing so the same article is not downloaded twice.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.pyindex de7a7a29e5..be0301a992 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,7 +23,6 @@ from ....database.models.library import (DocumentCollection,RAGIndex,)-from ....database.models.download_tracker import DownloadTracker# 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@@ -886,16 +885,12 @@ class CascadeHelper:if not document.original_url:return False- # Get URL hash using the same method as library_service- from ...utils import get_url_hash+ # B2 compat (#6758): match legacy-hash rows as well as the+ # canonical hash so pre-upgrade trackers are still reset.+ from ...utils import find_tracker_by_urltry:- url_hash = get_url_hash(str(document.original_url))- tracker = (- session.query(DownloadTracker)- .filter_by(url_hash=url_hash)- .first()- )+ tracker = find_tracker_by_url(session, str(document.original_url))if tracker:tracker.is_downloaded = False # type: ignore[assignment]diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex c3ecb9ff7c..f3e63e9e76 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -27,6 +27,7 @@ from pypdf import PdfReaderfrom ...utilities.arxiv import extract_arxiv_id, is_arxiv_paper_urlfrom ...utilities.type_utils import unwrap_setting+from ...utilities.url_utils import canonical_url_keyfrom ...constants import FILE_PATH_SENTINELS, FILE_PATH_TEXT_ONLYfrom ...database.models.download_tracker import (DownloadAttempt,@@ -65,8 +66,10 @@ from ...config.paths import get_library_directoryfrom ..utils import (apply_user_subdir,ensure_in_collection,+ find_tracker_by_url,get_document_for_resource,get_url_hash,+ get_url_hash_candidates,get_absolute_path_from_settings,is_downloadable_url,)@@ -324,7 +327,14 @@ class DownloadService:)def _normalize_url(self, url: str) -> str:- """Normalize URL for consistent hashing."""+ """Normalize URL for consistent hashing.++ Legacy spelling (pre-B2 #6758): retained for back-compat callers+ and unit tests, but NOT used by :meth:`_get_url_hash` anymore —+ that path goes through the shared ``normalize_url_for_hash``+ (lowercase-before-sort) so writer and readers agree (issue #6760+ follow-up).+ """# Remove protocol variationsurl = re.sub(r"^https?://", "", url)# Remove www@@ -339,9 +349,24 @@ class DownloadService:return url.lower()def _get_url_hash(self, url: str) -> str:- """Generate SHA256 hash of normalized URL."""- normalized = self._normalize_url(url)- return get_url_hash(normalized)+ """Generate SHA256 hash of normalized URL.++ B2 (issue #6758): canonicalize the raw URL first so tracking+ params, fragments, default ports, and userinfo hash alike — the+ legacy ``_normalize_url`` strip alone strips the scheme before the+ canonical form can be parsed, which would silently keep the gap.++ The writer must hash exactly what the readers hash: ``get_url_hash``+ already applies :func:`normalize_url_for_hash` (canonicalize ++ strip + lowercase-before-sort), so composing ``_normalize_url`` here+ double-normalizes — ``sort(raw-case).lower()`` followed by a second+ ``sort(lower)`` — and diverges from the single-normalized reader on+ mixed-case query URLs (issue #6760 follow-up: writer hash in none+ of the reader candidates → sync deletes the document, re-download+ then hits ``uq_download_tracker_url_hash``). Pass the canonical+ form straight into ``get_url_hash``.+ """+ return get_url_hash(canonical_url_key(url))def _build_egress_context(self, settings_snapshot):"""Build an EgressContext from the supplied snapshot. Returns@@ -439,14 +464,20 @@ class DownloadService:Returns:Tuple of (is_downloaded, file_path)"""- url_hash = self._get_url_hash(url)-+ # B2 compat (#6758): pre-upgrade rows still carry a legacy url_hash;+ # match canonical first, then legacy spellings (sequential+ # filter_by so MagicMock-forced misses keep working).with get_user_db_session(self.username, self.password) as session:- tracker = (- session.query(DownloadTracker)- .filter_by(url_hash=url_hash, is_downloaded=True)- .first()- )+ candidates = get_url_hash_candidates(url)+ tracker = None+ for candidate in candidates:+ tracker = (+ session.query(DownloadTracker)+ .filter_by(url_hash=candidate, is_downloaded=True)+ .first()+ )+ if tracker is not None:+ breakif tracker and tracker.file_path:# Compute absolute path and verify file still exists. Pass the@@ -708,13 +739,11 @@ class DownloadService:else None)- # Create download tracker entry+ # Create download tracker entry. B2 compat (#6758): reuse a+ # pre-upgrade legacy-hash row when present instead of inserting+ # a second tracker for the same URL.url_hash = self._get_url_hash(resource.url)- tracker = (- session.query(DownloadTracker)- .filter_by(url_hash=url_hash)- .first()- )+ tracker = find_tracker_by_url(session, resource.url)if not tracker:# Wrap the new-tracker INSERT in a SAVEPOINT so it is@@ -822,13 +851,26 @@ class DownloadService:from ...web.routers.rag import trigger_auto_indexfrom ...database.library_init import get_default_library_id- # Get the document that was just created+ # Resolve via get_document_for_resource so a dedup-linked+ # resource (resource.document_id -> canonical Document+ # owned by another resource) still triggers indexing —+ # the old resource_id-only lookup missed it and skipped+ # auto-indexing in the requested collection (#6758).+ resource_for_index = session.get(+ ResearchResource, resource_id+ )doc = (- session.query(Document)- .filter_by(resource_id=resource_id_val)- .order_by(Document.created_at.desc())- .first()+ get_document_for_resource(session, resource_for_index)+ if resource_for_index is not None+ else None)+ if doc is None:+ doc = (+ session.query(Document)+ .filter_by(resource_id=resource_id)+ .order_by(Document.created_at.desc())+ .first()+ )if doc:# Use collection_id from queue entry or default Library# NB: pass username string, not the SQLAlchemy session@@ -1151,68 +1193,215 @@ class DownloadService:tracker.file_path = target_tracker.file_pathtracker.file_name = target_tracker.file_nameelse:- # Get source type ID for research downloads- try:- source_type_id = get_source_type_id(- self.username, "research_download", self.password+ # B1 (issue #6758): content-hash dedup across resources.+ # Two different URLs can yield identical PDF bytes. Without+ # a pre-check the INSERT below violates UNIQUE(document_hash)+ # and the second resource ends up document-less after the+ # IntegrityError rollback. Mirror the text-path pre-check in+ # _save_text_with_db: link to the canonical Document instead.+ existing_by_hash = (+ sess.query(Document)+ .filter_by(document_hash=target_tracker.file_hash)+ .first()+ )+ if existing_by_hash:+ target_resource.document_id = existing_by_hash.id+ try:+ dedup_collection_id = (+ collection_id+ or get_default_library_id(+ self.username, self.password+ )+ )+ except Exception:+ logger.exception(+ "Failed to get library collection for dedup link"+ )+ dedup_collection_id = None+ if dedup_collection_id:+ ensure_in_collection(+ sess,+ existing_by_hash.id,+ dedup_collection_id,+ )+ else:+ logger.warning(+ f"Library collection not found - deduped document {existing_by_hash.id} will not be linked to default collection"+ )+ # Preserve/upgrade PDF storage on the dedup hit path.+ # Without this, a first download with storage "none"+ # followed by identical bytes with storage "database"+ # leaves the canonical document with no saved PDF while+ # the second tracker claims success. Only upgrade (never+ # downgrade): when the canonical already stores the PDF,+ # mirror its location onto this tracker for consistency.+ try:+ needs_upgrade = (+ existing_by_hash.storage_mode in (None, "none")+ ) and (+ pdf_storage_mode in ("database", "filesystem")+ )+ if needs_upgrade:+ file_path_result, _ = (+ pdf_storage_manager.save_pdf(+ pdf_content=pdf_content,+ document=existing_by_hash,+ session=sess,+ filename=f"{target_resource.id}.pdf",+ url=url,+ resource_id=target_resource.id,+ )+ )+ target_tracker.file_path = (+ file_path_result+ if file_path_result+ else None+ )+ target_tracker.file_name = (+ Path(file_path_result).name+ if file_path_result+ and file_path_result != "database"+ else None+ )+ # Keep sibling trackers for the same bytes+ # consistent: the canonical URL's tracker still+ # has file_path=None from its none-mode download,+ # which would otherwise make sync treat the now+ # upgraded document as missing.+ try:+ siblings = (+ sess.query(DownloadTracker)+ .filter_by(+ file_hash=target_tracker.file_hash+ )+ .all()+ )+ for sibling in siblings:+ if not sibling.file_path:+ sibling.file_path = (+ target_tracker.file_path+ )+ sibling.file_name = (+ target_tracker.file_name+ )+ except Exception:+ logger.exception(+ "Failed to sync sibling trackers after storage upgrade"+ )+ elif existing_by_hash.storage_mode == "database":+ target_tracker.file_path = "database"+ target_tracker.file_name = None+ elif (+ existing_by_hash.file_path+ in FILE_PATH_SENTINELS+ ):+ # Never mirror file_path sentinels+ # (``blob_deleted``, ``text_only_not_stored``,+ # ``metadata_only``) into the tracker: they name+ # no file, and the sync mid-branch would resolve+ # them as a relative path, miss, and run+ # ``delete_document_completely`` on the+ # text/chunks/vectors the sentinel was protecting+ # (issue #6760 follow-up). Leave the duplicate+ # tracker path-less, the same shape as a fresh+ # none-mode download.+ target_tracker.file_path = None+ target_tracker.file_name = None+ elif existing_by_hash.file_path:+ target_tracker.file_path = (+ existing_by_hash.file_path+ )+ target_tracker.file_name = (+ Path(existing_by_hash.file_path).name+ if existing_by_hash.file_path != "database"+ else None+ )+ else:+ # Canonical has no stored file (none-mode): same+ # shape as a fresh none-mode download+ # (is_downloaded=True, no path). Bounded+ # re-download, not data loss.+ target_tracker.file_path = None+ target_tracker.file_name = None+ except Exception:+ logger.exception(+ "Failed to reuse/upgrade deduped PDF storage"+ )+ if hasattr(tracker, "file_path"):+ tracker.file_path = target_tracker.file_path+ tracker.file_name = target_tracker.file_name+ logger.info(+ f"Linked resource {target_resource.id} to existing Document "+ f"{existing_by_hash.id} (matched on content hash)")- # Use provided collection_id or default to Library- library_collection_id = (- collection_id- or get_default_library_id(- self.username, self.password+ else:+ # Get source type ID for research downloads+ try:+ source_type_id = get_source_type_id(+ self.username,+ "research_download",+ self.password,+ )+ # Use provided collection_id or default to Library+ library_collection_id = (+ collection_id+ or get_default_library_id(+ self.username, self.password+ )+ )+ except Exception:+ logger.exception(+ "Failed to get source type or library collection")+ raise++ # Create new unified document entry+ doc_id = str(uuid.uuid4())+ doc = Document(+ id=doc_id,+ source_type_id=source_type_id,+ resource_id=target_resource.id,+ research_id=target_resource.research_id,+ document_hash=target_tracker.file_hash,+ original_url=url,+ file_size=len(pdf_content),+ file_type="pdf",+ mime_type="application/pdf",+ title=target_resource.title,+ status=DocumentStatus.COMPLETED,+ processed_at=datetime.now(UTC),+ storage_mode=pdf_storage_mode,)- except Exception:- logger.exception(- "Failed to get source type or library collection"+ sess.add(doc)+ sess.flush() # Ensure doc.id is available for blob storage+ # Save PDF using storage manager (updates storage_mode and file_path)+ file_path_result, _ = pdf_storage_manager.save_pdf(+ pdf_content=pdf_content,+ document=doc,+ session=sess,+ filename=f"{target_resource.id}.pdf",+ url=url,+ resource_id=target_resource.id,)- raise- # Create new unified document entry- doc_id = str(uuid.uuid4())- doc = Document(- id=doc_id,- source_type_id=source_type_id,- resource_id=target_resource.id,- research_id=target_resource.research_id,- document_hash=target_tracker.file_hash,- original_url=url,- file_size=len(pdf_content),- file_type="pdf",- mime_type="application/pdf",- title=target_resource.title,- status=DocumentStatus.COMPLETED,- processed_at=datetime.now(UTC),- storage_mode=pdf_storage_mode,- )- sess.add(doc)- sess.flush() # Ensure doc.id is available for blob storage- # Save PDF using storage manager (updates storage_mode and file_path)- file_path_result, _ = pdf_storage_manager.save_pdf(- pdf_content=pdf_content,- document=doc,- session=sess,- filename=f"{target_resource.id}.pdf",- url=url,- resource_id=target_resource.id,- )-- # Update tracker- target_tracker.file_path = (- file_path_result if file_path_result else None- )- target_tracker.file_name = (- Path(file_path_result).name- if file_path_result and file_path_result != "database"- else None- )- if hasattr(tracker, "file_path"):- tracker.file_path = target_tracker.file_path- tracker.file_name = target_tracker.file_name+ # Update tracker+ target_tracker.file_path = (+ file_path_result if file_path_result else None+ )+ target_tracker.file_name = (+ Path(file_path_result).name+ if file_path_result+ and file_path_result != "database"+ else None+ )+ if hasattr(tracker, "file_path"):+ tracker.file_path = target_tracker.file_path+ tracker.file_name = target_tracker.file_name- # Link document to default Library collection- ensure_in_collection(sess, doc_id, library_collection_id)+ # Link document to default Library collection+ ensure_in_collection(+ sess, doc_id, library_collection_id+ )if pdf_storage_mode == "database":logger.info(diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex f1b20eefaf..ba16bdc142 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -34,8 +34,8 @@ from ...utilities.db_utils import get_settings_managerfrom ...utilities.resource_utils import safe_closefrom ...utilities.sql_utils import escape_like as _escape_likefrom ..utils import (+ find_tracker_by_url,get_absolute_path_from_settings,- get_url_hash,open_file_location,)@@ -1071,14 +1071,12 @@ class LibraryService:)return False- # Get file path from tracker (only if document has original_url)+ # Get file path from tracker (only if document has original_url).+ # B2 compat (#6758): match legacy-hash rows so pre-upgrade+ # documents still unlink their physical file.tracker = Noneif doc.original_url:- tracker = (- session.query(DownloadTracker)- .filter_by(url_hash=self._get_url_hash(doc.original_url))- .first()- )+ tracker = find_tracker_by_url(session, doc.original_url)# Delete physical file. Own-root only: never resolve via the# legacy shared root, where a colliding relative path can be@@ -1149,11 +1147,8 @@ class LibraryService:tracker = Noneif doc.original_url:- tracker = (- session.query(DownloadTracker)- .filter_by(url_hash=self._get_url_hash(doc.original_url))- .first()- )+ # B2 compat (#6758): match legacy-hash rows.+ tracker = find_tracker_by_url(session, doc.original_url)if tracker and tracker.file_path:# Resolve within the per-user root (traversal + symlink safe),@@ -1198,17 +1193,6 @@ class LibraryService:except (ValueError, AttributeError):return ""- def _get_url_hash(self, url: str) -> str:- """Generate hash for URL."""- import re-- # Normalize URL- url = re.sub(r"^https?://", "", url)- url = re.sub(r"^www\.", "", url)- url = url.rstrip("/")-- return get_url_hash(url)-def _get_storage_path(self) -> str:"""Get library storage path from settings (respects LDR_DATA_DIR)."""settings = get_settings_manager()@@ -1277,16 +1261,50 @@ class LibraryService:settings_manager = Nonetry:for doc in documents:- # Get download tracker- tracker = (- session.query(DownloadTracker)- .filter_by(- url_hash=self._get_url_hash(doc.original_url)- )- .first()- )+ # Get download tracker. B2 compat (#6758): match+ # legacy-hash rows so pre-upgrade documents are not+ # mistaken for tracker-less orphans and deleted below.+ tracker = find_tracker_by_url(session, doc.original_url)if tracker and tracker.file_path:+ # Sentinel tracker paths (``blob_deleted``,+ # ``text_only_not_stored``, ``metadata_only``) name+ # no file by design — e.g. a blob purge keeps the+ # document complete with ``file_path="blob_deleted"``+ # while a dedup-mirrored duplicate tracker could+ # still carry that value. Resolving one as a+ # relative path always misses and would run+ # ``delete_document_completely`` on the+ # text/chunks/vectors the sentinel was protecting+ # (issue #6760 follow-up). Leave them alone like the+ # text-only branch below.+ if tracker.file_path in FILE_PATH_SENTINELS:+ stats["files_found"] += 1+ continue+ # Database-stored PDFs have no filesystem file to+ # sync — the blob is the source of truth. Treat a+ # present blob as found instead of falling into the+ # missing-file path that deletes the document.+ if (+ tracker.file_path == "database"+ or doc.storage_mode == "database"+ ):+ from ...database.models.library import (+ DocumentBlob,+ )++ has_blob = (+ session.query(DocumentBlob.document_id)+ .filter_by(document_id=doc.id)+ .first()+ is not None+ )+ if has_blob:+ stats["files_found"] += 1+ continue+ # Text-only documents (storage none) have no file+ # either; leave them alone (see the no-path branch+ # below for the tracker.file_path=None shape).# Check if file exists (per-user, legacy-shared fallback)if settings_manager is None:settings_manager = get_settings_manager(@@ -1328,7 +1346,16 @@ class LibraryService:removed_doc_ids.append(doc.id)stats["trackers_updated"] += 1else:- # No tracker or path - delete the document entry+ # No tracker or path. Text-only documents+ # (storage_mode "none") never have a file by design —+ # deleting them here would destroy text, chunks, and+ # vectors that are recoverable only by re-download+ # (dead links = permanent loss). Leave them alone.+ if (doc.storage_mode in (None, "none")) or (+ doc.file_path in FILE_PATH_SENTINELS+ ):+ stats["files_found"] += 1+ continuestats["files_missing"] += 1from ..deletion.utils.cascade_helper import (CascadeHelper,@@ -1414,14 +1441,10 @@ class LibraryService:"document has no original_url (likely user upload)")continue- # Get tracker and reset it- tracker = (- session.query(DownloadTracker)- .filter_by(- url_hash=self._get_url_hash(doc.original_url)- )- .first()- )+ # Get tracker and reset it. B2 compat (#6758): match+ # legacy-hash rows so a stale tracker is not left+ # is_downloaded=True while the document is PENDING.+ tracker = find_tracker_by_url(session, doc.original_url)if tracker:tracker.is_downloaded = Falsediff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.pyindex db9da835cd..8c18974cf9 100644--- a/src/local_deep_research/research_library/utils/__init__.py+++ b/src/local_deep_research/research_library/utils/__init__.py@@ -3,6 +3,7 @@import hashlibimport ipaddressimport os+import reimport socketimport subprocessimport sys@@ -255,6 +256,49 @@ def get_document_for_resource(session, resource):return session.query(Document).filter_by(resource_id=resource.id).first()+def normalize_url_for_hash(url: str) -> str:+ """Canonical normalization for URL-identity hashing (issue #6758 B2).++ Composes the shared :func:`canonical_url_key` (strips tracking query+ params, fragments, default ports, and userinfo; lowercases scheme and+ host) with the historical scheme/``www``/trailing-slash stripping,+ query-param sorting, and full lowercasing, so ``http`` vs ``https``,+ ``www`` variants, tracking-param decor, and param order all hash alike.++ Lowercasing happens BEFORE query-param sorting: ``sort(raw-case).lower()+ != sort(lower(raw))`` whenever mixed-case query keys change relative+ order (e.g. ``?q=x&Lang=fr&UserId=1``), and the tracker writer+ re-normalizes an already-lowercased string — sorting after lowering on+ one path but before lowering on the other yields different orders and+ different hashes (issue #6760 follow-up). Sorting the lowered form is+ deterministic on both paths and keeps the function idempotent.++ The ``canonical_url_key`` import is lazy: this module is imported at+ load time across the research-library stack, and a top-level import+ would hard-couple it to the utilities/security stack.+ """+ from ...utilities.url_utils import canonical_url_key++ try:+ normalized = canonical_url_key(url)+ except Exception:+ logger.warning("canonical_url_key failed, hashing raw URL")+ normalized = url if isinstance(url, str) else ""+ normalized = re.sub(r"^https?://", "", normalized or "")+ normalized = re.sub(r"^www\.", "", normalized)+ normalized = normalized.rstrip("/")+ # Lowercase first so the sort below is on the lowered form (see+ # docstring): otherwise mixed-case query keys sort differently before+ # vs after lowering and a double-normalized writer diverges from a+ # single-normalized reader.+ normalized = normalized.lower()+ if "?" in normalized:+ base, query = normalized.split("?", 1)+ params = sorted(query.split("&"))+ normalized = f"{base}?{'&'.join(params)}"+ return normalized++def get_url_hash(url: str) -> str:"""Generate a SHA256 hash of a URL.@@ -263,9 +307,120 @@ def get_url_hash(url: str) -> str:url: The URL to hashReturns:- The SHA256 hash of the URL+ The SHA256 hash of the canonical normalized URL (issue #6758 B2)+ """+ return hashlib.sha256(normalize_url_for_hash(url).encode()).hexdigest()+++def _legacy_normalize_download_service(url: str) -> str:+ """Pre-B2 (#6758) DownloadService._normalize_url spelling.++ Stripped scheme/``www``/trailing-slash, sorted raw ``&`` query pairs,+ lowercased — but did NOT strip tracking params, fragments, default+ ports, or userinfo. Rows written before B2 still carry this hash.+ """+ if not isinstance(url, str) or not url:+ return ""+ normalized = re.sub(r"^https?://", "", url)+ normalized = re.sub(r"^www\.", "", normalized)+ normalized = normalized.rstrip("/")+ if "?" in normalized:+ base, query = normalized.split("?", 1)+ params = sorted(query.split("&"))+ normalized = f"{base}?{'&'.join(params)}"+ return normalized.lower()+++def _legacy_normalize_library_service(url: str) -> str:+ """Pre-B2 (#6758) LibraryService._get_url_hash spelling.++ Same stripping as the download-service variant but WITHOUT query-param+ sorting. A separate candidate is required for multi-param URLs whose+ order differed.+ """+ if not isinstance(url, str) or not url:+ return ""+ normalized = re.sub(r"^https?://", "", url)+ normalized = re.sub(r"^www\.", "", normalized)+ normalized = normalized.rstrip("/")+ return normalized.lower()+++def get_legacy_url_hashes(url: str) -> list[str]:+ """Return pre-B2 (#6758) url_hash candidates for ``url``.++ Three legacy spellings existed in production:+ - raw ``sha256(url.lower())`` (cascade_helper looked up trackers with+ a bare ``get_url_hash`` that performed no stripping);+ - download-service normalized (scheme/``www``/trailing-slash strip ++ query sort);+ - library-service normalized (same strip, no sort).++ Used only as a read-compat fallback — new rows are always written with+ the canonical :func:`get_url_hash`. Callers must try the canonical hash+ first and fall back to these, never write them."""- return hashlib.sha256(url.lower().encode()).hexdigest()+ if not isinstance(url, str) or not url:+ return []+ candidates: list[str] = []+ raw_hash = hashlib.sha256(url.lower().encode()).hexdigest()+ candidates.append(raw_hash)+ dl_hash = hashlib.sha256(+ _legacy_normalize_download_service(url).encode()+ ).hexdigest()+ if dl_hash not in candidates:+ candidates.append(dl_hash)+ lib_hash = hashlib.sha256(+ _legacy_normalize_library_service(url).encode()+ ).hexdigest()+ if lib_hash not in candidates:+ candidates.append(lib_hash)+ return candidates+++def get_url_hash_candidates(url: str) -> list[str]:+ """Return ``[canonical, *legacy]`` url_hash candidates for ``url``.++ B2 (#6758) re-keys every URL that ``canonical_url_key`` mutates+ (tracking params, fragments, default ports, userinfo). Pre-upgrade+ ``download_tracker`` rows still carry a legacy hash, so a lookup by+ the canonical hash alone misses them — which previously drove+ duplicate tracker rows and, worse, ``sync_library_with_filesystem``'s+ "No tracker or path" branch deleting the document. Query+ ``DownloadTracker.url_hash.in_(candidates)`` (canonical first) to stay+ compatible with mixed-scheme tables without a data migration.+ """+ canonical = get_url_hash(url)+ out = [canonical]+ for legacy in get_legacy_url_hashes(url):+ if legacy != canonical and legacy not in out:+ out.append(legacy)+ return out+++def find_tracker_by_url(session, url: str):+ """Find a ``DownloadTracker`` for ``url`` across hash schemes.++ Tries the canonical B2 hash first, then the pre-B2 legacy spellings+ (see :func:`get_legacy_url_hashes`). Returns ``None`` when no row+ matches. Read-compat only — callers creating a tracker must still+ write the canonical hash.++ Implemented as sequential ``filter_by`` lookups (not a single+ ``IN``) so existing ``MagicMock`` tests that force+ ``filter_by(...).first() -> None`` keep forcing a miss on every+ candidate.+ """+ from ...database.models.download_tracker import DownloadTracker++ candidates = get_url_hash_candidates(url)+ for candidate in candidates:+ tracker = (+ session.query(DownloadTracker).filter_by(url_hash=candidate).first()+ )+ if tracker is not None:+ return tracker+ return Nonedef ensure_in_collection(diff --git a/src/local_deep_research/utilities/url_utils.py b/src/local_deep_research/utilities/url_utils.pyindex ea79ff672c..87adea8a22 100644--- a/src/local_deep_research/utilities/url_utils.py+++ b/src/local_deep_research/utilities/url_utils.py@@ -3,7 +3,7 @@from functools import lru_cachefrom typing import Optionalimport re-from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit+from urllib.parse import unquote, urlsplit, urlunsplitfrom loguru import logger@@ -430,8 +430,12 @@ def canonical_url_key(url: str) -> str:Click-through behavior is preserved — tracking params carry nocontent, and mainstream browsers already strip them automatically.- Percent-encoding is not normalized; query param order is preserved- as-is.+ Percent-encoding is not normalized: the raw query spellings+ ``?q=a+b`` vs ``?q=a%20b`` and ``?a=1;b=2`` vs ``?a=1%3Bb=2`` hash+ differently (a server may treat ``+``/``;`` literally, so merging+ them would risk linking a resource to the wrong document). Query+ param order is preserved as-is here; callers that need+ order-insensitivity (e.g. download-tracker hashing) sort afterwards.Internal library-document routes (``/library/document/<id>``, plus its``/pdf`` and ``/chunks#chunk-<n>`` views) collapse to a per-document@@ -515,18 +519,29 @@ def canonical_url_key(url: str) -> str:port = ""netloc = f"{host}:{port}" if port else host- # Filter query params case-insensitively on key; preserve order/values.+ # Filter query params case-insensitively on key; preserve raw+ # spellings and order. Operates on the raw ``&``-split pairs (no+ # parse_qsl/urlencode round-trip): decoding would merge spellings the+ # tracker must keep distinct (``+`` vs ``%20``, ``;`` vs ``%3B`` —+ # issue #6758 B2 review). Tracking detection decodes the key with+ # ``unquote`` (``%`` only, ``+`` left intact) so an encoded tracking+ # key is still stripped, but the kept pairs are re-emitted verbatim.if parsed.query:- pairs = parse_qsl(parsed.query, keep_blank_values=True)- kept = [- (k, v)- for k, v in pairs- if not (- k.lower() in _TRACKING_PARAMS- or any(k.lower().startswith(p) for p in _TRACKING_PREFIXES)- )- ]- query_str = urlencode(kept, doseq=True) if kept else ""+ kept_raw: list[str] = []+ for raw_pair in parsed.query.split("&"):+ if raw_pair == "":+ continue+ raw_key = raw_pair.split("=", 1)[0]+ try:+ decoded_key = unquote(raw_key).lower()+ except Exception:+ decoded_key = raw_key.lower()+ if decoded_key in _TRACKING_PARAMS or any(+ decoded_key.startswith(p) for p in _TRACKING_PREFIXES+ ):+ continue+ kept_raw.append(raw_pair)+ query_str = "&".join(kept_raw)else:query_str = ""diff --git a/tests/research_library/services/test_download_service_3827_fix.py b/tests/research_library/services/test_download_service_3827_fix.pyindex e0adab71f7..bf85c5285a 100644--- a/tests/research_library/services/test_download_service_3827_fix.py+++ b/tests/research_library/services/test_download_service_3827_fix.py@@ -35,9 +35,11 @@ from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.orm import sessionmakerfrom local_deep_research.database.models import Base+from local_deep_research.database.models.download_tracker import DownloadTrackerfrom local_deep_research.database.models.library import (Collection,Document,+ DocumentCollection,DocumentStatus,SourceType,)@@ -1068,6 +1070,929 @@ def test_process_user_documents_no_longer_indexes_rag_inline():mock_session.assert_not_called()+# ---------------------------------------------------------------------------+# Issue #6758, B1: the PDF research-download path had no content-hash+# pre-check. Two different URLs yielding identical PDF bytes went straight to+# INSERT and relied on UNIQUE(document_hash) -> IntegrityError ->+# safe_rollback, leaving the second resource document-less (re-downloadable,+# reads as "dedup did nothing"). The fix mirrors the text-path pre-check+# above: query Document(document_hash=file_hash) before INSERT and, on a hit,+# link resource.document_id (+ ensure_in_collection) instead of inserting.+# ---------------------------------------------------------------------------+++def test_pdf_path_dedups_identical_bytes_across_different_urls(+ session, source_type, library_collection, make_resource, svc+):+ """Two resources with different URLs but byte-identical PDFs share one+ Document; the second resource links to it instead of INSERTing.+ """+ res_a = make_resource("https://example.com/paper-A.pdf")+ res_b = make_resource("https://mirror.example.org/paper-B.pdf")+ pdf_content = b"%PDF-1.4 identical bytes served from two different URLs"+ file_hash = hashlib.sha256(pdf_content).hexdigest()++ # Wire the svc stub for the success path: server-side settings with+ # storage "none" (no filesystem writes), an open egress gate, and one+ # downloader serving identical bytes for both URLs.+ svc.library_root = "/tmp/ldr-test-library"+ svc.legacy_library_root = "/tmp/ldr-test-library"+ svc.settings = MagicMock()+ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ svc._check_url_against_policy = lambda url: (True, "ok") # noqa: E731+ downloader = MagicMock()+ downloader.can_handle.return_value = True+ downloader.download_with_result.return_value = MagicMock(+ is_success=True,+ content=pdf_content,+ status_code=200,+ skip_reason=None,+ )+ svc.downloaders = [downloader]++ tracker_a = DownloadTracker(+ url=res_a.url,+ url_hash="hash-6758-B1-A",+ first_resource_id=res_a.id,+ is_downloaded=False,+ )+ tracker_b = DownloadTracker(+ url=res_b.url,+ url_hash="hash-6758-B1-B",+ first_resource_id=res_b.id,+ is_downloaded=False,+ )+ session.add_all([tracker_a, tracker_b])+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library_collection.id,+ ),+ ):+ success_a, _, _ = svc._download_pdf(res_a, tracker_a, session)+ session.commit()+ success_b, _, _ = svc._download_pdf(res_b, tracker_b, session)+ session.commit()++ assert success_a is True+ assert success_b is True++ # Pre-fix the second INSERT raised IntegrityError (UNIQUE document_hash)+ # and rolled back; with the fix exactly one Document exists.+ docs = session.query(Document).filter_by(document_hash=file_hash).all()+ assert len(docs) == 1, (+ f"B1 dedup should have produced exactly one Document, got {len(docs)}"+ )+ canonical = docs[0]+ assert canonical.file_type == "pdf"++ session.refresh(res_b)+ assert res_b.document_id == canonical.id, (+ "Second resource should be linked to the canonical Document."+ )++ links = (+ session.query(DocumentCollection)+ .filter_by(+ document_id=canonical.id, collection_id=library_collection.id+ )+ .all()+ )+ assert len(links) == 1, (+ "Canonical document must be linked to the Library collection "+ "exactly once."+ )+++def test_pdf_path_still_inserts_for_distinct_bytes(+ session, source_type, library_collection, make_resource, svc+):+ """Guard against an over-eager dedup: different PDF bytes still produce+ distinct Documents (the pre-check must only fire on hash equality).+ """+ res_a = make_resource("https://example.com/unique-A.pdf")+ res_b = make_resource("https://example.com/unique-B.pdf")+ pdf_a = b"%PDF-1.4 unique bytes A"+ pdf_b = b"%PDF-1.4 unique bytes B"++ svc.library_root = "/tmp/ldr-test-library"+ svc.legacy_library_root = "/tmp/ldr-test-library"+ svc.settings = MagicMock()+ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ svc._check_url_against_policy = lambda url: (True, "ok") # noqa: E731+ downloader = MagicMock()+ downloader.can_handle.return_value = True+ downloader.download_with_result.side_effect = [+ MagicMock(+ is_success=True,+ content=pdf_a,+ status_code=200,+ skip_reason=None,+ ),+ MagicMock(+ is_success=True,+ content=pdf_b,+ status_code=200,+ skip_reason=None,+ ),+ ]+ svc.downloaders = [downloader]++ tracker_a = DownloadTracker(+ url=res_a.url,+ url_hash="hash-6758-B1-distinct-A",+ first_resource_id=res_a.id,+ is_downloaded=False,+ )+ tracker_b = DownloadTracker(+ url=res_b.url,+ url_hash="hash-6758-B1-distinct-B",+ first_resource_id=res_b.id,+ is_downloaded=False,+ )+ session.add_all([tracker_a, tracker_b])+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library_collection.id,+ ),+ ):+ success_a, _, _ = svc._download_pdf(res_a, tracker_a, session)+ session.commit()+ success_b, _, _ = svc._download_pdf(res_b, tracker_b, session)+ session.commit()++ assert success_a is True+ assert success_b is True+ assert session.query(Document).count() == 2+ session.refresh(res_a)+ session.refresh(res_b)+ assert res_a.document_id is None+ assert res_b.document_id is None+++# ---------------------------------------------------------------------------+# Issue #6758 follow-up: storage upgrade on the content-hash hit path.+# First download with storage "none", then identical bytes with storage+# "database" — the canonical Document must gain a blob instead of staying+# storage_mode="none" with no saved PDF, and both trackers must agree.+# ---------------------------------------------------------------------------+++def test_pdf_dedup_upgrades_storage_from_none_to_database(+ session, source_type, library_collection, make_resource, svc+):+ """Reproduces the AI-review failure: none → database must upgrade."""+ from local_deep_research.database.models.library import DocumentBlob++ res_a = make_resource("https://example.com/storage-A.pdf")+ res_b = make_resource("https://mirror.example.org/storage-B.pdf")+ pdf_content = b"%PDF-1.4 identical bytes for storage-upgrade test"+ file_hash = hashlib.sha256(pdf_content).hexdigest()++ svc.library_root = "/tmp/ldr-test-library"+ svc.legacy_library_root = "/tmp/ldr-test-library"+ svc.settings = MagicMock()+ # Mutable mode so the first call stores nothing and the second stores.+ current_mode = {"mode": "none"}+ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": current_mode["mode"],+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ svc._check_url_against_policy = lambda url: (True, "ok") # noqa: E731+ downloader = MagicMock()+ downloader.can_handle.return_value = True+ downloader.download_with_result.return_value = MagicMock(+ is_success=True,+ content=pdf_content,+ status_code=200,+ skip_reason=None,+ )+ svc.downloaders = [downloader]++ tracker_a = DownloadTracker(+ url=res_a.url,+ url_hash="hash-6758-storage-A",+ first_resource_id=res_a.id,+ is_downloaded=False,+ )+ tracker_b = DownloadTracker(+ url=res_b.url,+ url_hash="hash-6758-storage-B",+ first_resource_id=res_b.id,+ is_downloaded=False,+ )+ session.add_all([tracker_a, tracker_b])+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library_collection.id,+ ),+ ):+ success_a, _, _ = svc._download_pdf(res_a, tracker_a, session)+ session.commit()+ # Canonical is storage-mode none with no blob and no path.+ canonical = (+ session.query(Document).filter_by(document_hash=file_hash).one()+ )+ assert canonical.storage_mode == "none"+ assert (+ session.query(DocumentBlob)+ .filter_by(document_id=canonical.id)+ .first()+ is None+ )+ assert tracker_a.file_path is None++ current_mode["mode"] = "database"+ success_b, _, _ = svc._download_pdf(res_b, tracker_b, session)+ session.commit()++ assert success_a is True+ assert success_b is True+ session.refresh(canonical)+ # Upgraded: blob present, mode flipped, second tracker consistent.+ assert canonical.storage_mode == "database"+ assert (+ session.query(DocumentBlob).filter_by(document_id=canonical.id).first()+ is not None+ )+ session.refresh(tracker_b)+ assert tracker_b.file_path == "database"+ assert tracker_b.file_name is None+ # Sibling (first) tracker was backfilled so sync still finds the doc.+ session.refresh(tracker_a)+ assert tracker_a.file_path == "database"+ session.refresh(res_b)+ assert res_b.document_id == canonical.id+ # Still exactly one Document — upgrade, not duplicate.+ assert (+ session.query(Document).filter_by(document_hash=file_hash).count() == 1+ )+++def test_pdf_dedup_preserves_existing_database_storage(+ session, source_type, library_collection, make_resource, svc+):+ """First database, second none — must NOT downgrade the canonical."""+ from local_deep_research.database.models.library import DocumentBlob++ res_a = make_resource("https://example.com/preserve-A.pdf")+ res_b = make_resource("https://mirror.example.org/preserve-B.pdf")+ pdf_content = b"%PDF-1.4 identical bytes for preserve test"++ svc.library_root = "/tmp/ldr-test-library"+ svc.legacy_library_root = "/tmp/ldr-test-library"+ svc.settings = MagicMock()+ current_mode = {"mode": "database"}+ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": current_mode["mode"],+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ svc._check_url_against_policy = lambda url: (True, "ok") # noqa: E731+ downloader = MagicMock()+ downloader.can_handle.return_value = True+ downloader.download_with_result.return_value = MagicMock(+ is_success=True,+ content=pdf_content,+ status_code=200,+ skip_reason=None,+ )+ svc.downloaders = [downloader]++ tracker_a = DownloadTracker(+ url=res_a.url,+ url_hash="hash-6758-preserve-A",+ first_resource_id=res_a.id,+ is_downloaded=False,+ )+ tracker_b = DownloadTracker(+ url=res_b.url,+ url_hash="hash-6758-preserve-B",+ first_resource_id=res_b.id,+ is_downloaded=False,+ )+ session.add_all([tracker_a, tracker_b])+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library_collection.id,+ ),+ ):+ success_a, _, _ = svc._download_pdf(res_a, tracker_a, session)+ session.commit()+ file_hash = hashlib.sha256(pdf_content).hexdigest()+ canonical = (+ session.query(Document).filter_by(document_hash=file_hash).one()+ )+ assert canonical.storage_mode == "database"++ current_mode["mode"] = "none"+ success_b, _, _ = svc._download_pdf(res_b, tracker_b, session)+ session.commit()++ assert success_a is True+ assert success_b is True+ session.refresh(canonical)+ assert canonical.storage_mode == "database"+ assert (+ session.query(DocumentBlob).filter_by(document_id=canonical.id).first()+ is not None+ )+ session.refresh(tracker_b)+ # Second tracker mirrors the canonical's database storage.+ assert tracker_b.file_path == "database"+++# ---------------------------------------------------------------------------+# Issue #6758 follow-up: dedup link must still auto-index in the requested+# collection. The old download_resource lookup (Document.resource_id ==+# resource.id) misses the reused canonical (owned by another resource), so+# trigger_auto_index was skipped for duplicates queued elsewhere.+# ---------------------------------------------------------------------------+++def test_pdf_dedup_resolves_for_auto_index_in_different_collection(+ session, source_type, library_collection, make_resource, svc+):+ """Identical bytes under a second resource into a different collection+ must resolve to the canonical Document (old resource_id-only lookup+ returned None and skipped indexing)."""+ from local_deep_research.research_library.utils import (+ get_document_for_resource,+ )++ second_collection = Collection(+ id=str(uuid.uuid4()),+ name="Second",+ is_default=False,+ collection_type="user",+ )+ session.add(second_collection)+ session.commit()++ res_a = make_resource("https://example.com/index-A.pdf")+ res_b = make_resource("https://mirror.example.org/index-B.pdf")+ pdf_content = b"%PDF-1.4 identical bytes for auto-index test"++ svc.library_root = "/tmp/ldr-test-library"+ svc.legacy_library_root = "/tmp/ldr-test-library"+ svc.settings = MagicMock()+ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ svc._check_url_against_policy = lambda url: (True, "ok") # noqa: E731+ downloader = MagicMock()+ downloader.can_handle.return_value = True+ downloader.download_with_result.return_value = MagicMock(+ is_success=True,+ content=pdf_content,+ status_code=200,+ skip_reason=None,+ )+ svc.downloaders = [downloader]++ tracker_a = DownloadTracker(+ url=res_a.url,+ url_hash="hash-6758-index-A",+ first_resource_id=res_a.id,+ is_downloaded=False,+ )+ tracker_b = DownloadTracker(+ url=res_b.url,+ url_hash="hash-6758-index-B",+ first_resource_id=res_b.id,+ is_downloaded=False,+ )+ session.add_all([tracker_a, tracker_b])+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library_collection.id,+ ),+ ):+ svc._download_pdf(res_a, tracker_a, session)+ session.commit()+ # Second resource explicitly queued into the other collection.+ svc._download_pdf(+ res_b, tracker_b, session, collection_id=second_collection.id+ )+ session.commit()++ session.refresh(res_b)+ assert res_b.document_id is not None+ # Old lookup misses (canonical owned by res_a).+ old_lookup = session.query(Document).filter_by(resource_id=res_b.id).first()+ assert old_lookup is None+ # Helper used by the fixed download_resource finds the canonical.+ resolved = get_document_for_resource(session, res_b)+ assert resolved is not None+ assert resolved.id == res_b.document_id+ # Canonical linked into the requested (different) collection.+ link = (+ session.query(DocumentCollection)+ .filter_by(document_id=resolved.id, collection_id=second_collection.id)+ .first()+ )+ assert link is not None+++# ---------------------------------------------------------------------------+# Issue #6758 B2: legacy url_hash rows must still match post-upgrade lookups.+# Seeds pre-B2 spellings and asserts the compat path finds them.+# ---------------------------------------------------------------------------+++def test_legacy_url_hash_rows_still_matched(session, make_resource):+ """Mixed-scheme production state: old rows found by new lookups."""+ from local_deep_research.research_library.utils import (+ find_tracker_by_url,+ get_legacy_url_hashes,+ get_url_hash,+ get_url_hash_candidates,+ )++ # URL shapes that B2 re-keys (tracking params, fragment, default port,+ # userinfo) — plain URLs keep their hash and are covered elsewhere.+ urls = [+ "https://example.com/paper?utm_source=newsletter",+ "https://example.com/paper#section-2",+ "https://example.com:443/paper",+ "https://user:[email protected]/paper",+ "https://example.com/s?z=1&a=2",+ ]+ for i, url in enumerate(urls):+ res = make_resource(f"https://seed.example/{i}")+ new_hash = get_url_hash(url)+ legacy_hashes = get_legacy_url_hashes(url)+ # At least one legacy spelling must diverge, otherwise this URL+ # does not exercise the mixed-scheme path.+ assert any(h != new_hash for h in legacy_hashes), url+ assert new_hash in get_url_hash_candidates(url)+ for legacy in legacy_hashes:+ assert legacy in get_url_hash_candidates(url)++ # Seed the download-service legacy spelling (the most common+ # pre-B2 writer) and verify the compat lookup finds it.+ import re as _re++ legacy_dl = _re.sub(r"^https?://", "", url)+ legacy_dl = _re.sub(r"^www\.", "", legacy_dl).rstrip("/")+ if "?" in legacy_dl:+ base, query = legacy_dl.split("?", 1)+ legacy_dl = f"{base}?{'&'.join(sorted(query.split('&')))}"+ legacy_dl_hash = hashlib.sha256(legacy_dl.lower().encode()).hexdigest()++ tracker = DownloadTracker(+ url=url,+ url_hash=legacy_dl_hash,+ first_resource_id=res.id,+ is_downloaded=True,+ file_path="pdfs/legacy.pdf",+ )+ session.add(tracker)+ session.commit()++ found = find_tracker_by_url(session, url)+ assert found is not None, f"legacy row missed for {url}"+ assert found.id == tracker.id++ # Raw-legacy spelling (cascade_helper's old bare-hash writer) also+ # resolves when seeded instead.+ session.delete(found)+ session.commit()+ raw_hash = hashlib.sha256(url.lower().encode()).hexdigest()+ tracker2 = DownloadTracker(+ url=url,+ url_hash=raw_hash,+ first_resource_id=res.id,+ is_downloaded=True,+ file_path="pdfs/legacy.pdf",+ )+ session.add(tracker2)+ session.commit()+ found2 = find_tracker_by_url(session, url)+ assert found2 is not None, f"raw legacy row missed for {url}"+ assert found2.id == tracker2.id+ session.delete(found2)+ session.commit()+++# ---------------------------------------------------------------------------+# Minor: new failure branches need coverage — dedup-path collection-lookup+# fallback and canonical_url_key exception fallback.+# ---------------------------------------------------------------------------+++def test_pdf_dedup_links_without_collection_on_lookup_failure(+ session, source_type, library_collection, make_resource, svc+):+ """When get_default_library_id raises on the dedup path, the resource+ still links to the canonical Document (collection link skipped)."""+ res_a = make_resource("https://example.com/fallback-A.pdf")+ res_b = make_resource("https://mirror.example.org/fallback-B.pdf")+ pdf_content = b"%PDF-1.4 identical bytes for fallback test"+ file_hash = hashlib.sha256(pdf_content).hexdigest()++ svc.library_root = "/tmp/ldr-test-library"+ svc.legacy_library_root = "/tmp/ldr-test-library"+ svc.settings = MagicMock()+ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ svc._check_url_against_policy = lambda url: (True, "ok") # noqa: E731+ downloader = MagicMock()+ downloader.can_handle.return_value = True+ downloader.download_with_result.return_value = MagicMock(+ is_success=True,+ content=pdf_content,+ status_code=200,+ skip_reason=None,+ )+ svc.downloaders = [downloader]++ tracker_a = DownloadTracker(+ url=res_a.url,+ url_hash="hash-6758-fallback-A",+ first_resource_id=res_a.id,+ is_downloaded=False,+ )+ tracker_b = DownloadTracker(+ url=res_b.url,+ url_hash="hash-6758-fallback-B",+ first_resource_id=res_b.id,+ is_downloaded=False,+ )+ session.add_all([tracker_a, tracker_b])+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library_collection.id,+ ),+ ):+ svc._download_pdf(res_a, tracker_a, session)+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ side_effect=RuntimeError("library lookup down"),+ ),+ ):+ success_b, _, _ = svc._download_pdf(res_b, tracker_b, session)+ session.commit()++ assert success_b is True+ canonical = session.query(Document).filter_by(document_hash=file_hash).one()+ session.refresh(res_b)+ assert res_b.document_id == canonical.id+++def test_normalize_url_for_hash_falls_back_on_canonical_failure():+ """canonical_url_key raising must not break hashing (raw fallback)."""+ from local_deep_research.research_library import utils as utils_mod++ # canonical_url_key is lazily imported inside normalize_url_for_hash+ # from utilities.url_utils, so patch it at the source.+ with patch(+ "local_deep_research.utilities.url_utils.canonical_url_key",+ side_effect=RuntimeError("boom"),+ ):+ result = utils_mod.normalize_url_for_hash(+ "https://example.com/fallback-unique-6758?b=2&a=1"+ )+ # Falls back to raw URL, then legacy strip/sort/lower.+ assert result == "example.com/fallback-unique-6758?a=1&b=2"+ hashed = utils_mod.get_url_hash(+ "https://example.com/fallback-unique-6758b"+ )+ assert len(hashed) == 64+++# ---------------------------------------------------------------------------+# Minor: same URL serving updated bytes must not collapse to one Document.+# ---------------------------------------------------------------------------+++def test_same_url_updated_bytes_creates_new_document(+ session, source_type, library_collection, make_resource, svc+):+ """Same URL, different bytes (server updated file) → new Document.++ Guards against an over-eager content-hash dedup that would link the+ second download to the stale canonical instead of inserting.+ """+ # Two resources sharing one URL (e.g. two researches citing it) whose+ # server bytes change between downloads.+ res_a = make_resource("https://example.com/evolving.pdf")+ res_b = make_resource("https://example.com/evolving.pdf")+ pdf_a = b"%PDF-1.4 version one bytes"+ pdf_b = b"%PDF-1.4 version two bytes - updated on server"+ assert (+ hashlib.sha256(pdf_a).hexdigest() != hashlib.sha256(pdf_b).hexdigest()+ )++ svc.library_root = "/tmp/ldr-test-library"+ svc.legacy_library_root = "/tmp/ldr-test-library"+ svc.settings = MagicMock()+ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ svc._check_url_against_policy = lambda url: (True, "ok") # noqa: E731+ downloader = MagicMock()+ downloader.can_handle.return_value = True+ downloader.download_with_result.side_effect = [+ MagicMock(+ is_success=True, content=pdf_a, status_code=200, skip_reason=None+ ),+ MagicMock(+ is_success=True, content=pdf_b, status_code=200, skip_reason=None+ ),+ ]+ svc.downloaders = [downloader]++ tracker_a = DownloadTracker(+ url=res_a.url,+ url_hash="hash-6758-evolving-A",+ first_resource_id=res_a.id,+ is_downloaded=False,+ )+ tracker_b = DownloadTracker(+ url=res_b.url,+ url_hash="hash-6758-evolving-B",+ first_resource_id=res_b.id,+ is_downloaded=False,+ )+ session.add_all([tracker_a, tracker_b])+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library_collection.id,+ ),+ ):+ success_a, _, _ = svc._download_pdf(res_a, tracker_a, session)+ session.commit()+ success_b, _, _ = svc._download_pdf(res_b, tracker_b, session)+ session.commit()++ assert success_a is True+ assert success_b is True+ # Different bytes → two Documents, second not linked to first.+ assert session.query(Document).count() == 2+ session.refresh(res_b)+ first_doc = (+ session.query(Document)+ .filter_by(document_hash=hashlib.sha256(pdf_a).hexdigest())+ .one()+ )+ second_doc = (+ session.query(Document)+ .filter_by(document_hash=hashlib.sha256(pdf_b).hexdigest())+ .one()+ )+ assert first_doc.id != second_doc.id+ assert res_b.document_id is None+++# ---------------------------------------------------------------------------+# Issue #6760 follow-up blocker 1: tracker writer and readers must agree on+# mixed-case query URLs. The writer double-normalized+# (``_normalize_url(canonical(url))`` then ``get_url_hash``, i.e.+# sort(raw-case).lower() followed by a second sort(lower)), while the+# readers normalize once — so ``sort(raw).lower() != sort(lower(raw))``+# whenever mixed-case keys change relative order. The writer hash landed in+# none of the four reader candidates: sync then ran+# ``delete_document_completely`` on an intact document, and re-download+# INSERTed a duplicate tracker → ``IntegrityError`` on+# ``uq_download_tracker_url_hash`` (URL bricked).+# ---------------------------------------------------------------------------+++def test_writer_hash_in_candidates_mixed_case_battery(svc):+ """The actual writer hash must be a reader candidate (mixed-case URLs).++ Uses ``DownloadService._get_url_hash`` (the production writer), not the+ reader spelling — the previous compat test built expectations with the+ reader and could not catch the divergence.+ """+ from local_deep_research.research_library.utils import (+ get_url_hash_candidates,+ )++ urls = [+ # Exact shapes from the follow-up review.+ "https://example.com/paper.pdf?q=x&Lang=fr&UserId=1",+ "https://example.com/p?a=1&Z=2&utm_source=twitter",+ "https://example.com/p?a=1&Z=2#frag",+ # Extra mixed-case / order permutations.+ "https://example.com/p?Z=2&a=1",+ "https://example.com/p?A=1&b=2&C=3",+ "HTTPS://EXAMPLE.COM/Paper.PDF?Q=X&LANG=FR",+ "https://example.com/p?UserId=1&q=x&Lang=fr",+ ]+ for url in urls:+ writer = svc._get_url_hash(url)+ assert writer in get_url_hash_candidates(url), url++ # Mixed-case order-insensitivity still holds through the writer.+ assert svc._get_url_hash(+ "https://example.com/p?a=1&Z=2"+ ) == svc._get_url_hash("https://example.com/p?Z=2&a=1")+++# ---------------------------------------------------------------------------+# Issue #6760 follow-up blocker 2: the dedup mirror must not copy+# file_path sentinels, and sync must not delete documents behind one.+#+# Chain: database-mode PDF → blob purged (``file_path="blob_deleted"``,+# storage ``none``, document stays complete) → identical bytes arrive from+# a second URL with the default ``none`` mode → no upgrade → the+# ``"blob_deleted"`` sentinel was mirrored verbatim into the duplicate+# tracker → sync's mid-branch (which only accepted ``== "database"`` as+# blob-backed) fell to the file-exists check, always missed, and ran+# ``delete_document_completely`` on the text/chunks/vectors the purge+# deliberately preserved.+# ---------------------------------------------------------------------------+++def test_pdf_dedup_does_not_mirror_blob_deleted_sentinel(+ session, source_type, library_collection, make_resource, svc+):+ """Post-purge canonical + identical bytes elsewhere → path-less tracker."""+ from local_deep_research.constants import FILE_PATH_BLOB_DELETED++ res_a = make_resource("https://example.com/purged-A.pdf")+ res_b = make_resource("https://mirror.example.org/purged-B.pdf")+ pdf_content = b"%PDF-1.4 identical bytes for sentinel-mirror test"+ file_hash = hashlib.sha256(pdf_content).hexdigest()++ # Canonical in its post-blob-purge state: complete document, storage+ # none, sentinel file_path (see document_deletion blob-purge path).+ canonical = Document(+ id=str(uuid.uuid4()),+ source_type_id=source_type.id,+ resource_id=res_a.id,+ research_id=res_a.research_id,+ document_hash=file_hash,+ original_url=res_a.url,+ file_size=len(pdf_content),+ file_type="pdf",+ title=res_a.title,+ status=DocumentStatus.COMPLETED,+ storage_mode="none",+ file_path=FILE_PATH_BLOB_DELETED,+ )+ session.add(canonical)+ session.commit()++ svc.library_root = "/tmp/ldr-test-library"+ svc.legacy_library_root = "/tmp/ldr-test-library"+ svc.settings = MagicMock()+ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ svc._check_url_against_policy = lambda url: (True, "ok") # noqa: E731+ downloader = MagicMock()+ downloader.can_handle.return_value = True+ downloader.download_with_result.return_value = MagicMock(+ is_success=True,+ content=pdf_content,+ status_code=200,+ skip_reason=None,+ )+ svc.downloaders = [downloader]++ tracker_b = DownloadTracker(+ url=res_b.url,+ url_hash="hash-6760-sentinel-B",+ first_resource_id=res_b.id,+ is_downloaded=False,+ )+ session.add(tracker_b)+ session.commit()++ with (+ patch(f"{MODULE}.get_source_type_id", return_value=source_type.id),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library_collection.id,+ ),+ ):+ success_b, _, _ = svc._download_pdf(res_b, tracker_b, session)+ session.commit()++ assert success_b is True+ session.refresh(tracker_b)+ session.refresh(canonical)+ # Linked to the canonical — not a duplicate Document.+ session.refresh(res_b)+ assert res_b.document_id == canonical.id+ assert (+ session.query(Document).filter_by(document_hash=file_hash).count() == 1+ )+ # The sentinel must NOT be mirrored: the duplicate tracker stays+ # path-less (same shape as a fresh none-mode download).+ assert tracker_b.file_path is None+ assert tracker_b.file_name is None+ # Canonical untouched (no downgrade, sentinel preserved on the doc).+ assert canonical.file_path == FILE_PATH_BLOB_DELETED+ assert canonical.storage_mode == "none"+++def test_sync_leaves_sentinel_tracker_path_alone(mocker):+ """Sync mid-branch: a sentinel tracker path counts as found, no delete."""+ from contextlib import contextmanager+ from unittest.mock import Mock++ from local_deep_research.constants import FILE_PATH_BLOB_DELETED+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ with patch.object(LibraryService, "__init__", lambda self, username: None):+ service = LibraryService.__new__(LibraryService)+ service.username = "test_user"++ mock_doc = Mock()+ mock_doc.id = "doc-sentinel-1"+ mock_doc.title = "Purged Doc"+ mock_doc.original_url = "https://example.com/purged-A.pdf"+ mock_doc.storage_mode = "none"+ mock_doc.file_path = FILE_PATH_BLOB_DELETED++ mock_tracker = Mock()+ mock_tracker.file_path = FILE_PATH_BLOB_DELETED+ mock_tracker.is_downloaded = True++ mock_session = MagicMock()+ docs_q = MagicMock()+ docs_q.filter_by.return_value.filter.return_value.options.return_value.all.return_value = [+ mock_doc+ ]++ def _query_router(model):+ name = getattr(model, "__name__", str(model))+ if "Document" in name and "Blob" not in name:+ return docs_q+ return MagicMock()++ mock_session.query.side_effect = _query_router++ @contextmanager+ def _cm(username, password=None):+ yield mock_session++ mocker.patch(+ "local_deep_research.research_library.services.library_service.get_user_db_session",+ side_effect=_cm,+ )+ mocker.patch(+ "local_deep_research.research_library.services.library_service.find_tracker_by_url",+ return_value=mock_tracker,+ )+ delete_mock = mocker.patch(+ "local_deep_research.research_library.deletion.utils.cascade_helper.CascadeHelper.delete_document_completely"+ )++ stats = service.sync_library_with_filesystem()++ assert stats["files_found"] == 1+ assert stats["files_missing"] == 0+ delete_mock.assert_not_called()++# ---------------------------------------------------------------------------# Real-machinery contention test (reviewer ask #1 from PR #6720):# ---------------------------------------------------------------------------diff --git a/tests/research_library/services/test_download_service_arxiv_provenance.py b/tests/research_library/services/test_download_service_arxiv_provenance.pyindex 427b74c15e..293262e2e0 100644--- a/tests/research_library/services/test_download_service_arxiv_provenance.py+++ b/tests/research_library/services/test_download_service_arxiv_provenance.py@@ -87,6 +87,11 @@ def test_pdf_download_path_persists_typed_arxiv_origin(tracker.url_hash = "typed-provenance"tracker.download_attempts.count.return_value = 0session = MagicMock()+ # B1 (#6758): _download_pdf now pre-checks Document(document_hash)+ # before INSERT. Default MagicMock query chains are truthy, which would+ # take the dedup-link branch and skip save_pdf; force a miss so this+ # test exercises the new-document path it intends.+ session.query.return_value.filter_by.return_value.first.return_value = Nonearxiv = MagicMock(spec=ArxivDownloader)arxiv.can_handle.return_value = Truediff --git a/tests/research_library/services/test_download_service_coverage.py b/tests/research_library/services/test_download_service_coverage.pyindex e674c7e605..e6cf0fd537 100644--- a/tests/research_library/services/test_download_service_coverage.py+++ b/tests/research_library/services/test_download_service_coverage.py@@ -115,9 +115,15 @@ class TestNormalizeUrl:class TestGetUrlHash:def test_returns_hash(self, svc):+ from local_deep_research.utilities.url_utils import canonical_url_key+with patch(f"{MODULE}.get_url_hash", return_value="hash123") as m:result = svc._get_url_hash("https://www.example.com/page")- m.assert_called_once_with("example.com/page")+ # Writer passes the canonical form straight into get_url_hash+ # (no _normalize_url intermediate — issue #6760 follow-up).+ m.assert_called_once_with(+ canonical_url_key("https://www.example.com/page")+ )assert result == "hash123"def test_equivalent_urls_same_hash(self, svc):diff --git a/tests/research_library/services/test_download_service_deep_coverage.py b/tests/research_library/services/test_download_service_deep_coverage.pyindex 779bf62403..e872b2249d 100644--- a/tests/research_library/services/test_download_service_deep_coverage.py+++ b/tests/research_library/services/test_download_service_deep_coverage.py@@ -306,6 +306,13 @@ class TestDownloadPdfDeep:# Given a fresh arXiv PDF download and observable storage/text seamssession = MagicMock()+ # B1 (#6758): _download_pdf now pre-checks Document(document_hash)+ # before INSERT. Default MagicMock query chains are truthy, which+ # would take the dedup-link branch; force a miss so this test+ # exercises the new-document path it intends.+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )resource = MagicMock()resource.id = 11resource.url = "https://arxiv.org/abs/1234"@@ -422,6 +429,11 @@ class TestDownloadPdfDeep:def test_source_type_exception_propagates(self, svc):"""Exception from get_source_type_id is re-raised."""session = MagicMock()+ # B1 (#6758): force the content-hash pre-check to miss so the test+ # reaches the get_source_type_id call it intends to exercise.+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )resource = MagicMock()resource.id = 12resource.url = "https://example.com/p.pdf"diff --git a/tests/research_library/services/test_download_service_strategy_coverage.py b/tests/research_library/services/test_download_service_strategy_coverage.pyindex 5429ba97e6..cff6e71b7d 100644--- a/tests/research_library/services/test_download_service_strategy_coverage.py+++ b/tests/research_library/services/test_download_service_strategy_coverage.py@@ -437,6 +437,13 @@ class TestDownloadResourceGenericFallback:tracker.download_attempts.count.return_value = 0session = MagicMock()+ # B1 (#6758): _download_pdf now pre-checks Document(document_hash)+ # before INSERT. Default MagicMock query chains are truthy, which+ # would take the dedup-link branch and skip save_pdf; force a miss+ # so this test exercises the new-document path it intends.+ session.query.return_value.filter_by.return_value.first.return_value = (+ None+ )mock_psm = MagicMock()mock_psm.save_pdf.return_value = (None, None)stored_pdf_doc = MagicMock()@@ -998,12 +1005,14 @@ class TestRetryFailedDownload:session.get.return_value = resourcequeue_entry = MagicMock()- # Sequence: existing_doc=None, pre-download queue_entry=None, tracker=None,- # post-download queue_entry=queue_entry+ # Sequence with B2 compat (#6758): existing_doc=None,+ # pre-download queue_entry=None, post-download queue_entry.+ # Tracker lookup is via find_tracker_by_url (mocked to miss) and+ # auto-index resolution via get_document_for_resource (mocked to+ # miss) so no filter_by side_effects are consumed there.session.query.return_value.filter_by.return_value.first.side_effect = [None, # existing_docNone, # pre-download queue_entry- None, # trackerqueue_entry, # post-download queue_entry]session.query.return_value.filter_by.return_value.order_by.return_value.first.return_value = None@@ -1015,6 +1024,8 @@ class TestRetryFailedDownload:f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),patch.object(svc, "_get_url_hash", return_value="hash_q"),+ patch(f"{MODULE}.find_tracker_by_url", return_value=None),+ patch(f"{MODULE}.get_document_for_resource", return_value=None),patch.object(svc, "_download_pdf", return_value=(True, None, None)),):svc.download_resource(24)@@ -1033,7 +1044,6 @@ class TestRetryFailedDownload:session.query.return_value.filter_by.return_value.first.side_effect = [None, # existing_docNone, # pre-download queue_entry- None, # trackerqueue_entry, # post-download queue_entry]session.query.return_value.filter_by.return_value.order_by.return_value.first.return_value = None@@ -1045,6 +1055,8 @@ class TestRetryFailedDownload:f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),patch.object(svc, "_get_url_hash", return_value="hash_qf"),+ patch(f"{MODULE}.find_tracker_by_url", return_value=None),+ patch(f"{MODULE}.get_document_for_resource", return_value=None),patch.object(svc, "_download_pdf", return_value=(False, "No PDF found", None)),diff --git a/tests/research_library/services/test_library_service.py b/tests/research_library/services/test_library_service.pyindex 77786865c0..7499fb3b10 100644--- a/tests/research_library/services/test_library_service.py+++ b/tests/research_library/services/test_library_service.py@@ -194,56 +194,39 @@ class TestLibraryServiceDomainExtraction:class TestLibraryServiceUrlHash:- """Tests for URL hashing."""+ """Tests for URL hashing.++ ``LibraryService._get_url_hash`` was removed (issue #6760 follow-up):+ it double-normalized (``get_url_hash(normalize_url_for_hash(url))``)+ and diverged from the tracker writer on mixed-case query URLs. All+ lookups go through the shared ``get_url_hash`` / ``find_tracker_by_url``+ now — these tests pin that shared behavior instead.+ """def test_get_url_hash_normalizes_url(self):"""URL hashing normalizes URLs before hashing."""- from local_deep_research.research_library.services.library_service import (- LibraryService,- )+ from local_deep_research.research_library.utils import get_url_hash- with patch.object(- LibraryService, "__init__", lambda self, username: None- ):- service = LibraryService.__new__(LibraryService)- service.username = "test_user"-- # Same URL with different protocols should produce same hash- hash1 = service._get_url_hash("https://arxiv.org/abs/2301.00001")- hash2 = service._get_url_hash("http://arxiv.org/abs/2301.00001")- assert hash1 == hash2+ # Same URL with different protocols should produce same hash+ hash1 = get_url_hash("https://arxiv.org/abs/2301.00001")+ hash2 = get_url_hash("http://arxiv.org/abs/2301.00001")+ assert hash1 == hash2def test_get_url_hash_removes_www(self):"""URL hashing removes www prefix."""- from local_deep_research.research_library.services.library_service import (- LibraryService,- )+ from local_deep_research.research_library.utils import get_url_hash- with patch.object(- LibraryService, "__init__", lambda self, username: None- ):- service = LibraryService.__new__(LibraryService)- service.username = "test_user"-- hash1 = service._get_url_hash("https://www.example.com/page")- hash2 = service._get_url_hash("https://example.com/page")- assert hash1 == hash2+ hash1 = get_url_hash("https://www.example.com/page")+ hash2 = get_url_hash("https://example.com/page")+ assert hash1 == hash2def test_get_url_hash_removes_trailing_slash(self):"""URL hashing removes trailing slashes."""- from local_deep_research.research_library.services.library_service import (- LibraryService,- )-- with patch.object(- LibraryService, "__init__", lambda self, username: None- ):- service = LibraryService.__new__(LibraryService)- service.username = "test_user"+ from local_deep_research.research_library.utils import get_url_hash- hash1 = service._get_url_hash("https://example.com/page/")- hash2 = service._get_url_hash("https://example.com/page")- assert hash1 == hash2+ hash1 = get_url_hash("https://example.com/page/")+ hash2 = get_url_hash("https://example.com/page")+ assert hash1 == hash2class TestLibraryServiceToggleFavorite:diff --git a/tests/research_library/test_deletion_cascade_contracts.py b/tests/research_library/test_deletion_cascade_contracts.pyindex 0b4dbcc020..aca27c3371 100644--- a/tests/research_library/test_deletion_cascade_contracts.py+++ b/tests/research_library/test_deletion_cascade_contracts.py@@ -62,6 +62,7 @@ from local_deep_research.database.models import Basefrom local_deep_research.database.models.download_tracker import (DownloadTracker,)+from local_deep_research.research_library.utils import get_url_hashfrom local_deep_research.database.models.library import (Collection,CollectionFolder,@@ -295,10 +296,13 @@ def _add_folder(session, collection_id, folder_path):def _add_tracker(session, resource_id, url, doc_id):+ # Seed with the production hash: hand-rolling sha256(url.lower()) here+ # would pin the pre-B2 (#6758) scheme and silently diverge from the+ # cascade lookup under test.session.add(DownloadTracker(url=url,- url_hash=hashlib.sha256(url.lower().encode()).hexdigest(),+ url_hash=get_url_hash(url),first_resource_id=resource_id,file_path=f"pdfs/{doc_id}.pdf",file_name=f"{doc_id}.pdf",@@ -570,7 +574,9 @@ def _folder_keys(db):def _tracker_by_url(db, url):- url_hash = hashlib.sha256(url.lower().encode()).hexdigest()+ # Look up with the production hash (see _add_tracker): the old+ # hand-rolled sha256(url.lower()) no longer matches post-B2 (#6758).+ url_hash = get_url_hash(url)with db.fresh() as s:return s.query(DownloadTracker).filter_by(url_hash=url_hash).one()diff --git a/tests/research_library/test_download_service_contracts.py b/tests/research_library/test_download_service_contracts.pyindex c2a9ff08ed..36737d1d65 100644--- a/tests/research_library/test_download_service_contracts.py+++ b/tests/research_library/test_download_service_contracts.py@@ -112,6 +112,7 @@ from local_deep_research.research_library.services.pdf_storage_manager import (PDFStorageManager,resolve_pdf_storage_mode,)+from local_deep_research.research_library.utils import get_url_hashfrom local_deep_research.security import file_write_verifier, safe_requestsUSERNAME = "download_contract_user"@@ -353,7 +354,9 @@ def seeded(db):)tracker = DownloadTracker(url=url,- url_hash=hashlib.sha256(url.lower().encode()).hexdigest(),+ # Seed with the production hash (post-B2 #6758 scheme), not a+ # hand-rolled copy of its old implementation.+ url_hash=get_url_hash(url),first_resource_id=resource.id,is_downloaded=False,)diff --git a/tests/research_library/utils/test_utils.py b/tests/research_library/utils/test_utils.pyindex 8952597bc9..684ad7eb51 100644--- a/tests/research_library/utils/test_utils.py+++ b/tests/research_library/utils/test_utils.py@@ -15,8 +15,16 @@ class TestGetUrlHash:def test_returns_sha256_hex(self):from local_deep_research.research_library.utils import get_url_hash # noqa: E402+ # Golden vector: normalize("https://example.com/page") ==+ # "example.com/page" (scheme stripped, lowercased). Computed once+ # and pinned so the test fails if the normalization drifts — the+ # previous version computed the expectation with the function under+ # test and could never fail.url = "https://example.com/page"- expected = hashlib.sha256(url.lower().encode()).hexdigest()+ expected = hashlib.sha256(b"example.com/page").hexdigest()+ assert expected == (+ "d641f3ecfa3d1007cb7e145a76a12b4d969513a43ec173d57480df068534f9b8"+ )assert get_url_hash(url) == expecteddef test_case_insensitive(self):@@ -39,6 +47,97 @@ class TestGetUrlHash:assert len(result) == 64 # SHA256 hex length+# ---------------------------------------------------------------------------+# normalize_url_for_hash / B2 (issue #6758): URL-hash normalization+# ---------------------------------------------------------------------------+++class TestNormalizeUrlForHash:+ """B2: the same article with tracking params, fragments, default ports,+ userinfo, scheme or www variance must hash alike; genuinely different+ URLs must not be merged."""++ def test_tracking_params_are_stripped(self):+ from local_deep_research.research_library.utils import get_url_hash # noqa: E402++ assert get_url_hash(+ "https://example.com/paper?utm_source=newsletter&utm_medium=email"+ ) == get_url_hash("https://example.com/paper")+ assert get_url_hash(+ "https://example.com/paper?fbclid=abc123"+ ) == get_url_hash("https://example.com/paper")+ assert get_url_hash(+ "https://example.com/paper?gclid=xyz&page=2"+ ) == get_url_hash("https://example.com/paper?page=2")++ def test_fragments_are_stripped(self):+ from local_deep_research.research_library.utils import get_url_hash # noqa: E402++ assert get_url_hash(+ "https://example.com/paper#section-2"+ ) == get_url_hash("https://example.com/paper")++ def test_default_ports_are_stripped(self):+ from local_deep_research.research_library.utils import get_url_hash # noqa: E402++ assert get_url_hash("https://example.com:443/paper") == get_url_hash(+ "https://example.com/paper"+ )+ assert get_url_hash("http://example.com:80/paper") == get_url_hash(+ "http://example.com/paper"+ )++ def test_userinfo_is_stripped(self):+ from local_deep_research.research_library.utils import get_url_hash # noqa: E402++ assert get_url_hash(+ "https://user:[email protected]/paper"+ ) == get_url_hash("https://example.com/paper")++ def test_scheme_and_www_variants_match(self):+ from local_deep_research.research_library.utils import get_url_hash # noqa: E402++ assert get_url_hash("http://example.com/paper") == get_url_hash(+ "https://example.com/paper"+ )+ assert get_url_hash("https://www.example.com/paper") == get_url_hash(+ "https://example.com/paper"+ )++ def test_query_param_order_does_not_matter(self):+ from local_deep_research.research_library.utils import get_url_hash # noqa: E402++ assert get_url_hash("https://example.com/s?z=1&a=2") == get_url_hash(+ "https://example.com/s?a=2&z=1"+ )++ def test_meaningful_query_params_are_preserved(self):+ from local_deep_research.research_library.utils import get_url_hash # noqa: E402++ assert get_url_hash("https://example.com/paper?page=2") != get_url_hash(+ "https://example.com/paper?page=3"+ )+ assert get_url_hash("https://example.com/paper?page=2") != get_url_hash(+ "https://example.com/paper"+ )++ def test_percent_encoding_spellings_stay_distinct(self):+ """B2 review: ``+`` vs ``%20`` and ``;`` vs ``%3B`` must NOT merge.++ A server may treat ``+``/``;`` literally, so merging would link a+ resource to the wrong document (silent wrong-content link).+ ``canonical_url_key`` preserves raw query spellings for this reason.+ """+ from local_deep_research.research_library.utils import get_url_hash # noqa: E402++ assert get_url_hash("https://example.com/s?q=a+b") != get_url_hash(+ "https://example.com/s?q=a%20b"+ )+ assert get_url_hash("https://example.com/s?a=1;b=2") != get_url_hash(+ "https://example.com/s?a=1%3Bb=2"+ )++# ---------------------------------------------------------------------------# get_library_storage_path# ---------------------------------------------------------------------------