~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
test(queue): pin acting-user cleanup across research routes (#7707)
Chanhyo Jungf3bc70b0ebdb
diff --git a/tests/web/queue/test_queued_research_lifecycle_cleanup.py b/tests/web/queue/test_queued_research_lifecycle_cleanup.pyindex 4d91ecfb8c..e7c36a31b3 100644--- a/tests/web/queue/test_queued_research_lifecycle_cleanup.py+++ b/tests/web/queue/test_queued_research_lifecycle_cleanup.py@@ -250,6 +250,81 @@ def test_queue_rows_cannot_share_a_research_id(db_session: Session) -> None:db_session.commit()+def test_acting_user_cleanup_preserves_claimed_and_foreign_state(+ db_session: Session,+) -> None:+ # Given: requested IDs span owners and claims, with an own queue survivor.+ rows = [+ _queued_research("alice", "own-unclaimed", 2),+ _queued_research("alice", "own-claimed", 8, is_processing=True),+ _queued_research("alice", "own-survivor", 19),+ _queued_research("bob", "foreign-unclaimed", 7),+ _queued_research("bob", "foreign-claimed", 13, is_processing=True),+ ]+ for row in rows:+ row.settings_snapshot = {"query": row.query, "iterations": 3}+ db_session.add(+ _task_metadata(+ row.research_id,+ "processing" if row.is_processing else "queued",+ )+ )+ db_session.add_all(rows)+ db_session.add(QueueStatus(active_tasks=88, queued_tasks=99))+ db_session.commit()+ foreign_before = db_session.execute(+ QueuedResearch.__table__.select()+ .where(QueuedResearch.username == "bob")+ .order_by(QueuedResearch.id)+ ).all()+ protected_ids = {"own-claimed", "foreign-unclaimed", "foreign-claimed"}+ metadata_before = db_session.execute(+ TaskMetadata.__table__.select()+ .where(TaskMetadata.task_id.in_(protected_ids))+ .order_by(TaskMetadata.task_id)+ ).all()++ # When: ordinary actor-scoped cleanup excludes claimed work.+ result = cleanup_queued_research_state(+ db_session,+ ["own-unclaimed", *sorted(protected_ids)],+ include_claimed=False,+ acting_user="alice",+ )+ db_session.commit()+ db_session.expire_all()++ # Then: own unclaimed work is gone, and only the owner's positions compact.+ assert [+ (row.research_id, row.position, row.is_processing)+ for row in db_session.query(QueuedResearch)+ .filter_by(username="alice")+ .order_by(QueuedResearch.position)+ ] == [("own-claimed", 1, True), ("own-survivor", 2, False)]+ assert (+ db_session.execute(+ QueuedResearch.__table__.select()+ .where(QueuedResearch.username == "bob")+ .order_by(QueuedResearch.id)+ ).all()+ == foreign_before+ ), "foreign queue rows and payloads must survive unchanged"+ assert db_session.get(TaskMetadata, "own-unclaimed") is None+ assert db_session.get(TaskMetadata, "own-survivor") is not None+ assert (+ db_session.execute(+ TaskMetadata.__table__.select()+ .where(TaskMetadata.task_id.in_(protected_ids))+ .order_by(TaskMetadata.task_id)+ ).all()+ == metadata_before+ ), "protected task metadata must survive independently of queue rows"+ assert result.cleaned_ids == {"own-unclaimed"}+ assert result.protected_ids == protected_ids+ status = db_session.query(QueueStatus).one()+ assert (status.queued_tasks, status.active_tasks) == (2, 2)++def test_missing_parent_sweep_removes_orphans_without_retry_or_failure(db_session: Session,) -> None:diff --git a/tests/web/routers/test_research_cleanup_actor_scope.py b/tests/web/routers/test_research_cleanup_actor_scope.pynew file mode 100644index 0000000000..6278125bb0--- /dev/null+++ b/tests/web/routers/test_research_cleanup_actor_scope.py@@ -0,0 +1,219 @@+from contextlib import contextmanager+from inspect import signature+from unittest.mock import patch++import pytest+from sqlalchemy import create_engine, event+from sqlalchemy.orm import Session+from sqlalchemy.pool import StaticPool++from local_deep_research.database.models import (+ Base,+ QueuedResearch,+ ResearchHistory,+ TaskMetadata,+)+from local_deep_research.web.queue.lifecycle_cleanup import (+ cleanup_queued_research_state as real_cleanup,+)++_RR = "local_deep_research.web.routers.research"+_CLEANUP = (+ "local_deep_research.web.queue.lifecycle_cleanup."+ "cleanup_queued_research_state"+)+++def cleanup_db():+ engine = create_engine(+ "sqlite:///:memory:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )++ @event.listens_for(engine, "connect")+ def enable_foreign_keys(connection, _record):+ connection.execute("PRAGMA foreign_keys = ON")++ Base.metadata.create_all(engine)+ try:+ with Session(engine) as session:+ yield session+ finally:+ engine.dispose()+++def _patch_session(session: Session):+ @contextmanager+ def user_session(_username):+ yield session++ return patch(f"{_RR}.get_user_db_session", user_session)+++def _seed_queued(session: Session, username: str, research_id: str) -> None:+ session.add_all(+ [+ ResearchHistory(+ id=research_id,+ query=f"query for {research_id}",+ mode="quick",+ status="queued",+ created_at="2026-07-13T00:00:00+00:00",+ ),+ QueuedResearch(+ username=username,+ research_id=research_id,+ query=f"query for {research_id}",+ mode="quick",+ settings_snapshot={"iterations": 3},+ position=7,+ is_processing=False,+ ),+ TaskMetadata(+ task_id=research_id,+ task_type="research",+ status="queued",+ metadata_json={"research_id": research_id},+ ),+ ]+ )+ session.commit()+++def test_terminate_queued_cleanup_uses_authenticated_actor_and_unclaimed_policy(+ authenticated_client, cleanup_db: Session+) -> None:+ # Given: a real authenticated principal and its unclaimed queued research.+ auth = authenticated_client.get("/auth/check")+ assert auth.status_code == 200+ assert auth.json()["authenticated"] is True+ username = auth.json()["username"]+ _seed_queued(cleanup_db, username, "terminate-own")++ # When: the QUEUED success path calls through to the real cleanup helper.+ with (+ _patch_session(cleanup_db),+ patch(f"{_RR}.is_research_active", return_value=False),+ patch(f"{_RR}.set_termination_flag"),+ patch(_CLEANUP, wraps=real_cleanup) as cleanup,+ ):+ response = authenticated_client.post("/api/terminate/terminate-own")++ # Then: cleanup receives this principal and the effective default policy.+ assert response.status_code == 200, response.text+ assert response.json()["status"] == "success"+ cleanup.assert_called_once()+ bound = signature(real_cleanup).bind(+ *cleanup.call_args.args, **cleanup.call_args.kwargs+ )+ bound.apply_defaults()+ assert bound.arguments["db_session"] is cleanup_db+ assert bound.arguments["research_ids"] == ["terminate-own"]+ assert bound.arguments["acting_user"] == username, (+ "cleanup must use the authenticated actor"+ )+ assert bound.arguments["include_claimed"] is False, (+ "cleanup must exclude claimed work"+ )+ cleanup_db.expire_all()+ assert (+ cleanup_db.get(ResearchHistory, "terminate-own").status == "suspended"+ )+ assert cleanup_db.query(QueuedResearch).count() == 0+ assert cleanup_db.get(TaskMetadata, "terminate-own") is None+++def test_clear_history_cleanup_uses_authenticated_actor_and_unclaimed_policy(+ authenticated_client, cleanup_db: Session+) -> None:+ # Given: two deletable records owned by the authenticated principal.+ auth = authenticated_client.get("/auth/check")+ assert auth.status_code == 200+ assert auth.json()["authenticated"] is True+ username = auth.json()["username"]+ _seed_queued(cleanup_db, username, "clear-own-first")+ _seed_queued(cleanup_db, username, "clear-own-second")++ # When: clear_history deletes both parents and calls real queue cleanup.+ with (+ _patch_session(cleanup_db),+ patch(f"{_RR}.get_active_research_ids", return_value=[]),+ patch(f"{_RR}._unlink_report_file_if_inside_root"),+ patch(_CLEANUP, wraps=real_cleanup) as cleanup,+ ):+ response = authenticated_client.post("/api/clear_history")++ # Then: the caller supplies the actor and preserves the unclaimed-only policy.+ assert response.status_code == 200, response.text+ assert response.json()["status"] == "success"+ cleanup.assert_called_once()+ bound = signature(real_cleanup).bind(+ *cleanup.call_args.args, **cleanup.call_args.kwargs+ )+ bound.apply_defaults()+ assert bound.arguments["db_session"] is cleanup_db+ assert set(bound.arguments["research_ids"]) == {+ "clear-own-first",+ "clear-own-second",+ }+ assert bound.arguments["acting_user"] == username, (+ "cleanup must use the authenticated actor"+ )+ assert bound.arguments["include_claimed"] is False, (+ "cleanup must exclude claimed work"+ )+ cleanup_db.expire_all()+ assert cleanup_db.query(ResearchHistory).count() == 0+ assert cleanup_db.query(QueuedResearch).count() == 0+ assert cleanup_db.query(TaskMetadata).count() == 0+++def test_clear_history_real_cleanup_preserves_foreign_unclaimed_state(+ authenticated_client, cleanup_db: Session+) -> None:+ # Given: both parent IDs will reach cleanup in the injected synthetic DB.+ auth = authenticated_client.get("/auth/check")+ assert auth.status_code == 200+ assert auth.json()["authenticated"] is True+ username = auth.json()["username"]+ _seed_queued(cleanup_db, username, "clear-own")+ _seed_queued(cleanup_db, f"{username}-foreign", "clear-foreign")+ foreign_queue_before = cleanup_db.execute(+ QueuedResearch.__table__.select().where(+ QueuedResearch.research_id == "clear-foreign"+ )+ ).one()+ foreign_metadata_before = cleanup_db.execute(+ TaskMetadata.__table__.select().where(+ TaskMetadata.task_id == "clear-foreign"+ )+ ).one()++ # When: the real HTTP handler uses the original, unpatched cleanup helper.+ with (+ _patch_session(cleanup_db),+ patch(f"{_RR}.get_active_research_ids", return_value=[]),+ patch(f"{_RR}._unlink_report_file_if_inside_root"),+ ):+ response = authenticated_client.post("/api/clear_history")++ # Then: both parents were deleted, but cleanup preserves foreign private state.+ assert response.status_code == 200, response.text+ assert response.json()["status"] == "success"+ cleanup_db.expire_all()+ assert cleanup_db.query(ResearchHistory).count() == 0+ assert (+ cleanup_db.query(QueuedResearch)+ .filter_by(research_id="clear-own")+ .first()+ is None+ )+ assert cleanup_db.get(TaskMetadata, "clear-own") is None+ assert cleanup_db.execute(QueuedResearch.__table__.select()).all() == [+ foreign_queue_before+ ], "foreign unclaimed queue payload and position must survive"+ assert cleanup_db.execute(TaskMetadata.__table__.select()).all() == [+ foreign_metadata_before+ ], "foreign task metadata must survive independently of its queue row"