~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(database): preserve shared documents and download history on deletion (#7068)
LearningCircuiteaae95223c88
diff --git a/changelog.d/7068.bugfix.md b/changelog.d/7068.bugfix.mdnew file mode 100644index 0000000000..2565a595c8--- /dev/null+++ b/changelog.d/7068.bugfix.md@@ -0,0 +1,3 @@+Deleting or clearing a research now preserves download tracking and retry history when another research still references the same source: the identical URL, a URL the download service treats as the same (it ignores an `http://` or `https://` prefix in any letter case, uppercased scheme or host spellings, a leading `www.`, trailing slashes at the end of the URL and — except on the bare root path — directly before the `?`, and query-parameter order and letter case), or a recorded duplicate. Shared tracking is removed when its last research reference is deleted.++Concurrent new references are protected by a shared database snapshot. If a concurrent writer invalidates that snapshot, the research deletion and history-clearing endpoints retry the whole transaction with fresh references and protection checks. Retries are bounded, and report files are removed only after the database commit succeeds.diff --git a/changelog.d/7162.bugfix.md b/changelog.d/7162.bugfix.mdnew file mode 100644index 0000000000..772a251aff--- /dev/null+++ b/changelog.d/7162.bugfix.md@@ -0,0 +1 @@+Deleting a research run preserves library documents still referenced by another run, including their stored PDFs, collection memberships, and search indexes.diff --git a/docs/decisions/0012-wontfix-legacy-documents-resource-cascade.md b/docs/decisions/0012-wontfix-legacy-documents-resource-cascade.mdindex 6fe82f578c..b551cffd3e 100644--- a/docs/decisions/0012-wontfix-legacy-documents-resource-cascade.md+++ b/docs/decisions/0012-wontfix-legacy-documents-resource-cascade.md@@ -109,9 +109,10 @@ which governs branches that are pursued.deletes `research_resources` directly, and the blast radius isunchanged across the three potentially data-bearing sites — thelegacy FK adds marginal damage only for documents whose `resource_id`- points into the deleted session while their `research_id` does not; current- code sets `resource_id` once at creation and never re-points it, so- such divergence is not manufactured today.+ points into the deleted session while their `research_id` does not. At+ the September 12 review, code set `resource_id` once at creation and never+ re-pointed it, so it did not manufacture such divergence. The+ shared-document ownership review below covers later, aligned reparenting.- No other deletion route to `research_resources` exists under`src/local_deep_research/` — beyond the ORM `delete_resource` pathabove, no direct, bulk, or raw-SQL deletion of `ResearchResource`@@ -291,6 +292,41 @@ should a real victim ever surface.is the decision that it is accepted drift. New model/schema FK divergencesremain open defects.+## October 6 review: shared document lifetime++Issue [#7162](https://github.com/LearningCircuit/local-deep-research/issues/7162)+exposed a separate loss on both schema shapes: content deduplication lets another+research's resource point at a document still owned by the first research.+Deleting that first research removed the document through its uniform+`research_id` cascade, including the other research's stored paper.++The application cascade now retains a document when another surviving research+has an explicit `ResearchResource.document_id` reference to it. It chooses a+surviving resource deterministically and updates the document's `resource_id`+and `research_id` together. The document ID, text, PDF location/blob, collection+memberships and index state stay attached to the retained document. Retained+documents are excluded before the cascade computes their dependent-row scopes;+changing ownership only after that computation would still delete their blobs+and collection links. Transfers share the deletion savepoint, so guard refusal,+write failure and caller rollback restore the prior ownership.++This changes the existing research-delete semantics and therefore re-reviews+guard (1). Guards (2)–(4) remain intact: every transferred resource belongs to+the new research owner, ORM resource-deletion relationships are unchanged, and+`Document.research_id` retains `ON DELETE CASCADE` on both schema shapes. On a+legacy database, the retained document no longer references a resource being+deleted, so its resource CASCADE cannot remove it. No schema migration is+introduced; the legacy-FK migration disposition remains unchanged.++`tests/database/test_shared_document_lifetime.py` exercises the actual cascade+on file-backed databases with both resource-FK shapes and foreign keys enabled.+It covers retained text, blobs and indexes; batch transfers and protected+successors; transaction rollback; and concurrent reference insertion/removal+under WAL. A stale deletion snapshot must fail and retry against the committed+references. Deleting the last referencing research keeps the existing cascade+behavior. Explicit global document deletion remains global; this retention+rule applies to deleting research, not to deleting the document itself.+## References- PR [#3772](https://github.com/LearningCircuit/local-deep-research/pull/3772) — the wontfixed migration (core approach retained: reuse requires renumbering/re-parenting to the current head plus both alignment-aware settlement before the rebuild and a failing `PRAGMA foreign_key_check` after it, not the literal file)diff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.pyindex b5f47e64c3..468fcada02 100644--- a/src/local_deep_research/chat/service.py+++ b/src/local_deep_research/chat/service.py@@ -36,7 +36,7 @@ from ..web.routes.globals import (is_research_thread_alive,set_termination_flag,)-from ..web.routers.research import _delete_research_with_dependents+from ..database.research_cascade import delete_research_with_dependentsfrom ..constants import ResearchStatus# Standard exception tuple for service-layer DB operations@@ -1229,7 +1229,7 @@ class ChatService:# the shape ``#5074`` was protecting against, but# applied through the chat service's own liveness# gate rather than the helper's IN_PROGRESS check.- _delete_research_with_dependents(+ delete_research_with_dependents(db,research_id,require_status_not_in_progress=False,diff --git a/src/local_deep_research/database/research_cascade.py b/src/local_deep_research/database/research_cascade.pynew file mode 100644index 0000000000..e25567e7fb--- /dev/null+++ b/src/local_deep_research/database/research_cascade.py@@ -0,0 +1,720 @@+"""Explicit deletion of research rows and their foreign-key descendants.++Legacy SQLite databases retain the FK rules from table creation, and several+current download edges use NO ACTION. Derive a child-before-parent plan from+model metadata instead of relying on database cascades. The survival policy+clears links to chat, library, sync and synthesis rows that outlive a research.+Shared download trackers can move to another research's resource before the+plan runs, preserving their URL-level attempt and duplicate history.+Documents referenced by a surviving research likewise move to that resource;+their storage, collection links and indexing state remain attached to the same+document ID. Both ownership fields move together, including on legacy schemas.++Rows without an FK path to research_history, including document_chunks, are+outside this plan. Report files and UserActiveResearch remain caller concerns.+All writes use a nested savepoint; the caller owns the outer transaction.+"""++from loguru import logger+from sqlalchemy import (+ not_,+ select,+ text,+ tuple_,+)+from sqlalchemy.orm import Session++from ..constants import ResearchStatus+from .models import (+ Base,+ Document,+ DownloadDuplicates,+ DownloadTracker,+ QueuedResearch,+ ResearchHistory,+ ResearchResource,+)+from ..utilities.download_url import get_url_hash, get_url_hash_candidates+++_CASCADE_ROOT_TABLE = "research_history"++# (child_table, child_column) pairs whose rows SURVIVE a research+# delete with the link cleared. Every other edge reached by the+# metadata walk becomes a bulk DELETE. Keep this list to exactly the+# cases where deletion would destroy data owned by someone else:+# chat history outlives the research it discusses; library, sync and+# synthesis rows outlive any single research.+_CASCADE_SET_NULL = frozenset(+ {+ ("chat_messages", "research_id"),+ ("documents", "resource_id"),+ ("research_resources", "document_id"),+ ("download_tracker", "library_document_id"),+ ("note_syntheses", "result_document_id"),+ ("zotero_item_map", "document_id"),+ }+)++_cascade_plan_cache = None+++def _research_cascade_plan():+ """Derive ``(set_null_steps, delete_steps, table_to_class)`` from+ ``Base.metadata``.++ Each step is ``(child_table, child_column, parent_table,+ parent_column)``. Delete steps additionally carry their runtime+ order: deepest tables first, children before the parents they+ reference (topological over the reached subgraph). The result is+ cached — model metadata is fixed per process.+ """+ global _cascade_plan_cache+ if _cascade_plan_cache is not None:+ return _cascade_plan_cache++ table_to_class = {}+ for mapper in Base.registry.mappers:+ cls = mapper.class_+ table_name = getattr(cls.__table__, "name", None)+ if table_name:+ if table_name in table_to_class:+ raise AssertionError(+ f"cascade planner: table {table_name!r} maps to two classes"+ )+ table_to_class[table_name] = cls++ children_of: dict = {}+ for table in Base.metadata.tables.values():+ for fk in table.foreign_keys:+ children_of.setdefault(fk.column.table.name, []).append(+ (table.name, fk.parent.name, fk.column.name)+ )++ reached_edges = []+ levels = {_CASCADE_ROOT_TABLE: 0}+ queue = [_CASCADE_ROOT_TABLE]+ seen_edges = set()+ while queue:+ parent = queue.pop(0)+ for child, column, parent_column in sorted(children_of.get(parent, [])):+ key = (child, column, parent, parent_column)+ if key in seen_edges:+ continue+ seen_edges.add(key)+ if child not in table_to_class:+ raise AssertionError(+ "cascade planner: table "+ f"{child!r} references {parent!r} but has no "+ "mapped class — map it or exclude it explicitly"+ )+ reached_edges.append(key)+ if child not in levels:+ levels[child] = levels[parent] + 1+ queue.append(child)++ # A table's rows are deleted only when a deleted parent references+ # them through a non-surviving edge. Tables reached solely through+ # ``_CASCADE_SET_NULL`` edges (chat history, syntheses, sync state)+ # survive: edges targeting them need no step, since a row that is+ # never deleted cannot block anything.+ deleted_tables = {_CASCADE_ROOT_TABLE}+ changed = True+ while changed:+ changed = False+ for child, column, parent, _parent_column in reached_edges:+ if (+ parent in deleted_tables+ and (child, column) not in _CASCADE_SET_NULL+ and child not in deleted_tables+ ):+ deleted_tables.add(child)+ changed = True++ set_null_steps = [+ key for key in reached_edges if (key[0], key[1]) in _CASCADE_SET_NULL+ ]+ delete_steps = [+ key+ for key in reached_edges+ if (key[0], key[1]) not in _CASCADE_SET_NULL+ and key[2] in deleted_tables+ ]++ # Order deletes so every child goes before the parents it+ # references (Kahn's algorithm, table-name tie-break for+ # determinism). The planner asserts acyclicity: a future cyclic+ # FK must fail loudly here, not as a runtime IntegrityError.+ delete_tables = {step[0] for step in delete_steps}+ waiting_on = {table: set() for table in delete_tables}+ for child, _column, parent, _parent_column in delete_steps:+ if parent in waiting_on:+ waiting_on[parent].add(child)+ ordered_tables: list = []+ ready = sorted(+ table for table, blockers in waiting_on.items() if not blockers+ )+ while ready:+ table = ready.pop(0)+ ordered_tables.append(table)+ for other, blockers in waiting_on.items():+ if table in blockers:+ blockers.discard(table)+ if not blockers and other not in ordered_tables:+ ready.append(other)+ ready.sort()+ if len(ordered_tables) != len(waiting_on):+ raise AssertionError(+ "cascade planner: cyclic FKs among "+ f"{sorted(waiting_on)} — cannot order deletes"+ )+ table_rank = {table: rank for rank, table in enumerate(ordered_tables)}+ delete_steps.sort(key=lambda step: (table_rank[step[0]], step[0]))++ _cascade_plan_cache = (set_null_steps, delete_steps, table_to_class)+ return _cascade_plan_cache+++def _ensure_outer_db_transaction(db_session: Session) -> None:+ """Start a DB-level transaction when none exists yet.++ SQLite (and SQLCipher) in legacy transaction mode — the mode this+ app uses on every production connection (``isolation_level=""``,+ DEFERRED) — only opens a database transaction implicitly before+ DML. Pure ``SELECT``s leave the driver with no transaction even+ though the SQLAlchemy ``Session`` reports ``in_transaction() ==+ True``. Calling ``Session.begin_nested()`` in that state issues a+ standalone ``SAVEPOINT`` outside any ``BEGIN``; its ``RELEASE``+ then commits immediately instead of joining the caller's+ transaction, so a later ``db_session.rollback()`` cannot restore+ the rows (``clear_history`` ends up partly applied after a later+ failure). See the SQLAlchemy SQLite dialect docs on legacy+ transaction mode with the pysqlite driver.++ Probing the driver-level ``in_transaction`` flag and issuing a+ plain (DEFERRED) ``BEGIN`` when it is ``False`` makes the+ following ``begin_nested()`` a true nested savepoint: ``RELEASE``+ keeps the outer transaction open and the caller still owns+ ``commit`` / ``rollback``. DEFERRED (not IMMEDIATE) preserves the+ read-concurrency property production relies on (SELECTs take only+ a SHARED lock). If the transaction cannot be established, refuse+ deletion rather than risk using a stale snapshot or committing early.+ """+ connection = db_session.connection()+ raw = getattr(+ getattr(connection, "connection", None), "driver_connection", None+ )+ if raw is None:+ raise RuntimeError("research cascade: driver_connection unavailable")+ in_txn = getattr(raw, "in_transaction", None)+ if in_txn is None:+ raise RuntimeError(+ "research cascade: driver does not expose in_transaction"+ )+ is_in_txn = in_txn() if callable(in_txn) else bool(in_txn)+ if not is_in_txn:+ db_session.execute(text("BEGIN"))+++# Bound on bind parameters per IN list; SQLite builds before 3.32 cap a+# statement at 999.+_IN_CHUNK = 500+++def _chunks(values):+ values = list(values)+ for start in range(0, len(values), _IN_CHUNK):+ yield values[start : start + _IN_CHUNK]+++def _owned_trackers(db_session: Session, research_ids):+ """``(id, url, url_hash)`` of trackers whose first resource belongs to+ one of ``research_ids``."""+ owned = []+ for chunk in _chunks(research_ids):+ owned.extend(+ db_session.query(+ DownloadTracker.id,+ DownloadTracker.url,+ DownloadTracker.url_hash,+ )+ .filter(+ DownloadTracker.first_resource_id.in_(+ select(ResearchResource.id).where(+ ResearchResource.research_id.in_(chunk)+ )+ )+ )+ .all()+ )+ return owned+++def _tracker_references(db_session: Session, trackers):+ """Map each tracker id to the sorted ``(resource_id, research_id)`` of+ every existing resource that references it.++ A resource references a tracker when its URL is canonically equivalent+ to the tracker's URL, when its URL has the tracker's ``url_hash`` under the+ download service's current or legacy normalization (the service reuses+ trackers this way without recording a duplicate), or when a+ ``DownloadDuplicates`` row links it. Stored URLs and hashes are only+ read, never rewritten.++ Cost: ``research_resources.url`` has no index and the normalization+ cannot use one, so the URL match scans that table once for the whole+ ``trackers`` set. Stream rows in bounded batches and check the same+ hash candidates as download lookups in Python. The old SQL base filter+ cannot express canonical URL identity (userinfo, ports, fragments and+ tracking parameters), and could omit a surviving reference.+ """+ if not trackers:+ return {}+ references: dict = {tracker_id: set() for tracker_id, _u, _h in trackers}+ by_hash = {url_hash: tracker_id for tracker_id, _url, url_hash in trackers}+ by_url: dict = {}+ by_canonical_hash: dict = {}+ for tracker_id, url, _url_hash in trackers:+ by_url.setdefault(url, []).append(tracker_id)+ # A canonical resource URL cannot reconstruct a legacy hash of the+ # original decorated URL. Normalize both URLs without re-keying rows.+ # Several legacy trackers can represent the same canonical URL.+ by_canonical_hash.setdefault(get_url_hash(url), []).append(tracker_id)++ for chunk in _chunks(by_hash):+ for url_hash, resource_id, research_id in (+ db_session.query(+ DownloadDuplicates.url_hash,+ ResearchResource.id,+ ResearchResource.research_id,+ )+ .join(+ ResearchResource,+ ResearchResource.id == DownloadDuplicates.resource_id,+ )+ .join(+ ResearchHistory,+ ResearchHistory.id == ResearchResource.research_id,+ )+ .filter(DownloadDuplicates.url_hash.in_(chunk))+ ):+ references[by_hash[url_hash]].add((resource_id, research_id))++ url_column = ResearchResource.url+ candidates = (+ db_session.query(+ ResearchResource.id, ResearchResource.research_id, url_column+ )+ .join(+ ResearchHistory, ResearchHistory.id == ResearchResource.research_id+ )+ .filter(url_column.isnot(None))+ )+ for resource_id, research_id, url in candidates.yield_per(_IN_CHUNK):+ tracker_ids = set(by_url.get(url, ()))+ url_hashes = get_url_hash_candidates(url)+ tracker_ids.update(by_canonical_hash.get(url_hashes[0], ()))+ for url_hash in url_hashes:+ tracker_id = by_hash.get(url_hash)+ if tracker_id is not None:+ tracker_ids.add(tracker_id)+ for tracker_id in tracker_ids:+ references[tracker_id].add((resource_id, research_id))+ return {tracker_id: sorted(refs) for tracker_id, refs in references.items()}+++class SharedDownloadIndex:+ """Shared-download references for a batch of research deletes.++ ``clear_history`` deletes many researches in one transaction. Scanning+ ``research_resources`` once per tracker-owning research would repeat a+ full-table scan per research while holding the user database's write+ lock. :meth:`build` collects, in one scan, every resource that+ references a tracker owned by the batch. Trackers only move to+ resources that reference them, so this covers every tracker a batch+ member can own while the batch runs.++ Each delete then hands a tracker to the lowest-id referencing resource+ of a research that is neither being deleted nor already deleted+ (:meth:`mark_deleted`). This is the choice a fresh per-research scan+ would make, so a tracker handed to a later batch member moves again+ when that member is deleted, and stays with it when its guarded delete+ is refused. Researches outside the batch, including protected ones,+ are never deleted, so they stay eligible. A tracker the index has not+ seen (for example one created after :meth:`build`) is looked up with+ its own scan.+ """++ def __init__(self):+ self._references: dict = {}+ self._first_live: dict = {}+ self._deleted: set = set()++ @classmethod+ def build(cls, db_session: Session, research_ids) -> "SharedDownloadIndex":+ # The snapshot must belong to the same database transaction as the+ # deletes. Legacy SQLite SELECTs alone do not begin a transaction.+ _ensure_outer_db_transaction(db_session)+ index = cls()+ owned = _owned_trackers(db_session, list(dict.fromkeys(research_ids)))+ index._references = _tracker_references(db_session, owned)+ return index++ def mark_deleted(self, research_id: str) -> None:+ self._deleted.add(research_id)++ def replacements(self, db_session: Session, research_id: str) -> dict:+ """Map each tracker this research owns to its surviving resource.++ Returns early, after one tracker query, when the research owns no+ tracker. Trackers without a surviving reference are left out and+ deleted with the research.+ """+ owned = _owned_trackers(db_session, [research_id])+ if not owned:+ return {}+ unseen = [row for row in owned if row[0] not in self._references]+ if unseen:+ self._references.update(_tracker_references(db_session, unseen))+ replacements = {}+ for tracker_id, _url, _url_hash in owned:+ refs = self._references[tracker_id]+ start = self._first_live.get(tracker_id, 0)+ # Deleted researches never come back; skip them for good.+ while start < len(refs) and refs[start][1] in self._deleted:+ start += 1+ self._first_live[tracker_id] = start+ for resource_id, ref_research_id in refs[start:]:+ if (+ ref_research_id != research_id+ and ref_research_id not in self._deleted+ ):+ replacements[tracker_id] = resource_id+ break+ return replacements+++def _shared_download_replacements(db_session: Session, research_id: str):+ """Choose a surviving resource for each tracker owned by this research.++ One-off form of :meth:`SharedDownloadIndex.replacements`: no scan when+ the research owns no tracker, otherwise one scan of+ ``research_resources``.+ """+ return SharedDownloadIndex().replacements(db_session, research_id)+++def _shared_document_replacements(+ db_session: Session, research_id: str+) -> dict[str, tuple[int, str]]:+ """Choose a surviving explicit reference for each shared document.++ Resource URLs may differ for identical downloaded bytes. The canonical+ document link is the evidence of sharing, not URL equality. Choose the+ lowest resource ID deterministically and keep resource/research ownership+ aligned, preserving ADR-0012's protection on legacy resource-CASCADE DBs.+ """+ references = (+ db_session.query(+ Document.id, ResearchResource.id, ResearchResource.research_id+ )+ .join(ResearchResource, ResearchResource.document_id == Document.id)+ .join(+ ResearchHistory, ResearchHistory.id == ResearchResource.research_id+ )+ .filter(+ Document.research_id == research_id,+ ResearchResource.research_id != research_id,+ )+ .order_by(ResearchResource.id)+ .all()+ )+ replacements = {}+ for document_id, resource_id, surviving_research_id in references:+ replacements.setdefault(+ document_id, (resource_id, surviving_research_id)+ )+ return replacements+++def delete_research_with_dependents(+ db_session: Session,+ research_id: str,+ *,+ require_status_not_in_progress: bool = True,+ require_no_claimed_queue_row: bool = True,+ shared_downloads: SharedDownloadIndex | None = None,+) -> bool:+ """Delete a research and its owned FK descendants atomically.++ URL-level download trackers move to a surviving resource when one exists;+ their shared attempt history and other resources' duplicate links survive.+ Shared documents transfer both owner fields to a surviving resource,+ preserving their ID, stored PDF, collections and existing index entries.+ Deleting the last referencing research retains ordinary cascade behavior;+ explicit global document deletion remains a separate operation.+ A caller deleting many researches in one transaction passes one+ ``shared_downloads`` index built for the whole set+ (:meth:`SharedDownloadIndex.build`); the helper records each successful+ delete in it. Without one, a research that owns a tracker pays its own+ scan of ``research_resources``.++ All child-table deletes and the parent delete are issued against the+ same SQLAlchemy session without an intervening commit, so the row+ is removed in one transaction. The two ``require_*`` flags gate the+ parent DELETE on the same predicates the original ``#5074`` guard+ embedded inline:++ * ``require_status_not_in_progress`` — refuses rows still+ ``IN_PROGRESS`` (a worker owns them).+ * ``require_no_claimed_queue_row`` — refuses rows whose+ ``QueuedResearch`` entry has ``is_processing = True`` (a worker is+ about to start or has not finished writing back the row).++ When either flag is ``False`` the corresponding predicate is dropped+ entirely. Both default to ``True`` so the helper applies the full+ guard by default — callers that genuinely want an unconditional+ cascade (e.g. the chat service's per-attempt teardown, where a+ pre-loaded liveness check has already ruled out a live worker) opt+ out explicitly. The predicates run **inside** the parent ``DELETE``+ so a concurrent claim that lands between the helper's read and its+ delete is observed by SQL and the row is preserved.++ Atomicity per research: child writes run inside a ``SAVEPOINT``+ (``Session.begin_nested``). When the parent ``DELETE`` deletes zero+ rows — ghost row or a guard refusal — the savepoint is rolled back+ so the ``False`` return leaves parent *and* children untouched. A+ ``True`` return releases the savepoint into the caller's outer+ transaction (the caller still owns ``commit`` / ``rollback``). This+ is what makes ``clear_history``'s multi-row loop safe: one+ protected row's rollback does not discard its siblings' deletes.++ The reference lookup and savepoint share a real database transaction.+ In legacy transaction mode (production SQLCipher/SQLite with+ ``isolation_level=""``), SELECTs do not open one, so a DEFERRED+ ``BEGIN`` precedes Phase A (and the batch index's initial lookup).+ This both prevents a standalone ``RELEASE`` from committing early+ and prevents a concurrent new reference from being silently missed.+ If a WAL writer changes the snapshot, upgrading it to a write fails;+ the caller must roll back and retry with a fresh index.++ The helper performs an explicit, application-level cascade driven+ by ``_research_cascade_plan()`` (derived from ``Base.metadata``,+ so new plain-data tables are picked up with no code change). See+ the module docstring for why we do not rely on the DB-level+ ``ON DELETE CASCADE``. Caller is responsible for the surrounding+ transaction (``commit`` / ``rollback``).++ Returns ``True`` iff the ``research_history`` row was deleted.+ """+ _ensure_outer_db_transaction(db_session)+ set_null_steps, delete_steps, table_to_class = _research_cascade_plan()++ def _pk_columns(table):+ return [table.c[name] for name in table.primary_key.columns.keys()]++ def _pk_filter(table, pk_values):+ pk_cols = _pk_columns(table)+ if len(pk_cols) == 1:+ return pk_cols[0].in_([row[0] for row in pk_values])+ return tuple_(*pk_cols).in_(pk_values)++ # Phase A: resolve scopes top-down. ``scopes[table]`` holds the PK+ # tuples reachable from the named research; each step's parent+ # values are the referenced-column values over those rows. Edges+ # resolve in rounds (a step resolves once its parent table's scope+ # is final), so same-level parents — e.g. ``note_references``+ # scoped by both ``research_history`` and ``documents`` — work.+ # Read-only SELECTs only; no writes happen before Phase B.+ root_table = table_to_class[_CASCADE_ROOT_TABLE].__table__+ scopes = {+ _CASCADE_ROOT_TABLE: db_session.query(*_pk_columns(root_table))+ .filter(root_table.c.id == research_id)+ .all()+ }+ # Ghost row fast-path: no writes, no savepoint.+ if not scopes[_CASCADE_ROOT_TABLE]:+ return False++ if shared_downloads is None:+ shared_downloads = SharedDownloadIndex()+ download_replacements = shared_downloads.replacements(+ db_session, research_id+ )+ document_replacements = _shared_document_replacements(+ db_session, research_id+ )+ edge_parent_values: dict = {}++ def _resolve_step(child, column, parent, parent_column):+ parent_table = table_to_class[parent].__table__+ parent_pks = scopes.get(parent, [])+ if not parent_pks:+ edge_parent_values[(child, column, parent, parent_column)] = []+ return []+ values = [+ value+ for (value,) in db_session.query(parent_table.c[parent_column])+ .filter(_pk_filter(parent_table, parent_pks))+ .distinct()+ .all()+ if value is not None+ ]+ edge_parent_values[(child, column, parent, parent_column)] = values+ return values++ # A table's scope is final once every DELETE edge into it has+ # resolved (SET NULL edges never extend a scope — nulled rows+ # survive, so nothing traverses from them). DELETE edges form a+ # DAG (asserted by the planner), and every such edge is processed+ # parent-first, so this loop always terminates; the AssertionError+ # below is a safety net, not an expected path.+ all_steps = set_null_steps + delete_steps+ delete_step_set = set(delete_steps)+ resolved_tables = {_CASCADE_ROOT_TABLE}+ remaining_steps = set(all_steps)+ while remaining_steps:+ resolvable = sorted(+ step for step in remaining_steps if step[2] in resolved_tables+ )+ if not resolvable:+ raise AssertionError(+ "cascade planner: unresolvable scope chain from "+ f"{sorted(remaining_steps)} — cyclic FKs?"+ )+ for step in resolvable:+ child, column, parent, parent_column = step+ values = _resolve_step(child, column, parent, parent_column)+ if step in delete_step_set and values:+ child_table = table_to_class[child].__table__+ children = db_session.query(*_pk_columns(child_table)).filter(+ child_table.c[column].in_(values)+ )+ if child == "download_tracker" and download_replacements:+ # These trackers will move before deleting resources.+ # Exclude them from descendant scopes so their shared+ # attempts and other researches' duplicates survive.+ children = children.filter(+ child_table.c.id.notin_(download_replacements)+ )+ if child == "documents" and document_replacements:+ # Exclude retained documents before computing descendant+ # scopes, or blobs/collection links would still be deleted+ # even though the document's owner changes below.+ children = children.filter(+ child_table.c.id.notin_(document_replacements)+ )+ scopes.setdefault(child, []).extend(+ tuple(row) for row in children.all()+ )+ remaining_steps.discard(step)+ # Mark a table resolved once every DELETE edge into it has+ # resolved. NB: this must scan tables, not remaining steps —+ # a table whose edges all resolved in an earlier round is no+ # longer in ``remaining_steps`` but still needs marking so+ # deeper edges become resolvable.+ done_steps = set(all_steps) - remaining_steps+ for table in {step[0] for step in delete_steps}:+ if table not in resolved_tables and all(+ incoming in done_steps+ for incoming in delete_steps+ if incoming[0] == table+ ):+ resolved_tables.add(table)++ # Phases B–D run inside a SAVEPOINT so a zero-row parent DELETE+ # (ghost or guard refusal) rolls back the child writes for *this*+ # research only. Without this, ``clear_history`` would commit the+ # orphaned children of a skipped row along with its siblings.+ # Phase A already started the outer DB transaction, so RELEASE+ # cannot commit ahead of the caller's commit / rollback.+ savepoint = db_session.begin_nested()+ try:+ for document_id, (+ resource_id,+ owner_id,+ ) in document_replacements.items():+ db_session.query(Document).filter(+ Document.id == document_id, Document.research_id == research_id+ ).update(+ {"resource_id": resource_id, "research_id": owner_id},+ synchronize_session=False,+ )++ # Keep URL-level tracking with a surviving research. These updates+ # share the savepoint with the cascade, so a refused parent delete+ # restores the original ownership along with all child rows.+ for tracker_id, resource_id in download_replacements.items():+ db_session.query(DownloadTracker).filter(+ DownloadTracker.id == tracker_id+ ).update(+ {"first_resource_id": resource_id}, synchronize_session=False+ )++ # Phase B: clear the surviving links first (all such columns are+ # nullable). Nulling before deleting means the deletes below never+ # meet a row that still points at them, on any schema.+ for child, column, parent, parent_column in set_null_steps:+ values = edge_parent_values[(child, column, parent, parent_column)]+ if not values:+ continue+ cls = table_to_class[child]+ db_session.query(cls).filter(+ getattr(cls, column).in_(values)+ ).update({column: None}, synchronize_session=False)++ # Phase C: bulk deletes in planner order (deepest first), each+ # scoped to its own edge. Scopes were fully resolved in Phase A,+ # so no reads are needed here.+ for child, column, parent, parent_column in delete_steps:+ values = edge_parent_values[(child, column, parent, parent_column)]+ if not values:+ continue+ cls = table_to_class[child]+ child_table = cls.__table__+ db_session.query(cls).filter(+ child_table.c[column].in_(values)+ ).delete(synchronize_session=False)++ # Phase D: finally, the parent row itself. The ``#5074``+ # predicates are applied INSIDE this DELETE so a concurrent queue+ # claim or status write observed by the row sees them atomically —+ # mirroring the old ``DELETE ... WHERE id = ? AND status !=+ # IN_PROGRESS AND ~claimed_queue_row`` shape. A zero-row return+ # means the row did not exist or one of the guards blocked it;+ # callers that map the latter to a 400 must check the row+ # externally (the helper deliberately does not distinguish).+ parent_filters = [ResearchHistory.id == research_id]+ if require_status_not_in_progress:+ parent_filters.append(+ ResearchHistory.status != ResearchStatus.IN_PROGRESS+ )+ if require_no_claimed_queue_row:+ claimed_queue_row = db_session.query(QueuedResearch.id).filter(+ QueuedResearch.research_id == research_id,+ QueuedResearch.is_processing.is_(True),+ )+ parent_filters.append(not_(claimed_queue_row.exists()))++ deleted = (+ db_session.query(ResearchHistory)+ .filter(*parent_filters)+ .delete(synchronize_session=False)+ )++ if not deleted:+ # Guard refused (or ghost raced away): undo this research's+ # child writes, keep the outer transaction for siblings.+ savepoint.rollback()+ return False+ savepoint.commit()+ shared_downloads.mark_deleted(research_id)+ return True+ except Exception:+ try:+ savepoint.rollback()+ except Exception as rollback_exc:+ logger.debug(+ f"research cascade savepoint rollback failed: {rollback_exc}"+ )+ raisediff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.pyindex 48f5751c59..97960aacdc 100644--- a/src/local_deep_research/research_library/utils/__init__.py+++ b/src/local_deep_research/research_library/utils/__init__.py@@ -1,9 +1,7 @@"""Shared utility functions for the Research Library."""-import hashlibimport ipaddressimport os-import reimport socketimport subprocessimport sys@@ -17,6 +15,12 @@ from loguru import loggerfrom ...security import redact_url_for_logfrom ...config.paths import get_library_directory+from ...utilities.download_url import (+ normalize_url_for_hash as normalize_url_for_hash,+ get_url_hash as get_url_hash,+ get_legacy_url_hashes as get_legacy_url_hashes,+ get_url_hash_candidates as get_url_hash_candidates,+)from ...database.models.library import Document, DocumentCollectionfrom ...security.ip_ranges import PRIVATE_IP_RANGESfrom ...security.network_utils import is_private_ip@@ -258,148 +262,6 @@ 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.-- Args:- url: The URL to hash-- Returns:- 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.- """- 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.diff --git a/src/local_deep_research/utilities/download_url.py b/src/local_deep_research/utilities/download_url.pynew file mode 100644index 0000000000..6620229176--- /dev/null+++ b/src/local_deep_research/utilities/download_url.py@@ -0,0 +1,153 @@+"""URL identity shared by download writers, readers and research deletion.++No database, service or web imports are needed to load these helpers.+"""++import hashlib+import re++from loguru import logger+++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 both the database and research-library stacks. Defer+ loading the utilities/security stack until normalization is needed.+ """+ from .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("&"))+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: URL query-param sorting only; this module builds no SQL+ normalized = f"{base}?{'&'.join(params)}"+ return normalized+++def get_url_hash(url: str) -> str:+ """+ Generate a SHA256 hash of a URL.++ Args:+ url: The URL to hash++ Returns:+ 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("&"))+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: URL query-param sorting only; this module builds no SQL+ 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.+ """+ 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 outdiff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.pyindex c8d6a6fd29..864d9681d9 100644--- a/src/local_deep_research/web/routers/research.py+++ b/src/local_deep_research/web/routers/research.py@@ -31,7 +31,7 @@ from pathlib import Pathfrom loguru import loggerfrom ...settings.logger import log_settings-from sqlalchemy import case, func, not_, text, tuple_+from sqlalchemy import case, funcfrom sqlalchemy.orm import Sessionfrom typing import Optional, Annotated@@ -62,7 +62,6 @@ from ..services.pdf_service import ()from ...database.models import (- Base,QueuedResearch,ResearchHistory,UserActiveResearch,@@ -72,7 +71,12 @@ from ..models.database import (calculate_duration,)from ...database.models.library import Document as Document+from ...database.research_cascade import (+ SharedDownloadIndex,+ delete_research_with_dependents as _delete_research_with_dependents,+)from ...database.session_context import get_user_db_session+from ...database.sqlcipher_utils import retry_on_db_lockfrom ...llm.providers.base import normalize_providerfrom ..auth.password_utils import resolve_user_passwordfrom ..services.research_service import (@@ -1851,486 +1855,6 @@ def _unlink_report_file_if_inside_root(report_path: Optional[str]) -> bool:return False-# ----------------------------------------------------------------------------# Application-level cascade for ``research_history`` deletions-# ----------------------------------------------------------------------------#-# Schema reality (see ``src/local_deep_research/database/models/``;-# table names are the physical SQLite names): the ``research_history``-# descendant closure spans two dozen tables at depths 1-3, with mixed-# ``ON DELETE`` rules — several depth-2 edges (``download_tracker`` /-# ``download_duplicates`` → ``research_resources``,-# ``download_attempts`` / ``download_duplicates`` →-# ``download_tracker.url_hash``) were never declared CASCADE at all.-#-# Declared rules cannot be trusted anyway: legacy user databases keep-# whatever rules existed when each table was created (SQLite bakes FK-# rules into ``CREATE TABLE``), and ``PRAGMA foreign_keys = ON`` (set-# on every production connection) turns any gap into ``FOREIGN KEY-# constraint failed`` instead of silent orphans. The helper below-# therefore performs the *entire* cascade explicitly in application-# code and never depends on declared rules firing.-#-# How it works: ``_research_cascade_plan()`` derives the plan from-# ``Base.metadata`` on first use (metadata is fixed per process, so-# the plan is built once and cached):-# 1. Walk every FK edge transitively reachable from-# ``research_history`` — any depth, including edges that target-# non-PK unique columns such as ``download_tracker.url_hash``.-# 2. Every reached edge is classified by ``_CASCADE_SET_NULL``:-# listed ``(table, column)`` pairs are nulled (those rows survive-# — chat history, library/sync/synthesis rows outlive any single-# research); every other reached edge becomes a bulk ``DELETE``.-# 3. At runtime each step is scoped to rows reachable from the named-# research (parent keys collected top-down), nulls run first,-# deletes run deepest-first in topological order (the planner-# asserts acyclicity, so a future cyclic FK fails loudly instead-# of violating constraints at runtime).-# Sibling researches are untouched. ``url_hash`` is shared across-# researches for the same URL, so attempt/duplicate rows under a-# shared hash are inherently shared and go with the hash.-#-# Known limitations:-# 1. Tables with no FK path to ``research_history`` are invisible to-# the walk and keep prior behaviour — e.g. ``document_chunks``-# links via a rule-less ``source_id`` column (no constraint to-# violate; orphans possible, as before). Plain non-FK-# ``research_id`` columns are not deletion scopes; their rows are-# reached through their non-nullable FK key columns instead.-# 2. **Side effects.** The report file on disk and the per-user cap-# counter (``UserActiveResearch``) stay outside the helper:-# not FK targets.-#-# Coverage contract (guarded by ``TestHelperCoverageBaseMetadata`` and-# ``TestDepth2ResourceChildCascade``): the plan must classify *every*-# FK edge in the ``research_history`` descendant closure. Plain data-# tables need nothing and are picked up automatically; rows that must-# survive need an entry in ``_CASCADE_SET_NULL``. A new table, a-# renamed column, or policy drift fails CI instead of orphaning or-# 500ing in production.-_CASCADE_ROOT_TABLE = "research_history"--# (child_table, child_column) pairs whose rows SURVIVE a research-# delete with the link cleared. Every other edge reached by the-# metadata walk becomes a bulk DELETE. Keep this list to exactly the-# cases where deletion would destroy data owned by someone else:-# chat history outlives the research it discusses; library, sync and-# synthesis rows outlive any single research.-_CASCADE_SET_NULL = frozenset(- {- ("chat_messages", "research_id"),- ("documents", "resource_id"),- ("research_resources", "document_id"),- ("download_tracker", "library_document_id"),- ("note_syntheses", "result_document_id"),- ("zotero_item_map", "document_id"),- }-)--_cascade_plan_cache = None---def _research_cascade_plan():- """Derive ``(set_null_steps, delete_steps, table_to_class)`` from- ``Base.metadata``.-- Each step is ``(child_table, child_column, parent_table,- parent_column)``. Delete steps additionally carry their runtime- order: deepest tables first, children before the parents they- reference (topological over the reached subgraph). The result is- cached — model metadata is fixed per process.- """- global _cascade_plan_cache- if _cascade_plan_cache is not None:- return _cascade_plan_cache-- table_to_class = {}- for mapper in Base.registry.mappers:- cls = mapper.class_- table_name = getattr(cls.__table__, "name", None)- if table_name:- if table_name in table_to_class:- raise AssertionError(- f"cascade planner: table {table_name!r} maps to two classes"- )- table_to_class[table_name] = cls-- children_of: dict = {}- for table in Base.metadata.tables.values():- for fk in table.foreign_keys:- children_of.setdefault(fk.column.table.name, []).append(- (table.name, fk.parent.name, fk.column.name)- )-- reached_edges = []- levels = {_CASCADE_ROOT_TABLE: 0}- queue = [_CASCADE_ROOT_TABLE]- seen_edges = set()- while queue:- parent = queue.pop(0)- for child, column, parent_column in sorted(children_of.get(parent, [])):- key = (child, column, parent, parent_column)- if key in seen_edges:- continue- seen_edges.add(key)- if child not in table_to_class:- raise AssertionError(- "cascade planner: table "- f"{child!r} references {parent!r} but has no "- "mapped class — map it or exclude it explicitly"- )- reached_edges.append(key)- if child not in levels:- levels[child] = levels[parent] + 1- queue.append(child)-- # A table's rows are deleted only when a deleted parent references- # them through a non-surviving edge. Tables reached solely through- # ``_CASCADE_SET_NULL`` edges (chat history, syntheses, sync state)- # survive: edges targeting them need no step, since a row that is- # never deleted cannot block anything.- deleted_tables = {_CASCADE_ROOT_TABLE}- changed = True- while changed:- changed = False- for child, column, parent, _parent_column in reached_edges:- if (- parent in deleted_tables- and (child, column) not in _CASCADE_SET_NULL- and child not in deleted_tables- ):- deleted_tables.add(child)- changed = True-- set_null_steps = [- key for key in reached_edges if (key[0], key[1]) in _CASCADE_SET_NULL- ]- delete_steps = [- key- for key in reached_edges- if (key[0], key[1]) not in _CASCADE_SET_NULL- and key[2] in deleted_tables- ]-- # Order deletes so every child goes before the parents it- # references (Kahn's algorithm, table-name tie-break for- # determinism). The planner asserts acyclicity: a future cyclic- # FK must fail loudly here, not as a runtime IntegrityError.- delete_tables = {step[0] for step in delete_steps}- waiting_on = {table: set() for table in delete_tables}- for child, _column, parent, _parent_column in delete_steps:- if parent in waiting_on:- waiting_on[parent].add(child)- ordered_tables: list = []- ready = sorted(- table for table, blockers in waiting_on.items() if not blockers- )- while ready:- table = ready.pop(0)- ordered_tables.append(table)- for other, blockers in waiting_on.items():- if table in blockers:- blockers.discard(table)- if not blockers and other not in ordered_tables:- ready.append(other)- ready.sort()- if len(ordered_tables) != len(waiting_on):- raise AssertionError(- "cascade planner: cyclic FKs among "- f"{sorted(waiting_on)} — cannot order deletes"- )- table_rank = {table: rank for rank, table in enumerate(ordered_tables)}- delete_steps.sort(key=lambda step: (table_rank[step[0]], step[0]))-- _cascade_plan_cache = (set_null_steps, delete_steps, table_to_class)- return _cascade_plan_cache---def _ensure_outer_db_transaction(db_session: Session) -> None:- """Start a DB-level transaction when none exists yet.-- SQLite (and SQLCipher) in legacy transaction mode — the mode this- app uses on every production connection (``isolation_level=""``,- DEFERRED) — only opens a database transaction implicitly before- DML. Pure ``SELECT``s leave the driver with no transaction even- though the SQLAlchemy ``Session`` reports ``in_transaction() ==- True``. Calling ``Session.begin_nested()`` in that state issues a- standalone ``SAVEPOINT`` outside any ``BEGIN``; its ``RELEASE``- then commits immediately instead of joining the caller's- transaction, so a later ``db_session.rollback()`` cannot restore- the rows (``clear_history`` ends up partly applied after a later- failure). See the SQLAlchemy SQLite dialect docs on legacy- transaction mode with the pysqlite driver.-- Probing the driver-level ``in_transaction`` flag and issuing a- plain (DEFERRED) ``BEGIN`` when it is ``False`` makes the- following ``begin_nested()`` a true nested savepoint: ``RELEASE``- keeps the outer transaction open and the caller still owns- ``commit`` / ``rollback``. DEFERRED (not IMMEDIATE) preserves the- read-concurrency property production relies on (SELECTs take only- a SHARED lock). Best-effort: when the driver state cannot be- determined, proceed without forcing ``BEGIN`` rather than risking- a spurious ``cannot start a transaction within a transaction``- that would poison the session.- """- try:- connection = db_session.connection()- raw = getattr(- getattr(connection, "connection", None), "driver_connection", None- )- if raw is None:- logger.warning(- "research cascade: driver_connection unavailable, proceeding "- "without a forced BEGIN — a standalone savepoint may commit "- "early if the driver has no transaction"- )- return- in_txn = getattr(raw, "in_transaction", None)- if in_txn is None:- logger.warning(- "research cascade: driver does not expose in_transaction, "- "proceeding without a forced BEGIN — a standalone savepoint "- "may commit early if the driver has no transaction"- )- return- is_in_txn = in_txn() if callable(in_txn) else bool(in_txn)- if not is_in_txn:- db_session.execute(text("BEGIN"))- except Exception:- logger.exception(- "research cascade: could not ensure outer transaction before "- "savepoint — proceeding with a possibly standalone savepoint "- "that may commit early"- )---def _delete_research_with_dependents(- db_session: Session,- research_id: str,- *,- require_status_not_in_progress: bool = True,- require_no_claimed_queue_row: bool = True,-) -> bool:- """Delete ``research_history.id = research_id`` and every row that- references it, *atomically*.-- All child-table deletes and the parent delete are issued against the- same SQLAlchemy session without an intervening commit, so the row- is removed in one transaction. The two ``require_*`` flags gate the- parent DELETE on the same predicates the original ``#5074`` guard- embedded inline:-- * ``require_status_not_in_progress`` — refuses rows still- ``IN_PROGRESS`` (a worker owns them).- * ``require_no_claimed_queue_row`` — refuses rows whose- ``QueuedResearch`` entry has ``is_processing = True`` (a worker is- about to start or has not finished writing back the row).-- When either flag is ``False`` the corresponding predicate is dropped- entirely. Both default to ``True`` so the helper applies the full- guard by default — callers that genuinely want an unconditional- cascade (e.g. the chat service's per-attempt teardown, where a- pre-loaded liveness check has already ruled out a live worker) opt- out explicitly. The predicates run **inside** the parent ``DELETE``- so a concurrent claim that lands between the helper's read and its- delete is observed by SQL and the row is preserved.-- Atomicity per research: child writes run inside a ``SAVEPOINT``- (``Session.begin_nested``). When the parent ``DELETE`` deletes zero- rows — ghost row or a guard refusal — the savepoint is rolled back- so the ``False`` return leaves parent *and* children untouched. A- ``True`` return releases the savepoint into the caller's outer- transaction (the caller still owns ``commit`` / ``rollback``). This- is what makes ``clear_history``'s multi-row loop safe: one- protected row's rollback does not discard its siblings' deletes.-- The savepoint is only nested when a real database transaction- already exists. Phase A is read-only, and in legacy transaction- mode (production SQLCipher/SQLite with ``isolation_level=""``)- SELECTs do not open one — so the helper forces a DEFERRED- ``BEGIN`` first (see ``_ensure_outer_db_transaction``). Without- it, ``RELEASE`` commits immediately and a later caller- ``rollback()`` cannot restore parent or children.-- The helper performs an explicit, application-level cascade driven- by ``_research_cascade_plan()`` (derived from ``Base.metadata``,- so new plain-data tables are picked up with no code change). See- the block above for why we don't rely on the DB-level- ``ON DELETE CASCADE``. Caller is responsible for the surrounding- transaction (``commit`` / ``rollback``).-- Returns ``True`` iff the ``research_history`` row was deleted.- """- set_null_steps, delete_steps, table_to_class = _research_cascade_plan()-- def _pk_columns(table):- return [table.c[name] for name in table.primary_key.columns.keys()]-- def _pk_filter(table, pk_values):- pk_cols = _pk_columns(table)- if len(pk_cols) == 1:- return pk_cols[0].in_([row[0] for row in pk_values])- return tuple_(*pk_cols).in_(pk_values)-- # Phase A: resolve scopes top-down. ``scopes[table]`` holds the PK- # tuples reachable from the named research; each step's parent- # values are the referenced-column values over those rows. Edges- # resolve in rounds (a step resolves once its parent table's scope- # is final), so same-level parents — e.g. ``note_references``- # scoped by both ``research_history`` and ``documents`` — work.- # Read-only SELECTs only; no writes happen before Phase B.- root_table = table_to_class[_CASCADE_ROOT_TABLE].__table__- scopes = {- _CASCADE_ROOT_TABLE: db_session.query(*_pk_columns(root_table))- .filter(root_table.c.id == research_id)- .all()- }- edge_parent_values: dict = {}-- def _resolve_step(child, column, parent, parent_column):- parent_table = table_to_class[parent].__table__- parent_pks = scopes.get(parent, [])- if not parent_pks:- edge_parent_values[(child, column, parent, parent_column)] = []- return []- values = [- value- for (value,) in db_session.query(parent_table.c[parent_column])- .filter(_pk_filter(parent_table, parent_pks))- .distinct()- .all()- if value is not None- ]- edge_parent_values[(child, column, parent, parent_column)] = values- return values-- # A table's scope is final once every DELETE edge into it has- # resolved (SET NULL edges never extend a scope — nulled rows- # survive, so nothing traverses from them). DELETE edges form a- # DAG (asserted by the planner), and every such edge is processed- # parent-first, so this loop always terminates; the AssertionError- # below is a safety net, not an expected path.- all_steps = set_null_steps + delete_steps- delete_step_set = set(delete_steps)- resolved_tables = {_CASCADE_ROOT_TABLE}- remaining_steps = set(all_steps)- while remaining_steps:- resolvable = sorted(- step for step in remaining_steps if step[2] in resolved_tables- )- if not resolvable:- raise AssertionError(- "cascade planner: unresolvable scope chain from "- f"{sorted(remaining_steps)} — cyclic FKs?"- )- for step in resolvable:- child, column, parent, parent_column = step- values = _resolve_step(child, column, parent, parent_column)- if step in delete_step_set and values:- child_table = table_to_class[child].__table__- scopes.setdefault(child, []).extend(- tuple(row)- for row in db_session.query(*_pk_columns(child_table))- .filter(child_table.c[column].in_(values))- .all()- )- remaining_steps.discard(step)- # Mark a table resolved once every DELETE edge into it has- # resolved. NB: this must scan tables, not remaining steps —- # a table whose edges all resolved in an earlier round is no- # longer in ``remaining_steps`` but still needs marking so- # deeper edges become resolvable.- done_steps = set(all_steps) - remaining_steps- for table in {step[0] for step in delete_steps}:- if table not in resolved_tables and all(- incoming in done_steps- for incoming in delete_steps- if incoming[0] == table- ):- resolved_tables.add(table)-- # Ghost row fast-path: no writes, no savepoint.- if not scopes[_CASCADE_ROOT_TABLE]:- return False-- # Phases B–D run inside a SAVEPOINT so a zero-row parent DELETE- # (ghost or guard refusal) rolls back the child writes for *this*- # research only. Without this, ``clear_history`` would commit the- # orphaned children of a skipped row along with its siblings.- # The outer DB transaction must exist first: in legacy mode a- # SELECT-only session has none, and a standalone SAVEPOINT's- # RELEASE commits early (caller rollback then restores nothing).- _ensure_outer_db_transaction(db_session)- savepoint = db_session.begin_nested()- try:- # Phase B: clear the surviving links first (all such columns are- # nullable). Nulling before deleting means the deletes below never- # meet a row that still points at them, on any schema.- for child, column, parent, parent_column in set_null_steps:- values = edge_parent_values[(child, column, parent, parent_column)]- if not values:- continue- cls = table_to_class[child]- db_session.query(cls).filter(- getattr(cls, column).in_(values)- ).update({column: None}, synchronize_session=False)-- # Phase C: bulk deletes in planner order (deepest first), each- # scoped to its own edge. Scopes were fully resolved in Phase A,- # so no reads are needed here.- for child, column, parent, parent_column in delete_steps:- values = edge_parent_values[(child, column, parent, parent_column)]- if not values:- continue- cls = table_to_class[child]- child_table = cls.__table__- db_session.query(cls).filter(- child_table.c[column].in_(values)- ).delete(synchronize_session=False)-- # Phase D: finally, the parent row itself. The ``#5074``- # predicates are applied INSIDE this DELETE so a concurrent queue- # claim or status write observed by the row sees them atomically —- # mirroring the old ``DELETE ... WHERE id = ? AND status !=- # IN_PROGRESS AND ~claimed_queue_row`` shape. A zero-row return- # means the row did not exist or one of the guards blocked it;- # callers that map the latter to a 400 must check the row- # externally (the helper deliberately does not distinguish).- parent_filters = [ResearchHistory.id == research_id]- if require_status_not_in_progress:- parent_filters.append(- ResearchHistory.status != ResearchStatus.IN_PROGRESS- )- if require_no_claimed_queue_row:- claimed_queue_row = db_session.query(QueuedResearch.id).filter(- QueuedResearch.research_id == research_id,- QueuedResearch.is_processing.is_(True),- )- parent_filters.append(not_(claimed_queue_row.exists()))-- deleted = (- db_session.query(ResearchHistory)- .filter(*parent_filters)- .delete(synchronize_session=False)- )-- if not deleted:- # Guard refused (or ghost raced away): undo this research's- # child writes, keep the outer transaction for siblings.- savepoint.rollback()- return False- savepoint.commit()- return True- except Exception:- try:- savepoint.rollback()- except Exception as rollback_exc:- logger.debug(- f"research cascade savepoint rollback failed: {rollback_exc}"- )- raise--@router.delete("/api/delete/{research_id}")def delete_research(request: Request,@@ -2339,7 +1863,7 @@ def delete_research():"""Delete a research record"""- try:+ def delete_once():with get_user_db_session(username) as db_session:research = (db_session.query(ResearchHistory)@@ -2415,13 +1939,6 @@ def delete_research(db_session.commit()return {"status": "success"}- # Delete report file if it exists. `report_path` comes from the- # DB column — normally written by the research worker pointing at- # the user's reports dir, but a corrupted row (or future buggy- # writer) could set it to `../../etc/passwd`. The helper resolves- # and confirms containment before unlinking.- _unlink_report_file_if_inside_root(report_path)-# ``user_active_researches`` is not a CASCADE child of# ``research_history.id`` (see ``chat/service.py``'s parallel# cleanup), so the helper above does not touch it. Drop any@@ -2436,7 +1953,16 @@ def delete_research(cleanup_queued_research_state(db_session, [research_id])db_session.commit()- return {"status": "success"}+ # Files cannot roll back with the transaction. Remove the report only+ # after its database deletion commits, retaining the containment guard.+ _unlink_report_file_if_inside_root(report_path)+ return {"status": "success"}++ try:+ # A concurrent writer can invalidate the cascade's read snapshot.+ # The failed context rolls back; each bounded retry re-reads the row,+ # queue claim and shared references in a new transaction.+ return retry_on_db_lock(delete_once)except Exception:logger.exception("Error deleting research")return JSONResponse(@@ -2451,7 +1977,7 @@ def clear_history():"""Clear all research history"""- try:+ def clear_once():with get_user_db_session(username) as db_session:# Get all research records first to clean up files. Select# only id + report_path (the columns the cleanup loop uses)@@ -2476,6 +2002,14 @@ def clear_history(if research.id not in protected_ids]+ # One scan of research_resources for the whole set instead of+ # one per tracker-owning research. Building the index starts+ # a real DB transaction shared with all deletes. A concurrent+ # WAL write makes a stale snapshot fail closed on mutation;+ # retrying the request builds a fresh index.+ shared_downloads = SharedDownloadIndex.build(+ db_session, deletable_ids+ )deleted_ids = []for research_id in deletable_ids:# The #5074 atomic guard is applied INSIDE the helper's@@ -2497,16 +2031,12 @@ def clear_history(# Application-level cascade with the IN_PROGRESS and# claimed-queue predicates baked into the parent# DELETE; see ``_delete_research_with_dependents``.- if _delete_research_with_dependents(db_session, research_id):+ if _delete_research_with_dependents(+ db_session, research_id, shared_downloads=shared_downloads+ ):deleted_ids.append(research_id)if deleted_ids:- for research in research_records:- if research.id not in deleted_ids:- continue-- _unlink_report_file_if_inside_root(research.report_path)-from ..queue.lifecycle_cleanup import (cleanup_queued_research_state,)@@ -2515,7 +2045,15 @@ def clear_history(db_session.commit()- return {"status": "success"}+ for research in research_records:+ if research.id in deleted_ids:+ _unlink_report_file_if_inside_root(research.report_path)+ return {"status": "success"}++ try:+ # Retry the whole batch so its protection snapshot and shared-download+ # index are rebuilt after rollback; never reuse a partially applied plan.+ return retry_on_db_lock(clear_once)except Exception:logger.exception("Error clearing history")return JSONResponse(diff --git a/tests/database/test_model_constraint_contracts.py b/tests/database/test_model_constraint_contracts.pyindex a726433c7b..19302bc835 100644--- a/tests/database/test_model_constraint_contracts.py+++ b/tests/database/test_model_constraint_contracts.py@@ -663,7 +663,7 @@ def test_delete_research_helper_cleans_download_tracker_rows():(``_research_cascade_plan``), so the tables are not named in thehelper body; assert instead that the plan classifies thedownload-tracker edges as deletes."""- from local_deep_research.web.routers.research import (+ from local_deep_research.database.research_cascade import (_research_cascade_plan,)diff --git a/tests/database/test_research_cascade.py b/tests/database/test_research_cascade.pynew file mode 100644index 0000000000..dc590fd657--- /dev/null+++ b/tests/database/test_research_cascade.py@@ -0,0 +1,873 @@+"""Shared download ownership during the application-level research cascade."""++from datetime import UTC, datetime+from hashlib import sha256++import random++import pytest+from sqlalchemy import create_engine, event+from sqlalchemy.exc import OperationalError+from sqlalchemy.orm import Session++from local_deep_research.database.models import (+ Base,+ DownloadAttempt,+ DownloadDuplicates,+ DownloadTracker,+ QueuedResearch,+ ResearchHistory,+ ResearchResource,+)+from local_deep_research.utilities.download_url import (+ get_legacy_url_hashes,+ get_url_hash as download_url_hash,+ get_url_hash_candidates,+)+from local_deep_research.database import research_cascade+from local_deep_research.database.research_cascade import (+ SharedDownloadIndex,+ _shared_download_replacements,+ delete_research_with_dependents,+)+++_NOW = datetime(2025, 1, 1, tzinfo=UTC)+_URL = "https://example.com/shared.pdf"+++def cascade_session():+ engine = create_engine("sqlite://")++ @event.listens_for(engine, "connect")+ def enable_foreign_keys(connection, _record):+ connection.execute("PRAGMA foreign_keys = ON")++ Base.metadata.create_all(engine)+ with Session(engine) as session:+ yield session+ engine.dispose()+++def _shared_download_family(session, *, recorded_duplicate=True, same_url=True):+ for research_id in ("owner", "sibling"):+ session.add(+ ResearchHistory(+ id=research_id,+ query="q",+ mode="quick",+ status="completed",+ created_at=_NOW,+ )+ )+ session.flush()+ resources = []+ for research_id, url in (+ ("owner", _URL),+ ("owner", _URL),+ ("sibling", _URL if same_url else _URL + "?download=1"),+ ):+ resource = ResearchResource(+ research_id=research_id,+ title="source",+ url=url,+ source_type="web",+ created_at=_NOW,+ )+ session.add(resource)+ session.flush()+ resources.append(resource.id)+ url_hash = sha256(_URL.encode()).hexdigest()+ tracker = DownloadTracker(+ url=_URL,+ url_hash=url_hash,+ first_resource_id=resources[0],+ is_downloaded=True,+ file_hash="a" * 64,+ file_path="2025/01/shared.pdf",+ file_name="shared.pdf",+ file_size=123,+ first_seen=_NOW,+ downloaded_at=_NOW,+ last_checked=_NOW,+ )+ session.add(tracker)+ session.flush()+ tracker_id = tracker.id+ if recorded_duplicate:+ for resource_id, research_id in zip(+ resources, ("owner", "owner", "sibling"), strict=True+ ):+ session.add(+ DownloadDuplicates(+ url_hash=url_hash,+ resource_id=resource_id,+ research_id=research_id,+ )+ )+ session.add(+ DownloadAttempt(url_hash=url_hash, attempt_number=1, succeeded=True)+ )+ session.commit()+ return tracker_id, resources++[email protected]("deleted_research", ["owner", "sibling"])+ ("recorded_duplicate", "same_url"),+ [(True, False), (False, True), (True, True)],+)+def test_shared_tracker_survives_either_research_delete(+ cascade_session, deleted_research, recorded_duplicate, same_url+):+ tracker_id, resources = _shared_download_family(+ cascade_session,+ recorded_duplicate=recorded_duplicate,+ same_url=same_url,+ )++ assert delete_research_with_dependents(cascade_session, deleted_research)+ cascade_session.commit()+ cascade_session.expire_all()++ tracker = cascade_session.get(DownloadTracker, tracker_id)+ assert tracker is not None+ assert tracker.first_resource_id == (+ resources[2] if deleted_research == "owner" else resources[0]+ )+ assert tracker.is_downloaded is True+ assert tracker.file_hash == "a" * 64+ assert tracker.file_path == "2025/01/shared.pdf"+ assert tracker.file_name == "shared.pdf"+ assert tracker.file_size == 123+ assert tracker.downloaded_at == _NOW+ attempts = cascade_session.query(DownloadAttempt).all()+ assert len(attempts) == 1+ assert attempts[0].url_hash == tracker.url_hash+ assert attempts[0].succeeded is True+ surviving_research = "sibling" if deleted_research == "owner" else "owner"+ assert cascade_session.get(ResearchHistory, deleted_research) is None+ assert cascade_session.get(ResearchHistory, surviving_research) is not None+ surviving_resources = (+ {resources[2]} if deleted_research == "owner" else set(resources[:2])+ )+ assert {+ row.id for row in cascade_session.query(ResearchResource)+ } == surviving_resources+ assert {+ row.resource_id for row in cascade_session.query(DownloadDuplicates)+ } == (surviving_resources if recorded_duplicate else set())+++def test_deleting_last_research_removes_shared_download_family(cascade_session):+ _shared_download_family(cascade_session)++ # Transfer and eventual deletion must work in one clear-history transaction.+ for research_id in ("owner", "sibling"):+ assert delete_research_with_dependents(cascade_session, research_id)+ cascade_session.commit()++ for model in (+ ResearchHistory,+ ResearchResource,+ DownloadTracker,+ DownloadDuplicates,+ DownloadAttempt,+ ):+ assert cascade_session.query(model).count() == 0++[email protected]("guard", ["status", "claim"])+def test_guard_refusal_restores_shared_tracker_owner(cascade_session, guard):+ tracker_id, resources = _shared_download_family(cascade_session)+ if guard == "status":+ cascade_session.get(ResearchHistory, "owner").status = "in_progress"+ else:+ cascade_session.add(+ QueuedResearch(+ username="user",+ research_id="owner",+ query="q",+ mode="quick",+ position=1,+ is_processing=True,+ created_at=_NOW,+ )+ )+ cascade_session.commit()++ assert delete_research_with_dependents(cascade_session, "owner") is False+ cascade_session.commit()+ cascade_session.expire_all()++ assert (+ cascade_session.get(DownloadTracker, tracker_id).first_resource_id+ == resources[0]+ )+ assert cascade_session.query(ResearchHistory).count() == 2+ assert cascade_session.query(ResearchResource).count() == 3+ assert cascade_session.query(DownloadDuplicates).count() == 3+ assert cascade_session.query(DownloadAttempt).count() == 1++[email protected]("delete_sibling", [False, True])+def test_caller_rollback_restores_shared_download_family(+ cascade_session, delete_sibling+):+ tracker_id, resources = _shared_download_family(cascade_session)+ assert delete_research_with_dependents(cascade_session, "owner")+ if delete_sibling:+ assert delete_research_with_dependents(cascade_session, "sibling")+ cascade_session.rollback()++ # A fresh session catches any early commit when releasing the savepoint.+ with Session(cascade_session.get_bind()) as fresh:+ assert (+ fresh.get(DownloadTracker, tracker_id).first_resource_id+ == resources[0]+ )+ assert fresh.query(ResearchHistory).count() == 2+ assert fresh.query(ResearchResource).count() == 3+ assert fresh.query(DownloadDuplicates).count() == 3+ assert fresh.query(DownloadAttempt).count() == 1+++def test_clear_preserves_tracker_transferred_to_protected_sibling(+ cascade_session,+):+ tracker_id, resources = _shared_download_family(cascade_session)+ cascade_session.get(ResearchHistory, "sibling").status = "in_progress"+ cascade_session.commit()++ assert delete_research_with_dependents(cascade_session, "owner")+ assert delete_research_with_dependents(cascade_session, "sibling") is False+ cascade_session.commit()+ cascade_session.expire_all()++ assert cascade_session.get(ResearchHistory, "owner") is None+ assert cascade_session.get(ResearchHistory, "sibling") is not None+ assert (+ cascade_session.get(DownloadTracker, tracker_id).first_resource_id+ == resources[2]+ )+ assert cascade_session.query(ResearchResource).count() == 1+ assert cascade_session.query(DownloadDuplicates).count() == 1+ assert cascade_session.query(DownloadAttempt).count() == 1+++def _add_research(session, research_id):+ session.add(+ ResearchHistory(+ id=research_id,+ query="q",+ mode="quick",+ status="completed",+ created_at=_NOW,+ )+ )+ session.flush()+++def _add_resource(session, research_id, url):+ resource = ResearchResource(+ research_id=research_id,+ title="source",+ url=url,+ source_type="web",+ created_at=_NOW,+ )+ session.add(resource)+ session.flush()+ return resource.id+++ ("owner_url", "sibling_url"),+ [+ ("https://arxiv.org/pdf/2401.12345", "http://arxiv.org/pdf/2401.12345"),+ ("https://arxiv.org/pdf/1", "http://www.arxiv.org/pdf/1/"),+ ("https://x.org/q?b=2&a=1", "https://X.org/q?a=1&b=2"),+ ("https://\u00fc.org/\u00e4", "https://www.\u00fc.org/\u00c4/"),+ ("https://x.org/k", "https://x.org/\u212a"),+ ("https://x.org/a\x00b", "http://x.org/a\x00b"),+ ("https://x.org/a", "https://user:[email protected]/a"),+ ("https://x.org/a", "https://x.org:443/a"),+ ("https://x.org/a", "https://x.org/a#fragment"),+ ("https://x.org/a", "https://x.org/a?utm_source=mail"),+ (+ "https://x.org/q?Lang=fr&UserId=1&q=x",+ "https://x.org/q?q=x&lang=fr&userid=1",+ ),+ ],+ ids=[+ "scheme",+ "www-trailing-slash",+ "query-order-case",+ "non-ascii-uppercase-sibling",+ "kelvin-sign",+ "nul",+ "userinfo",+ "default-port",+ "fragment",+ "tracking-query",+ "mixed-case-query-order",+ ],+)+def test_tracker_shared_through_normalized_url_survives_owner_delete(+ cascade_session, owner_url, sibling_url+):+ """The download service reuses a tracker for any URL with the same+ normalized hash and records no duplicate row; deletion must agree."""+ assert download_url_hash(owner_url) == download_url_hash(sibling_url)+ _add_research(cascade_session, "owner")+ _add_research(cascade_session, "sibling")+ _add_research(cascade_session, "unrelated")+ owner_resource = _add_resource(cascade_session, "owner", owner_url)+ sibling_resource = _add_resource(cascade_session, "sibling", sibling_url)+ _add_resource(cascade_session, "unrelated", "https://other.org/x")+ url_hash = download_url_hash(owner_url)+ tracker = DownloadTracker(+ url=owner_url,+ url_hash=url_hash,+ first_resource_id=owner_resource,+ is_downloaded=True,+ )+ cascade_session.add(tracker)+ cascade_session.flush()+ tracker_id = tracker.id+ cascade_session.add(+ DownloadAttempt(url_hash=url_hash, attempt_number=1, succeeded=True)+ )+ cascade_session.commit()++ assert delete_research_with_dependents(cascade_session, "owner")+ cascade_session.commit()+ cascade_session.expire_all()++ tracker = cascade_session.get(DownloadTracker, tracker_id)+ assert tracker is not None+ assert tracker.first_resource_id == sibling_resource+ assert cascade_session.query(DownloadAttempt).count() == 1+++def test_research_without_trackers_does_not_scan_resources(cascade_session):+ """clear_history calls the helper once per research; a research that+ owns no tracker must not pay a scan of every research's resources."""+ for index in range(3):+ research_id = f"r{index}"+ _add_research(cascade_session, research_id)+ for source in range(3):+ _add_resource(+ cascade_session, research_id, f"https://s{index}.org/{source}"+ )+ cascade_session.commit()++ engine = cascade_session.get_bind()+ statements = []++ def capture(_conn, _cursor, statement, parameters, _context, _many):+ statements.append((statement, parameters))++ event.listen(engine, "before_cursor_execute", capture)+ try:+ assert _shared_download_replacements(cascade_session, "r1") == {}+ finally:+ event.remove(engine, "before_cursor_execute", capture)++ assert statements+ plan_rows = []+ for statement, parameters in statements:+ plan_rows.extend(+ row[-1]+ for row in cascade_session.connection().exec_driver_sql(+ "EXPLAIN QUERY PLAN " + statement, parameters+ )+ )+ assert not [+ row for row in plan_rows if row.startswith("SCAN research_resources")+ ], plan_rows++[email protected]("hash_index", [0, 1, 2])+def test_legacy_tracker_survives_owner_delete(cascade_session, hash_index):+ # Different casing keeps the stored URL unequal while all three legacy+ # hash spellings remain valid reader candidates. The main canonical hash+ # differs because it removes the fragment, default port and tracking key.+ owner_url = "https://www.x.org:443/A?b=2&a=1&utm_source=mail#page"+ sibling_url = owner_url.lower()+ hashes = get_legacy_url_hashes(owner_url)+ assert len(hashes) == 3+ url_hash = hashes[hash_index]+ assert url_hash != download_url_hash(sibling_url)+ assert url_hash in get_url_hash_candidates(sibling_url)+ _add_research(cascade_session, "owner")+ _add_research(cascade_session, "sibling")+ owner = _add_resource(cascade_session, "owner", owner_url)+ sibling = _add_resource(cascade_session, "sibling", sibling_url)+ tracker = DownloadTracker(+ url=owner_url, url_hash=url_hash, first_resource_id=owner+ )+ cascade_session.add(tracker)+ cascade_session.flush()+ tracker_id = tracker.id+ cascade_session.add(+ DownloadAttempt(url_hash=url_hash, attempt_number=1, succeeded=True)+ )+ cascade_session.commit()++ assert delete_research_with_dependents(cascade_session, "owner")+ cascade_session.commit()+ cascade_session.expire_all()+ tracker = cascade_session.get(DownloadTracker, tracker_id)+ assert tracker is not None+ assert tracker.first_resource_id == sibling+ assert tracker.url_hash == url_hash+ assert cascade_session.query(DownloadAttempt).count() == 1+++ "batch", [False, True], ids=["single", "clear-history"]+)+ "hash_indices",+ [(0,), (1,), (2,), (0, 1, 2)],+ ids=["raw", "download-service", "library-service", "all-legacy-spellings"],+)+def test_legacy_trackers_survive_canonical_reference(+ cascade_session, batch, hash_indices+):+ """Canonical references preserve legacy tracker IDs and attempt history."""+ owner_url = "https://www.x.org:443/A?b=2&a=1&utm_source=mail#page"+ sibling_url = "https://x.org/a?a=1&b=2"+ hashes = get_legacy_url_hashes(owner_url)+ assert len(hashes) == 3+ assert download_url_hash(owner_url) == download_url_hash(sibling_url)+ assert set(hashes).isdisjoint(get_url_hash_candidates(sibling_url))+ for name in ("owner", "sibling", "unrelated"):+ _add_research(cascade_session, name)+ owner = _add_resource(cascade_session, "owner", owner_url)+ # Create this first: a meaningful query difference must not take ownership.+ _add_resource(cascade_session, "unrelated", "https://x.org/a?a=1&b=3")+ sibling = _add_resource(cascade_session, "sibling", sibling_url)+ expected = []+ for hash_index in hash_indices:+ url_hash = hashes[hash_index]+ tracker = DownloadTracker(+ url=owner_url, url_hash=url_hash, first_resource_id=owner+ )+ cascade_session.add(tracker)+ cascade_session.flush()+ attempt = DownloadAttempt(+ url_hash=url_hash, attempt_number=1, succeeded=True+ )+ cascade_session.add(attempt)+ cascade_session.flush()+ expected.append((tracker.id, url_hash, attempt.id))+ cascade_session.commit()++ index = (+ SharedDownloadIndex.build(cascade_session, ["owner"]) if batch else None+ )+ assert delete_research_with_dependents(+ cascade_session, "owner", shared_downloads=index+ )+ cascade_session.commit()+ cascade_session.expire_all()++ for tracker_id, url_hash, attempt_id in expected:+ tracker = cascade_session.get(DownloadTracker, tracker_id)+ assert tracker is not None+ assert tracker.first_resource_id == sibling+ assert tracker.url == owner_url+ assert tracker.url_hash == url_hash+ attempt = cascade_session.get(DownloadAttempt, attempt_id)+ assert attempt is not None+ assert attempt.url_hash == url_hash+ assert attempt.attempt_number == 1+ assert attempt.succeeded is True+ assert cascade_session.query(DownloadTracker).count() == len(expected)+ assert cascade_session.query(DownloadAttempt).count() == len(expected)+++def test_different_query_does_not_preserve_tracker(cascade_session):+ for name in ("owner", "unrelated"):+ _add_research(cascade_session, name)+ url = "https://x.org/p?id=1"+ owner = _add_resource(cascade_session, "owner", url)+ _add_resource(cascade_session, "unrelated", "https://x.org/p?id=2")+ _add_tracker(cascade_session, url, owner)+ cascade_session.commit()+ assert delete_research_with_dependents(cascade_session, "owner")+ cascade_session.commit()+ assert cascade_session.query(DownloadTracker).count() == 0+ assert cascade_session.query(DownloadAttempt).count() == 0+++def test_download_url_hash_matches_download_service():+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )+ from local_deep_research.research_library.utils import get_url_hash++ for url in (+ "https://www.Example.com/a/?b=2&a=1",+ "http://x.org/p/",+ "https://\u00fc.org/\u00c4",+ "https://user:[email protected]:443/q?b=2&a=1&utm_source=mail#page",+ "https://x.org/q?q=x&Lang=fr&UserId=1",+ ):+ canonical = get_url_hash(url)+ assert download_url_hash(url) == canonical+ # The service must go through the shared formula, not restate it.+ service = DownloadService.__new__(DownloadService)+ assert service._get_url_hash(url) == download_url_hash(url) == canonical+++def _add_tracker(session, url, first_resource_id):+ url_hash = download_url_hash(url)+ tracker = DownloadTracker(+ url=url,+ url_hash=url_hash,+ first_resource_id=first_resource_id,+ is_downloaded=True,+ )+ session.add(tracker)+ session.flush()+ session.add(+ DownloadAttempt(url_hash=url_hash, attempt_number=1, succeeded=True)+ )+ return tracker.id+++def _capture_resource_scans(session):+ """Collect the plans of every statement until the returned stop()."""+ engine = session.get_bind()+ statements = []++ def capture(_conn, _cursor, statement, parameters, _context, _many):+ if statement.lstrip().upper().startswith("SELECT"):+ statements.append((statement, parameters))++ event.listen(engine, "before_cursor_execute", capture)++ def stop():+ event.remove(engine, "before_cursor_execute", capture)+ scans = 0+ for statement, parameters in statements:+ scans += sum(+ row[-1].startswith("SCAN research_resources")+ for row in session.connection().exec_driver_sql(+ "EXPLAIN QUERY PLAN " + statement, parameters+ )+ )+ return scans++ return stop+++def test_transaction_start_failure_preserves_research(cascade_session):+ _add_research(cascade_session, "owner")+ resource = _add_resource(cascade_session, "owner", _URL)+ tracker_id = _add_tracker(cascade_session, _URL, resource)+ cascade_session.commit()+ engine = cascade_session.get_bind()++ def refuse_begin(conn, cursor, statement, parameters, context, executemany):+ if statement == "BEGIN":+ raise RuntimeError("transaction unavailable")++ event.listen(engine, "before_cursor_execute", refuse_begin)+ try:+ with pytest.raises(RuntimeError, match="transaction unavailable"):+ delete_research_with_dependents(cascade_session, "owner")+ finally:+ event.remove(engine, "before_cursor_execute", refuse_begin)+ cascade_session.rollback()+ assert cascade_session.get(ResearchHistory, "owner") is not None+ assert cascade_session.get(DownloadTracker, tracker_id) is not None+ assert cascade_session.query(DownloadAttempt).count() == 1+++ "batch", [False, True], ids=["single", "clear-history"]+)+def test_concurrent_reference_keeps_download_history(+ tmp_path, monkeypatch, batch+):+ """A committed reference appearing after the lookup must survive.++ WAL permits the second connection to commit while deletion holds a read+ snapshot. A stale snapshot may force deletion to retry; committing a+ deletion that discards the new reference's history is never acceptable.+ """+ engine = create_engine(+ f"sqlite:///{tmp_path / 'concurrent-reference.db'}",+ connect_args={"isolation_level": "", "timeout": 1},+ )++ @event.listens_for(engine, "connect")+ def enable_foreign_keys(connection, _record):+ connection.execute("PRAGMA foreign_keys = ON")++ with engine.connect() as connection:+ assert (+ connection.exec_driver_sql("PRAGMA journal_mode=WAL").scalar()+ == "wal"+ )+ Base.metadata.create_all(engine)+ with Session(engine) as seed:+ _add_research(seed, "owner")+ owner = _add_resource(seed, "owner", _URL)+ tracker_id = _add_tracker(seed, _URL, owner)+ seed.commit()++ added = []++ def add_reference():+ with Session(engine) as writer:+ _add_research(writer, "new-sibling")+ added.append(_add_resource(writer, "new-sibling", _URL))+ writer.commit()++ lookup = research_cascade._tracker_references++ def lookup_then_insert(*args):+ result = lookup(*args)+ if not added:+ add_reference()+ return result++ monkeypatch.setattr(+ research_cascade, "_tracker_references", lookup_then_insert+ )+ try:+ with Session(engine) as deletion:+ index = (+ SharedDownloadIndex.build(deletion, ["owner"])+ if batch+ else None+ )+ try:+ deleted = delete_research_with_dependents(+ deletion, "owner", shared_downloads=index+ )+ deletion.commit()+ except OperationalError as exc:+ assert "database is locked" in str(exc)+ deletion.rollback()+ deleted = False++ deletion.expire_all()+ tracker = deletion.get(DownloadTracker, tracker_id)+ assert tracker is not None, (+ "A new reference lost its shared tracker"+ )+ assert deletion.query(DownloadAttempt).count() == 1+ assert deletion.get(ResearchResource, added[0]) is not None+ if not deleted:+ # Rebuilding after the stale-snapshot refusal must make progress.+ deletion.rollback()+ assert delete_research_with_dependents(deletion, "owner")+ deletion.commit()+ deletion.expire_all()+ tracker = deletion.get(DownloadTracker, tracker_id)+ assert tracker.first_resource_id == added[0]+ assert deletion.get(ResearchHistory, "owner") is None+ assert deletion.query(DownloadAttempt).count() == 1+ finally:+ engine.dispose()+++def test_batch_delete_scans_resources_once(cascade_session):+ """clear_history deletes many tracker-owning researches in one write+ transaction; the shared-download lookup must scan research_resources+ once for the whole batch, not once per research."""+ research_ids = [f"r{index}" for index in range(4)]+ for research_id in [*research_ids, "keeper"]:+ _add_research(cascade_session, research_id)+ for index, research_id in enumerate(research_ids):+ owned = _add_resource(+ cascade_session, research_id, f"https://s.org/{index}"+ )+ _add_tracker(cascade_session, f"https://s.org/{index}", owned)+ _add_resource(cascade_session, "keeper", f"http://s.org/{index}/")+ cascade_session.commit()++ stop = _capture_resource_scans(cascade_session)+ index = SharedDownloadIndex.build(cascade_session, research_ids)+ for research_id in research_ids:+ assert delete_research_with_dependents(+ cascade_session, research_id, shared_downloads=index+ )+ scans = stop()+ cascade_session.commit()++ assert scans == 1+ assert cascade_session.query(DownloadTracker).count() == 4+ assert cascade_session.query(DownloadAttempt).count() == 4+ keeper_resources = {+ row.id+ for row in cascade_session.query(ResearchResource).filter_by(+ research_id="keeper"+ )+ }+ assert {+ tracker.first_resource_id+ for tracker in cascade_session.query(DownloadTracker)+ } == keeper_resources++[email protected]("refused", [False, True])+def test_batch_hands_tracker_between_members(cascade_session, refused):+ """A tracker handed to a later batch member moves again when that+ member is deleted, and stays with it when its delete is refused. A+ protected research outside the batch keeps the tracker in the end."""+ for research_id in ("owner", "middle", "protected"):+ _add_research(cascade_session, research_id)+ owner_resource = _add_resource(cascade_session, "owner", _URL)+ middle_resource = _add_resource(cascade_session, "middle", _URL)+ protected_resource = _add_resource(+ cascade_session, "protected", "http://www.example.com/shared.pdf"+ )+ tracker_id = _add_tracker(cascade_session, _URL, owner_resource)+ if refused:+ cascade_session.get(ResearchHistory, "middle").status = "in_progress"+ cascade_session.commit()++ index = SharedDownloadIndex.build(cascade_session, ["owner", "middle"])+ assert delete_research_with_dependents(+ cascade_session, "owner", shared_downloads=index+ )+ assert (+ cascade_session.query(DownloadTracker.first_resource_id).scalar()+ == middle_resource+ )+ assert delete_research_with_dependents(+ cascade_session, "middle", shared_downloads=index+ ) is (not refused)+ cascade_session.commit()+ cascade_session.expire_all()++ tracker = cascade_session.get(DownloadTracker, tracker_id)+ assert tracker.first_resource_id == (+ middle_resource if refused else protected_resource+ )+ assert cascade_session.query(DownloadAttempt).count() == 1+++def test_batch_index_looks_up_tracker_created_after_build(cascade_session):+ for research_id in ("owner", "sibling"):+ _add_research(cascade_session, research_id)+ owner_resource = _add_resource(cascade_session, "owner", _URL)+ sibling_resource = _add_resource(+ cascade_session, "sibling", "http://example.com/shared.pdf"+ )+ cascade_session.commit()++ index = SharedDownloadIndex.build(cascade_session, ["owner"])+ tracker_id = _add_tracker(cascade_session, _URL, owner_resource)+ cascade_session.commit()++ assert delete_research_with_dependents(+ cascade_session, "owner", shared_downloads=index+ )+ cascade_session.commit()+ assert (+ cascade_session.get(DownloadTracker, tracker_id).first_resource_id+ == sibling_resource+ )+++def _random_library(session, seed):+ """Researches citing overlapping URL variants, some trackers, some+ recorded duplicates and some in-progress (refused) researches."""+ rng = random.Random(seed)+ variants = [+ "https://a.org/p",+ "http://www.a.org/p/",+ "https://A.org/p",+ "https://b.org/q?x=1&y=2",+ "https://b.org/q?y=2&x=1",+ "https://\u00fc.org/\u00e4",+ "https://\u00fc.org/\u00c4",+ "https://user:[email protected]:443/q?b=2&a=1&utm_source=mail#page",+ "https://x.org/q?q=x&Lang=fr&UserId=1",+ "https://c.org/r",+ ]+ research_ids = [f"r{index}" for index in range(rng.randint(2, 6))]+ for research_id in research_ids:+ _add_research(session, research_id)+ if rng.random() < 0.25:+ session.get(ResearchHistory, research_id).status = "in_progress"+ resources = []+ for research_id in research_ids:+ for url in rng.sample(variants, rng.randint(1, 4)):+ resources.append(+ (_add_resource(session, research_id, url), research_id, url)+ )+ trackers = {}+ for resource_id, research_id, url in resources:+ url_hash = download_url_hash(url)+ if url_hash not in trackers and rng.random() < 0.7:+ trackers[url_hash] = _add_tracker(session, url, resource_id)+ elif url_hash in trackers and rng.random() < 0.3:+ session.add(+ DownloadDuplicates(+ url_hash=url_hash,+ resource_id=resource_id,+ research_id=research_id,+ )+ )+ session.commit()+ batch = [rid for rid in research_ids if rng.random() < 0.8]+ rng.shuffle(batch)+ return batch+++def _final_state(session):+ return (+ sorted(+ session.query(+ DownloadTracker.id, DownloadTracker.first_resource_id+ ).all()+ ),+ sorted(session.query(DownloadAttempt.url_hash).all()),+ sorted(session.query(DownloadDuplicates.resource_id).all()),+ sorted(session.query(ResearchHistory.id).all()),+ )++[email protected]("in_chunk", [500, 1])+def test_batch_index_matches_per_research_lookup(monkeypatch, in_chunk):+ """One index for the batch must choose the same owners as a fresh+ per-research scan, including with chunked IN lists and without the+ SQL pre-filter (in_chunk=1)."""++ def run(seed, batched):+ engine = create_engine("sqlite://")++ @event.listens_for(engine, "connect")+ def enable_foreign_keys(connection, _record):+ connection.execute("PRAGMA foreign_keys = ON")++ Base.metadata.create_all(engine)+ with Session(engine) as session:+ batch = _random_library(session, seed)+ index = (+ SharedDownloadIndex.build(session, batch) if batched else None+ )+ for research_id in batch:+ delete_research_with_dependents(+ session, research_id, shared_downloads=index+ )+ session.commit()+ state = _final_state(session)+ engine.dispose()+ return state++ for seed in range(40):+ expected = run(seed, batched=False)+ monkeypatch.setattr(research_cascade, "_IN_CHUNK", in_chunk)+ assert run(seed, batched=True) == expected, seed+ monkeypatch.setattr(research_cascade, "_IN_CHUNK", 500)diff --git a/tests/database/test_shared_document_lifetime.py b/tests/database/test_shared_document_lifetime.pynew file mode 100644index 0000000000..2bb4f3fa23--- /dev/null+++ b/tests/database/test_shared_document_lifetime.py@@ -0,0 +1,657 @@+"""Shared library content must outlive any one referencing research."""++from contextlib import contextmanager+from datetime import UTC, datetime+from hashlib import sha256+import sqlite3++import pytest+from sqlalchemy import MetaData, create_engine, event+from sqlalchemy.exc import OperationalError+from sqlalchemy.orm import Session++from local_deep_research.database import research_cascade+from local_deep_research.database.models import (+ Base,+ QueuedResearch,+ ResearchHistory,+ ResearchResource,+)+from local_deep_research.database.models.library import (+ Collection,+ Document,+ DocumentBlob,+ DocumentChunk,+ DocumentCollection,+ EmbeddingProvider,+ RAGIndex,+ RagDocumentStatus,+ SourceType,+)+from local_deep_research.database.research_cascade import (+ SharedDownloadIndex,+ delete_research_with_dependents,+)+from local_deep_research.research_library.deletion.utils.cascade_helper import (+ CascadeHelper,+)+++NOW = datetime(2026, 10, 1, tzinfo=UTC)+PDF = b"%PDF-1.4 stored canonical paper"+BODY = "Complete canonical paper text."+++ params=["SET NULL", "CASCADE"], ids=["current", "legacy-resource-fk"]+)+def database(tmp_path, request):+ engine = create_engine(+ f"sqlite:///{tmp_path / 'shared-documents.sqlite'}",+ connect_args={"isolation_level": "", "timeout": 1},+ )++ @event.listens_for(engine, "connect")+ def enable_foreign_keys(connection, _record):+ connection.execute("PRAGMA foreign_keys=ON")++ # Clone metadata rather than mutating the production models or another+ # test's cached cascade plan. Only the historical resource FK differs.+ schema = MetaData()+ for table in Base.metadata.tables.values():+ table.to_metadata(schema)+ for constraint in schema.tables["documents"].foreign_key_constraints:+ if tuple(constraint.column_keys) == ("resource_id",):+ constraint.ondelete = request.param+ with engine.connect() as connection:+ assert (+ connection.exec_driver_sql("PRAGMA journal_mode=WAL").scalar()+ == "wal"+ )+ # Group schema setup; legacy SQLite otherwise commits each DDL alone.+ # The sessions under test still start with their normal driver behavior.+ connection.exec_driver_sql("BEGIN")+ schema.create_all(connection)+ connection.commit()+ resource_fk = next(+ row+ for row in connection.exec_driver_sql(+ "PRAGMA foreign_key_list(documents)"+ )+ if row[3] == "resource_id"+ )+ assert resource_fk[6] == request.param+ try:+ yield engine+ finally:+ engine.dispose()+++def seed_family(engine, *, references=True):+ with Session(engine) as session:+ session.add(+ SourceType(+ id="source", name="research_download", display_name="Research"+ )+ )+ for research_id in ("owner", "sibling", "last"):+ session.add(+ ResearchHistory(+ id=research_id,+ query="q",+ mode="quick",+ status="completed",+ created_at=NOW.isoformat(),+ )+ )+ session.add_all(+ [+ Collection(id="library", name="Library"),+ Collection(id="selected", name="Selected"),+ ]+ )+ session.flush()+ resources = {}+ for research_id in ("owner", "sibling", "last"):+ resource = ResearchResource(+ research_id=research_id,+ title="Shared paper",+ url=f"https://example.org/{research_id}.pdf",+ source_type="academic",+ created_at=NOW.isoformat(),+ )+ session.add(resource)+ session.flush()+ resources[research_id] = resource.id+ session.add(+ Document(+ id="canonical",+ source_type_id="source",+ resource_id=resources["owner"],+ research_id="owner",+ document_hash=sha256(PDF).hexdigest(),+ title="Shared paper",+ original_url="https://example.org/owner.pdf",+ file_type="pdf",+ file_path="database",+ storage_mode="database",+ file_size=len(PDF),+ text_content=BODY,+ word_count=len(BODY.split()),+ character_count=len(BODY),+ extraction_method="html_extraction",+ extraction_source="arxiv_html",+ extraction_quality="high",+ processed_at=NOW,+ )+ )+ # A document with no surviving reference must retain ordinary cascade+ # behavior; the shared-document exception must not preserve everything.+ session.add(+ Document(+ id="unshared",+ source_type_id="source",+ research_id="owner",+ document_hash="unshared",+ file_size=16,+ file_type="text",+ text_content="Private to owner",+ )+ )+ session.flush()+ session.add(+ DocumentBlob(+ document_id="canonical",+ pdf_binary=PDF,+ blob_hash=sha256(PDF).hexdigest(),+ )+ )+ if references:+ for research_id in ("sibling", "last"):+ session.get(+ ResearchResource, resources[research_id]+ ).document_id = "canonical"+ for collection_id in ("library", "selected"):+ index = RAGIndex(+ collection_name=f"collection_{collection_id}",+ embedding_model="test",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ embedding_dimension=2,+ index_path=f"/{collection_id}.faiss",+ index_hash=collection_id,+ chunk_size=100,+ chunk_overlap=0,+ )+ session.add(index)+ session.flush()+ session.add_all(+ [+ DocumentCollection(+ document_id="canonical",+ collection_id=collection_id,+ indexed=True,+ chunk_count=1,+ last_indexed_at=NOW,+ ),+ RagDocumentStatus(+ document_id="canonical",+ collection_id=collection_id,+ rag_index_id=index.id,+ chunk_count=1,+ indexed_at=NOW,+ ),+ DocumentChunk(+ chunk_hash=collection_id,+ source_type="document",+ source_id="canonical",+ collection_name=f"collection_{collection_id}",+ chunk_text=BODY,+ chunk_index=0,+ start_char=0,+ end_char=len(BODY),+ word_count=len(BODY.split()),+ embedding_id=collection_id,+ embedding_model="test",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ ),+ ]+ )+ session.commit()+ return resources+++def assert_preserved(session, research_id, resource_id):+ session.expire_all()+ doc = session.get(Document, "canonical")+ assert doc is not None+ assert (doc.research_id, doc.resource_id) == (research_id, resource_id)+ assert (+ session.get(ResearchResource, resource_id).research_id+ == doc.research_id+ )+ assert doc.text_content == BODY+ assert doc.document_hash == sha256(PDF).hexdigest()+ assert doc.extraction_source == "arxiv_html"+ assert doc.extraction_quality == "high"+ assert doc.original_url == "https://example.org/owner.pdf"+ assert (doc.file_path, doc.storage_mode, doc.file_size) == (+ "database",+ "database",+ len(PDF),+ )+ assert session.get(DocumentBlob, doc.id).pdf_binary == PDF+ links = (+ session.query(DocumentCollection).filter_by(document_id=doc.id).all()+ )+ assert {+ (+ link.collection_id,+ link.indexed,+ link.chunk_count,+ link.last_indexed_at,+ )+ for link in links+ } == {(collection, True, 1, NOW) for collection in ("library", "selected")}+ assert (+ session.query(RagDocumentStatus).filter_by(document_id=doc.id).count()+ == 2+ )+ assert {+ (row.embedding_id, row.chunk_text)+ for row in session.query(DocumentChunk).filter_by(source_id=doc.id)+ } == {("library", BODY), ("selected", BODY)}+ assert (+ session.connection().exec_driver_sql("PRAGMA foreign_key_check").all()+ == []+ )++[email protected]("deleted", ["owner", "sibling"])+def test_other_research_keeps_document_and_all_stored_content(+ database, deleted+):+ resources = seed_family(database)+ with Session(database) as session:+ assert delete_research_with_dependents(session, deleted)+ session.commit()+ remaining_owner = "sibling" if deleted == "owner" else "owner"+ assert_preserved(session, remaining_owner, resources[remaining_owner])+ assert session.get(ResearchHistory, deleted) is None+ assert (+ session.get(ResearchResource, resources["last"]).document_id+ == "canonical"+ )+ if deleted == "owner":+ assert session.get(Document, "unshared") is None++[email protected]("order", [("owner", "sibling"), ("sibling", "owner")])+def test_clear_history_transfers_to_surviving_research(database, order):+ resources = seed_family(database)+ with Session(database) as session:+ index = SharedDownloadIndex.build(session, order)+ for research_id in order:+ assert delete_research_with_dependents(+ session, research_id, shared_downloads=index+ )+ session.commit()+ assert_preserved(session, "last", resources["last"])+ assert (+ session.get(ResearchResource, resources["last"]).document_id+ == "canonical"+ )+++def test_last_reference_keeps_existing_document_cascade(database):+ seed_family(database)+ with Session(database) as session:+ index = SharedDownloadIndex.build(session, ["owner", "sibling", "last"])+ for research_id in ("owner", "sibling", "last"):+ assert delete_research_with_dependents(+ session, research_id, shared_downloads=index+ )+ session.commit()+ for model in (+ ResearchHistory,+ ResearchResource,+ Document,+ DocumentBlob,+ DocumentCollection,+ RagDocumentStatus,+ ):+ assert session.query(model).count() == 0++[email protected]("guard", ["status", "queue"])+def test_guard_refusal_restores_ownership_and_content(database, guard):+ resources = seed_family(database)+ with Session(database) as session:+ if guard == "status":+ session.get(ResearchHistory, "owner").status = "in_progress"+ else:+ session.add(+ QueuedResearch(+ username="test",+ research_id="owner",+ query="q",+ mode="quick",+ position=1,+ is_processing=True,+ created_at=NOW,+ )+ )+ session.commit()+ assert not delete_research_with_dependents(session, "owner")+ session.commit()+ assert_preserved(session, "owner", resources["owner"])+ assert session.get(Document, "unshared") is not None+ assert session.query(ResearchHistory).count() == 3+++def test_caller_rollback_restores_transferred_owner(database):+ resources = seed_family(database)+ with Session(database) as session:+ index = SharedDownloadIndex.build(session, ["owner", "sibling"])+ for research_id in ("owner", "sibling"):+ assert delete_research_with_dependents(+ session, research_id, shared_downloads=index+ )+ session.rollback()+ with Session(database) as verification:+ assert_preserved(verification, "owner", resources["owner"])+ assert verification.query(ResearchHistory).count() == 3+ assert (+ verification.get(ResearchResource, resources["sibling"]).document_id+ == "canonical"+ )++[email protected]("failure_stage", ["transfer", "parent-delete"])+def test_failed_transfer_rolls_back_deletion(database, failure_stage):+ resources = seed_family(database)++ def fail_owner_change(_conn, _cursor, statement, *_args):+ if (+ failure_stage == "transfer"+ and statement.startswith("UPDATE documents SET")+ and "research_id=" in statement+ ) or (+ failure_stage == "parent-delete"+ and statement.startswith("DELETE FROM research_history")+ ):+ raise RuntimeError("controlled ownership write failure")++ event.listen(database, "before_cursor_execute", fail_owner_change)+ try:+ with Session(database) as session:+ with pytest.raises(+ RuntimeError, match="controlled ownership write failure"+ ):+ delete_research_with_dependents(session, "owner")+ session.rollback()+ finally:+ event.remove(database, "before_cursor_execute", fail_owner_change)+ with Session(database) as verification:+ assert_preserved(verification, "owner", resources["owner"])+ assert verification.query(ResearchHistory).count() == 3+++def test_explicit_document_database_delete_remains_global(database):+ resources = seed_family(database)+ with Session(database) as session:+ assert CascadeHelper.delete_document_completely(session, "canonical")+ session.commit()+ assert session.get(Document, "canonical") is None+ assert session.get(DocumentBlob, "canonical") is None+ assert session.query(ResearchHistory).count() == 3+ for research_id in ("sibling", "last"):+ assert (+ session.get(+ ResearchResource, resources[research_id]+ ).document_id+ is None+ )+++def test_batch_retains_document_with_protected_successor(database):+ resources = seed_family(database)+ with Session(database) as session:+ session.get(ResearchHistory, "sibling").status = "in_progress"+ session.commit()+ index = SharedDownloadIndex.build(session, ["owner", "sibling", "last"])+ assert delete_research_with_dependents(+ session, "owner", shared_downloads=index+ )+ assert not delete_research_with_dependents(+ session, "sibling", shared_downloads=index+ )+ assert delete_research_with_dependents(+ session, "last", shared_downloads=index+ )+ session.commit()+ assert_preserved(session, "sibling", resources["sibling"])+ assert session.query(ResearchHistory).count() == 1++[email protected]("batch", [False, True], ids=["single", "batch"])[email protected]("change", ["add", "remove"])+def test_concurrent_references_require_fresh_deletion_snapshot(+ database, monkeypatch, batch, change+):+ resources = seed_family(database, references=change == "remove")+ lookup = research_cascade._shared_document_replacements+ changed = False++ def change_after_lookup(*args):+ nonlocal changed+ result = lookup(*args)+ if not changed:+ changed = True+ with Session(database) as writer:+ for research_id in ("sibling", "last"):+ writer.get(+ ResearchResource, resources[research_id]+ ).document_id = "canonical" if change == "add" else None+ writer.commit()+ return result++ monkeypatch.setattr(+ research_cascade, "_shared_document_replacements", change_after_lookup+ )+ with Session(database) as deletion:+ index = (+ SharedDownloadIndex.build(deletion, ["owner"]) if batch else None+ )+ with pytest.raises(OperationalError, match="database is locked"):+ delete_research_with_dependents(+ deletion, "owner", shared_downloads=index+ )+ deletion.rollback()+ assert changed+ with Session(database) as verification:+ assert_preserved(verification, "owner", resources["owner"])+ assert verification.get(ResearchHistory, "owner") is not None+ expected = "canonical" if change == "add" else None+ assert (+ verification.get(+ ResearchResource, resources["sibling"]+ ).document_id+ == expected+ )++ # The retry must follow the committed references rather than its old+ # retention decision, in either direction and with a fresh batch index.+ index = (+ SharedDownloadIndex.build(deletion, ["owner"]) if batch else None+ )+ assert delete_research_with_dependents(+ deletion, "owner", shared_downloads=index+ )+ deletion.commit()+ if change == "add":+ assert_preserved(deletion, "sibling", resources["sibling"])+ else:+ assert deletion.get(Document, "canonical") is None+ assert deletion.get(DocumentBlob, "canonical") is None+ assert deletion.get(ResearchHistory, "owner") is None+ assert deletion.get(ResearchHistory, "sibling") is not None+++def route_session(database, monkeypatch):+ from local_deep_research.web.routers import research++ # Match the production context: a thread reuses its Session, but a failed+ # outer scope rolls back before another operation may use it.+ with Session(database) as session:++ @contextmanager+ def context(_username):+ try:+ yield session+ finally:+ if session.in_transaction():+ session.rollback()++ monkeypatch.setattr(research, "get_user_db_session", context)+ monkeypatch.setattr(+ research, "get_active_research_ids", lambda: {"sibling", "last"}+ )+ yield session+++def call_delete_route(batch):+ from local_deep_research.web.routers import research++ if batch:+ return research.clear_history(request=None, username="test-user")+ return research.delete_research(+ request=None, research_id="owner", username="test-user"+ )++[email protected]("batch", [False, True], ids=["single", "batch"])[email protected]("change", ["add", "remove"])+def test_routes_retry_changed_document_references(+ database, route_session, monkeypatch, batch, change+):+ resources = seed_family(database, references=change == "remove")+ lookup = research_cascade._shared_document_replacements+ lookups = 0++ def change_after_lookup(*args):+ nonlocal lookups+ result = lookup(*args)+ lookups += 1+ if lookups == 1:+ with Session(database) as writer:+ for research_id in ("sibling", "last"):+ writer.get(+ ResearchResource, resources[research_id]+ ).document_id = "canonical" if change == "add" else None+ writer.commit()+ return result++ monkeypatch.setattr(+ research_cascade, "_shared_document_replacements", change_after_lookup+ )+ assert call_delete_route(batch) == {"status": "success"}+ assert lookups == 2+ assert not route_session.in_transaction()+ with Session(database) as verification:+ assert verification.get(ResearchHistory, "owner") is None+ assert verification.get(ResearchHistory, "sibling") is not None+ if change == "add":+ assert_preserved(verification, "sibling", resources["sibling"])+ else:+ assert verification.get(Document, "canonical") is None+ assert verification.get(DocumentBlob, "canonical") is None++[email protected]("batch", [False, True], ids=["single", "batch"])+def test_retry_rechecks_a_research_claimed_by_another_writer(+ database, route_session, monkeypatch, batch+):+ resources = seed_family(database)+ lookup = research_cascade._shared_document_replacements+ changed = False++ def claim_after_lookup(*args):+ nonlocal changed+ result = lookup(*args)+ if not changed:+ changed = True+ with Session(database) as writer:+ writer.get(ResearchHistory, "owner").status = "in_progress"+ writer.commit()+ return result++ monkeypatch.setattr(+ research_cascade, "_shared_document_replacements", claim_after_lookup+ )+ response = call_delete_route(batch)+ if batch:+ assert response == {"status": "success"}+ else:+ assert response.status_code == 400+ assert changed+ with Session(database) as verification:+ assert (+ verification.get(ResearchHistory, "owner").status == "in_progress"+ )+ assert_preserved(verification, "owner", resources["owner"])++[email protected]("batch", [False, True], ids=["single", "batch"])[email protected]("failure", ["transient-lock", "persistent-lock", "io"])+def test_report_file_survives_until_deletion_commits(+ database, route_session, monkeypatch, tmp_path, batch, failure+):+ from local_deep_research.config import paths++ resources = seed_family(database)+ report = tmp_path / "research-report.md"+ report.write_text("Retain the report when its database deletion fails.")+ monkeypatch.setattr(+ paths, "get_research_outputs_directory", lambda: tmp_path+ )+ with Session(database) as writer:+ writer.get(ResearchHistory, "owner").report_path = str(report)+ writer.commit()++ real_commit = route_session.commit+ attempts = 0++ def commit():+ nonlocal attempts+ attempts += 1+ # This is a real file: even an ultimately successful retry must not+ # remove it before the successful database commit.+ assert report.is_file()+ if failure == "persistent-lock" or attempts == 1:+ message = (+ "disk I/O error" if failure == "io" else "database is locked"+ )+ raise OperationalError(+ "COMMIT", None, sqlite3.OperationalError(message)+ )+ real_commit()++ monkeypatch.setattr(route_session, "commit", commit)+ response = call_delete_route(batch)+ if failure == "transient-lock":+ assert response == {"status": "success"}+ assert attempts == 2+ assert not report.exists()+ with Session(database) as verification:+ assert verification.get(ResearchHistory, "owner") is None+ else:+ assert response.status_code == 500+ assert attempts == (3 if failure == "persistent-lock" else 1)+ assert (+ report.read_text()+ == "Retain the report when its database deletion fails."+ )+ with Session(database) as verification:+ assert verification.get(ResearchHistory, "owner") is not None+ assert_preserved(verification, "owner", resources["owner"])diff --git a/tests/research_library/deletion/utils/test_cascade_helper.py b/tests/research_library/deletion/utils/test_cascade_helper.pyindex 8749fe44cd..a1ecd7d7d8 100644--- a/tests/research_library/deletion/utils/test_cascade_helper.py+++ b/tests/research_library/deletion/utils/test_cascade_helper.py@@ -374,9 +374,12 @@ class TestCascadeHelperUpdateDownloadTracker:mock_tracker = MagicMock()mock_session.query.return_value.filter_by.return_value.first.return_value = mock_tracker- # Mock get_url_hash at the correct location (inside the method)+ # Patch where update_download_tracker's call chain reads it:+ # find_tracker_by_url -> get_url_hash_candidates resolves+ # get_url_hash from utilities.download_url module globals, not+ # from the research_library.utils re-export shim.with patch(- "local_deep_research.research_library.utils.get_url_hash",+ "local_deep_research.utilities.download_url.get_url_hash",return_value="abc123",):result = CascadeHelper.update_download_tracker(diff --git a/tests/research_library/deletion/utils/test_cascade_helper_coverage.py b/tests/research_library/deletion/utils/test_cascade_helper_coverage.pyindex 459f24d567..18ffe9a7a7 100644--- a/tests/research_library/deletion/utils/test_cascade_helper_coverage.py+++ b/tests/research_library/deletion/utils/test_cascade_helper_coverage.py@@ -145,7 +145,7 @@ class TestUpdateDownloadTrackerNoTracker:mock_doc.original_url = "https://example.com/paper.pdf"with patch(- "local_deep_research.research_library.utils.get_url_hash",+ "local_deep_research.utilities.download_url.get_url_hash",return_value="abc123",):result = CascadeHelper.update_download_tracker(@@ -160,7 +160,7 @@ class TestUpdateDownloadTrackerNoTracker:mock_doc.original_url = "https://example.com/paper.pdf"with patch(- "local_deep_research.research_library.utils.get_url_hash",+ "local_deep_research.utilities.download_url.get_url_hash",side_effect=Exception("hash error"),):result = CascadeHelper.update_download_tracker(diff --git a/tests/web/routers/test_delete_research_cascade.py b/tests/web/routers/test_delete_research_cascade.pyindex 86e821962c..0e8e0902de 100644--- a/tests/web/routers/test_delete_research_cascade.py+++ b/tests/web/routers/test_delete_research_cascade.py@@ -8,26 +8,27 @@ rely on SQLite's ``ON DELETE CASCADE`` rules (set up by the model layerand enabled at connect time by ``apply_performance_pragmas``) to clean upthe rows in ``app_logs`` (model ``ResearchLog``),``research_resources``, etc. In-repo every FK on-``research_history.id`` is ``CASCADE``/``SET NULL`` from birth, so a-fresh schema never raises — the fix is defensive against out-of-repo-/ partial schemas where a child table's FK lacks ``ON DELETE-CASCADE``. With ``PRAGMA foreign_keys = ON`` that shape raises+``research_history.id`` is ``CASCADE``/``SET NULL`` from birth. Several+depth-2 download FKs use ``NO ACTION``, so downloaded sources can block+deletion even on a fresh schema. Partial schemas can also lack a+first-level ``ON DELETE CASCADE`` rule. With ``PRAGMA foreign_keys = ON``+that shape raises``FOREIGN KEY constraint failed`` and the route surfaces a 500 (withthe SQLite default of ``OFF`` the same delete succeeds silently andorphans rows instead — a separate orphaning mode the explicitdeletes also repair, but not the 500 discriminated here). The fix-performs the first-level cascade explicitly at the application layer;+derives a full descendant cascade from model metadata at the application layer;these tests pin six properties:1. **Coverage** — every model that declares an FK on``research_history.id`` is deleted (or, for the SET NULL FK on``chat_messages.research_id``, cleared). An introspection test- walks ``Base.metadata`` so a future FK that lands outside the- list fails CI.+ walks ``Base.metadata`` so every descendant FK is classified, and+ a missing survival policy for a declared SET NULL edge fails CI.2. **Robustness against partial schemas** — the route-level testsrebuild a CASCADE-bearing child table (``research_strategies``)*without* ``ON DELETE CASCADE``, mirroring the production- fragility. On ``main`` the route returns 500; on this branch it+ fragility. The old bulk-delete route returns 500; the explicit cascadeanswers 200 with the row gone. A negative-control class proves thesame broken behaviour still happens for the bulk-delete shape thatthe helper replaced.@@ -749,6 +750,113 @@ class TestClearHistoryRouteWithFKEnforcement:assert db_with_fk.query(ResearchResource).count() == 0+class TestClearHistorySharedDownloadIndex:+ """``clear_history`` must build one ``SharedDownloadIndex`` for the+ whole batch and hand it to every per-research delete; otherwise each+ tracker-owning research pays its own ``research_resources`` scan."""++ def test_route_builds_one_index_and_scans_resources_once(+ self, authenticated_client, db_with_fk+ ):+ from local_deep_research.database.models import (+ DownloadTracker,+ ResearchResource,+ )+ from local_deep_research.utilities.download_url import (+ get_url_hash as download_url_hash,+ )+ from local_deep_research.database.research_cascade import (+ SharedDownloadIndex,+ )++ _add_research(db_with_fk, "keeper", status="in_progress")+ ids = [f"r{index}" for index in range(4)]+ for index, rid in enumerate(ids):+ _add_research(db_with_fk, rid)+ url = f"https://s.org/{index}"+ owned = ResearchResource(+ research_id=rid,+ title="t",+ url=url,+ source_type="web",+ created_at=_NOW,+ )+ sibling = ResearchResource(+ research_id="keeper",+ title="t",+ url=f"http://s.org/{index}/",+ source_type="web",+ created_at=_NOW,+ )+ db_with_fk.add_all([owned, sibling])+ db_with_fk.flush()+ db_with_fk.add(+ DownloadTracker(+ url=url,+ url_hash=download_url_hash(url),+ first_resource_id=owned.id,+ is_downloaded=True,+ )+ )+ db_with_fk.commit()++ engine = db_with_fk.get_bind()+ selects = []++ def capture(_conn, _cursor, statement, parameters, _ctx, _many):+ if statement.lstrip().upper().startswith("SELECT"):+ selects.append((statement, parameters))++ built = []+ real_build = SharedDownloadIndex.build.__func__+ real_delete = __import__(+ "local_deep_research.database.research_cascade",+ fromlist=["delete_research_with_dependents"],+ ).delete_research_with_dependents+ passed = []++ def spy_build(cls, session, research_ids):+ index = real_build(cls, session, research_ids)+ built.append(index)+ return index++ def spy_delete(session, research_id, **kwargs):+ passed.append(kwargs.get("shared_downloads"))+ return real_delete(session, research_id, **kwargs)++ event.listen(engine, "before_cursor_execute", capture)+ try:+ with (+ _patch_session(db_with_fk),+ patch(f"{_RR}.get_active_research_ids", return_value=[]),+ patch(_LIFECYCLE_CLEANUP),+ patch.object(+ SharedDownloadIndex, "build", classmethod(spy_build)+ ),+ patch(f"{_RR}._delete_research_with_dependents", spy_delete),+ ):+ response = authenticated_client.post("/api/clear_history")+ finally:+ event.remove(engine, "before_cursor_execute", capture)++ assert response.status_code == 200, response.text[:300]+ assert len(built) == 1+ assert len(passed) == len(ids)+ assert all(index is built[0] for index in passed)++ scans = 0+ for statement, parameters in selects:+ scans += sum(+ row[-1].startswith("SCAN research_resources")+ for row in db_with_fk.connection().exec_driver_sql(+ "EXPLAIN QUERY PLAN " + statement, parameters+ )+ )+ assert scans == 1+ # Trackers survive, handed to the protected keeper's resources.+ assert db_with_fk.query(DownloadTracker).count() == len(ids)++# ---------------------------------------------------------------------------# Partial-schema discriminator — the test the original# ``test_delete_succeeds_when_child_tables_have_rows`` lacked. A@@ -1650,7 +1758,7 @@ class TestHelperCoverageBaseMetadata:return edgesdef test_every_fk_on_research_history_id_is_covered(self):- from local_deep_research.web.routers.research import (+ from local_deep_research.database.research_cascade import (_CASCADE_SET_NULL,_research_cascade_plan,)@@ -1737,3 +1845,34 @@ class TestHelperCoverageBaseMetadata:)assert callable(_delete_research_with_dependents)++ def test_survival_policy_matches_schema_set_null_edges(self):+ from local_deep_research.database.models import Base+ from local_deep_research.database.research_cascade import (+ _CASCADE_SET_NULL,+ )++ closure = set(self._closure_edges())+ schema_survivors = set()+ for table in Base.metadata.tables.values():+ for fk in table.foreign_keys:+ edge = (+ table.name,+ fk.parent.name,+ fk.column.table.name,+ fk.column.name,+ )+ if (+ edge in closure+ and (fk.ondelete or "").upper() == "SET NULL"+ ):+ assert fk.parent.nullable, (+ f"SET NULL on non-nullable {edge}"+ )+ schema_survivors.add((table.name, fk.parent.name))++ assert _CASCADE_SET_NULL == schema_survivors, (+ "research cascade survival policy differs from declared SET NULL "+ f"edges: missing {sorted(schema_survivors - _CASCADE_SET_NULL)}, "+ f"stale {sorted(_CASCADE_SET_NULL - schema_survivors)}"+ )diff --git a/tests/web/test_research_state_registry.py b/tests/web/test_research_state_registry.pyindex 2251bf8442..9b4e966682 100644--- a/tests/web/test_research_state_registry.py+++ b/tests/web/test_research_state_registry.py@@ -360,7 +360,11 @@ def test_the_census_enumerates_every_known_registry_call_site():"terminate_research","append_research_log",),- ("web/routers/research.py", "clear_history", "get_active_research_ids"),+ (+ "web/routers/research.py",+ "clear_history::clear_once",+ "get_active_research_ids",+ ),("web/routers/chat.py","send_message::_impl",