~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
# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for per-attempt delete + retry endpoints.
Issue #4659: when a chat-triggered research fails (OoM, crash, dead LLM
endpoint), the user message stays in the thread and there's no in-chat
way to retry without copy-pasting. The new endpoints
DELETE /api/chat/sessions/<sid>/attempts/<rid>
POST /api/chat/sessions/<sid>/attempts/<rid>/retry
let the client delete or re-run a single attempt atomically.
Coverage in this file:
- Service-level (``ChatService.delete_attempt`` /
``get_original_attempt_query``): happy path, missing, in-progress
refusal, stale-IN_PROGRESS reclaim, message_count decrement,
research_meta fallback.
- HTTP-level: happy paths, 404 / 409 mappings, CSRF enforcement,
concurrent-message 409 race via the partial unique index.
"""
import asyncio
import inspect
import json
import hashlib
import uuid
from datetime import datetime, UTC
from contextlib import contextmanager
from unittest.mock import MagicMock, patch
import pytest
from local_deep_research.chat.service import (
AttemptInProgress,
AttemptNotFound,
ChatService,
)
from local_deep_research.constants import ResearchStatus
from local_deep_research.database.models import (
ChatMessage,
ChatProgressStep,
ChatRole,
ChatSession,
ChatSessionStatus,
ResearchHistory,
UserActiveResearch,
)
# ---------------------------------------------------------------------------
# Seed helpers — used by both service-level and HTTP-level tests.
# ---------------------------------------------------------------------------
@contextmanager
def _service_db(SessionLocal):
"""Redirect ``ChatService.get_user_db_session`` to the test DB.
ChatService opens the per-user encrypted DB by username; the test
DB from ``setup_database_for_all_tests`` is a plain SQLite file.
Same pattern as ``tests/chat/test_chat_delete_terminates_research.py``.
"""
@contextmanager
def _managed_test_session():
with SessionLocal() as db:
yield db
with patch(
"local_deep_research.chat.service.get_user_db_session",
side_effect=lambda *_args, **_kwargs: _managed_test_session(),
):
yield
def _seed_attempt(
db,
username: str,
session_id: str,
research_id: str,
*,
research_status: str = ResearchStatus.FAILED.value,
user_content: str = "What is quantum computing?",
assistant_content: str | None = "Quantum computing uses qubits...",
include_research_meta: bool = True,
user_message_id: str | None = None,
):
"""Insert a full attempt (user msg + research + optional assistant msg).
Returns ``(user_message_id, assistant_message_id_or_None)``.
"""
# Look up the session to find the next sequence_number.
session = db.query(ChatSession).filter_by(id=session_id).first()
next_seq = (session.message_count if session else 0) + 1
user_msg_id = user_message_id or str(uuid.uuid4())
# Mirror production: _spawn_chat_research inserts the user message with
# research_id=NULL and links it to the attempt only via
# research_meta.submission.message_id. Only legacy rows that predate the
# research_meta field carried research_id on the user message — model
# those when include_research_meta is False so the fallback lookup path
# in get_original_attempt_query / delete_attempt stays exercised.
user_research_id = None if include_research_meta else research_id
db.add(
ChatMessage(
id=user_msg_id,
session_id=session_id,
research_id=user_research_id,
role=ChatRole.USER.value,
message_type="query",
content=user_content,
sequence_number=next_seq,
)
)
research_meta = None
if include_research_meta:
research_meta = {
"submission": {
"chat_session_id": session_id,
"message_id": user_msg_id,
"research_mode": "quick",
}
}
db.add(
ResearchHistory(
id=research_id,
query=user_content,
mode="quick",
status=research_status,
created_at=datetime.now(UTC).isoformat(),
chat_session_id=session_id,
research_meta=research_meta,
)
)
assistant_msg_id = None
if assistant_content is not None:
assistant_msg_id = str(uuid.uuid4())
db.add(
ChatMessage(
id=assistant_msg_id,
session_id=session_id,
research_id=research_id,
role=ChatRole.ASSISTANT.value,
message_type="response",
content=assistant_content,
sequence_number=next_seq + 1,
)
)
# A progress step tied to this research.
db.add(
ChatProgressStep(
id=str(uuid.uuid4()),
research_id=research_id,
session_id=session_id,
phase="search",
content="Searching...",
sequence_number=1,
)
)
# Bump session message_count to match what we inserted.
if session:
session.message_count = session.message_count + (
2 if assistant_content is not None else 1
)
db.commit()
return user_msg_id, assistant_msg_id
def _seed_attempt_document(db, research_id: str) -> tuple[str, str]:
"""Attach a library document with one indexed chunk to an attempt.
The research cascade deletes the document; its RAG data is purged
post-commit. Returns ``(document_id, collection_id)``.
"""
from local_deep_research.database.models import (
Collection,
Document,
DocumentChunk,
DocumentCollection,
SourceType,
)
from local_deep_research.database.models.library import (
EmbeddingProvider,
)
document_id = str(uuid.uuid4())
collection_id = str(uuid.uuid4())
chunk_text = "private chat research chunk"
source_type_id = str(uuid.uuid4())
db.add(
SourceType(
id=source_type_id,
name=source_type_id,
display_name="Research Download",
icon="download",
)
)
db.add(
Document(
id=document_id,
research_id=research_id,
source_type_id=source_type_id,
document_hash=f"hash-{document_id}",
file_size=len(chunk_text),
file_type="txt",
)
)
db.add(
Collection(
id=collection_id,
name=f"chat-{collection_id}",
collection_type="user_collection",
)
)
db.add(
DocumentCollection(
document_id=document_id,
collection_id=collection_id,
indexed=True,
chunk_count=1,
)
)
db.add(
DocumentChunk(
chunk_hash=hashlib.sha256(chunk_text.encode()).hexdigest(),
source_type="document",
source_id=document_id,
collection_name=f"collection_{collection_id}",
chunk_text=chunk_text,
chunk_index=0,
start_char=0,
end_char=len(chunk_text),
word_count=len(chunk_text.split()),
embedding_id=str(uuid.uuid4()),
embedding_model="fake-model",
embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
embedding_dimension=8,
)
)
db.commit()
return document_id, collection_id
def _make_session(db, username: str, title: str = "test chat") -> str:
session_id = str(uuid.uuid4())
db.add(
ChatSession(
id=session_id,
title=title,
status=ChatSessionStatus.ACTIVE.value,
message_count=0,
)
)
db.commit()
return session_id
# ===========================================================================
# Service-level: ChatService.delete_attempt
# ===========================================================================
class TestDeleteAttemptService:
"""Direct ChatService.delete_attempt tests."""
def test_delete_attempt_happy_path(self, setup_database_for_all_tests):
"""Deleting a FAILED attempt removes the user msg, assistant msg,
progress step, and research row; decrements message_count by 2."""
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_id = _make_session(db, username)
research_id = str(uuid.uuid4())
user_msg_id, assistant_msg_id = _seed_attempt(
db,
username,
session_id,
research_id,
research_status=ResearchStatus.FAILED.value,
)
# Sanity: 2 messages (user + assistant) + 1 step + 1 research
# exist. Count by session_id, NOT research_id — the user message
# is seeded with research_id=NULL (production behaviour), so a
# research_id filter would only see the assistant row.
assert (
db.query(ChatMessage).filter_by(session_id=session_id).count()
== 2
)
# Regression guard for #4659: the user message must be linked
# to the attempt only via research_meta, with research_id NULL.
user_row = db.query(ChatMessage).filter_by(id=user_msg_id).first()
assert user_row is not None
assert user_row.research_id is None
assert (
db.query(ChatProgressStep)
.filter_by(research_id=research_id)
.count()
== 1
)
with _service_db(SessionLocal):
result = service.delete_attempt(session_id, research_id)
assert result is True
with SessionLocal() as db:
# All attempt rows gone — including the NULL-research_id user
# message (the #4659 bug left it orphaned in the thread).
assert (
db.query(ChatMessage).filter_by(session_id=session_id).count()
== 0
)
assert (
db.query(ChatMessage).filter_by(id=user_msg_id).first() is None
)
assert (
db.query(ChatProgressStep)
.filter_by(research_id=research_id)
.count()
== 0
)
assert (
db.query(ResearchHistory).filter_by(id=research_id).first()
is None
)
# Session still exists and message_count was decremented.
session = db.query(ChatSession).filter_by(id=session_id).first()
assert session is not None
assert session.message_count == 0
def test_delete_attempt_purges_research_document_chunks_after_commit(
self, setup_database_for_all_tests
):
"""Chat teardown uses the same vector-before-chunk purge as history."""
from local_deep_research.database.models import (
Document,
DocumentChunk,
)
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
research_id = str(uuid.uuid4())
with SessionLocal() as db:
session_id = _make_session(db, username)
_seed_attempt(db, username, session_id, research_id)
document_id, collection_id = _seed_attempt_document(db, research_id)
events = []
class _Rag:
def __enter__(self):
return self
def __exit__(self, *_args):
return False
def purge_documents_vectors(self, doc_ids, coll_id):
assert doc_ids == [document_id]
doc_id = doc_ids[0]
with SessionLocal() as db:
assert db.query(Document).filter_by(id=doc_id).count() == 0
assert (
db.query(DocumentChunk)
.filter_by(source_id=doc_id)
.count()
== 1
)
events.append(("vectors", doc_ids, coll_id))
@contextmanager
def _document_db(*_args, **_kwargs):
with SessionLocal() as db:
yield db
with (
_service_db(SessionLocal),
patch(
"local_deep_research.research_library.deletion.services.document_deletion.get_user_db_session",
_document_db,
),
patch(
"local_deep_research.research_library.deletion.services.document_deletion.capture_request_db_password",
return_value="test-password",
),
patch(
"local_deep_research.research_library.services.rag_service_factory.get_rag_service",
side_effect=lambda *_args, **_kwargs: _Rag(),
),
):
assert service.delete_attempt(session_id, research_id) is True
with SessionLocal() as db:
assert db.query(Document).filter_by(id=document_id).count() == 0
assert (
db.query(DocumentChunk).filter_by(source_id=document_id).count()
== 0
)
# The vector callback observed the committed document deletion with
# its chunk still present. The real DB backstop then removed the chunk.
assert events == [("vectors", [document_id], collection_id)]
def test_delete_attempt_failed_no_assistant_removes_user_msg(
self, setup_database_for_all_tests
):
"""Primary #4659 case: a FAILED attempt with NO assistant reply.
The user message is the only chat row and is stored with
research_id=NULL (linked via research_meta.submission.message_id).
Before the fix, delete_attempt filtered solely on research_id, so it
removed nothing user-visible and never decremented message_count —
leaving an orphaned user bubble. Delete must remove the user message
and decrement the counter by exactly 1.
"""
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_id = _make_session(db, username)
research_id = str(uuid.uuid4())
user_msg_id, assistant_msg_id = _seed_attempt(
db,
username,
session_id,
research_id,
research_status=ResearchStatus.FAILED.value,
assistant_content=None,
)
assert assistant_msg_id is None
# Only the user message exists, and it has NULL research_id.
assert (
db.query(ChatMessage).filter_by(session_id=session_id).count()
== 1
)
user_row = db.query(ChatMessage).filter_by(id=user_msg_id).first()
assert user_row is not None and user_row.research_id is None
assert (
db.query(ChatSession)
.filter_by(id=session_id)
.first()
.message_count
== 1
)
with _service_db(SessionLocal):
assert service.delete_attempt(session_id, research_id) is True
with SessionLocal() as db:
assert (
db.query(ChatMessage).filter_by(id=user_msg_id).first() is None
)
assert (
db.query(ChatMessage).filter_by(session_id=session_id).count()
== 0
)
assert (
db.query(ResearchHistory).filter_by(id=research_id).first()
is None
)
# The counter was decremented by exactly 1 (the orphaned user
# bubble), not left drifting at 1.
assert (
db.query(ChatSession)
.filter_by(id=session_id)
.first()
.message_count
== 0
)
def test_delete_attempt_missing(self, setup_database_for_all_tests):
"""Unknown research_id → AttemptNotFound."""
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_id = _make_session(db, username)
with _service_db(SessionLocal):
with pytest.raises(AttemptNotFound):
service.delete_attempt(session_id, str(uuid.uuid4()))
def test_delete_attempt_wrong_session(self, setup_database_for_all_tests):
"""Research exists but belongs to a different session_id →
AttemptNotFound (scoped lookup refuses to return cross-session
rows)."""
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_a = _make_session(db, username, title="A")
session_b = _make_session(db, username, title="B")
research_id = str(uuid.uuid4())
_seed_attempt(
db,
username,
session_a,
research_id,
research_status=ResearchStatus.FAILED.value,
)
# Asking for the research under session_b must 404.
with _service_db(SessionLocal):
with pytest.raises(AttemptNotFound):
service.delete_attempt(session_b, research_id)
def test_delete_attempt_in_progress_with_live_thread(
self, setup_database_for_all_tests
):
"""IN_PROGRESS + alive thread → AttemptInProgress (409 mapping)
and the worker is flagged for termination."""
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_id = _make_session(db, username)
research_id = str(uuid.uuid4())
_seed_attempt(
db,
username,
session_id,
research_id,
research_status=ResearchStatus.IN_PROGRESS.value,
)
flagged = []
with (
patch(
"local_deep_research.chat.service.set_termination_flag",
side_effect=lambda rid: flagged.append(rid),
),
patch(
"local_deep_research.chat.service.is_research_thread_alive",
return_value=True,
),
_service_db(SessionLocal),
):
with pytest.raises(AttemptInProgress):
service.delete_attempt(session_id, research_id)
# Worker was flagged before the raise.
assert flagged == [research_id]
# Row still exists — we refused to hard-delete.
with SessionLocal() as db:
assert (
db.query(ResearchHistory).filter_by(id=research_id).first()
is not None
)
def test_delete_attempt_stale_in_progress_reclaims(
self, setup_database_for_all_tests
):
"""IN_PROGRESS but thread is dead → reclaimed and deleted (200),
not 409."""
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_id = _make_session(db, username)
research_id = str(uuid.uuid4())
_seed_attempt(
db,
username,
session_id,
research_id,
research_status=ResearchStatus.IN_PROGRESS.value,
)
# is_research_thread_alive returns False → sweep reclaims.
with (
patch(
"local_deep_research.chat.service.is_research_thread_alive",
return_value=False,
),
_service_db(SessionLocal),
):
assert service.delete_attempt(session_id, research_id) is True
with SessionLocal() as db:
assert (
db.query(ResearchHistory).filter_by(id=research_id).first()
is None
)
def test_delete_attempt_cascades_note_references_via_helper(
self, setup_database_for_all_tests
):
"""Chokepoint coverage: ``ChatService.delete_attempt`` is the
third place that deletes a ``ResearchHistory`` row. Before
the helper, the chat service hand-rolled its own cascade and
missed ``NoteReference`` (a citation-link table on
``target_research_id``); rows in that table pointing at the
deleted attempt would orphan and surface an FK violation on
the next attempt insert. After the helper, every
FK-referencing row pointing at the attempt is gone — this
test pins that expansion."""
from local_deep_research.database.models import (
NoteReference,
)
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
# A document to act as NoteReference.note_id (the FK requires
# a row in the documents table — but NoteReference FK is to
# Documents(id) without ON DELETE CASCADE, so we just need
# the row to exist).
from local_deep_research.database.models import (
Collection,
Document,
SourceType,
)
with SessionLocal() as db:
session_id = _make_session(db, username)
research_id = str(uuid.uuid4())
user_msg_id, _ = _seed_attempt(
db,
username,
session_id,
research_id,
research_status=ResearchStatus.FAILED.value,
)
source_type_id = f"st-{research_id}"
db.add(
SourceType(
id=source_type_id,
name=source_type_id,
display_name="Research Download",
icon="download",
)
)
doc_id = f"doc-{research_id}"
db.add(
Document(
id=doc_id,
research_id=research_id,
source_type_id=source_type_id,
document_hash=f"hash-{research_id}",
file_size=10,
file_type="txt",
)
)
db.add(
Collection(
id=f"coll-{research_id}",
name="c",
collection_type="user_collection",
)
)
db.add(
NoteReference(
note_id=doc_id,
target_research_id=research_id,
created_at=datetime.now(UTC),
)
)
db.commit()
# Sanity: a NoteReference row pointing at our research.
assert (
db.query(NoteReference)
.filter_by(target_research_id=research_id)
.count()
== 1
)
with _service_db(SessionLocal):
assert service.delete_attempt(session_id, research_id) is True
with SessionLocal() as db:
# The attempt is gone AND the NoteReference row that
# pointed at it — the helper now owns that branch.
assert (
db.query(ResearchHistory).filter_by(id=research_id).first()
is None
)
assert (
db.query(NoteReference)
.filter_by(target_research_id=research_id)
.count()
== 0
), (
"ChatService.delete_attempt must route through the "
"helper so NoteReference rows pointing at the "
"attempt are removed"
)
# ===========================================================================
# Service-level: ChatService.get_original_attempt_query
# ===========================================================================
class TestGetOriginalAttemptQuery:
"""Direct ChatService.get_original_attempt_query tests."""
def test_uses_research_meta_message_id_fast_path(
self, setup_database_for_all_tests
):
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_id = _make_session(db, username)
research_id = str(uuid.uuid4())
_seed_attempt(
db,
username,
session_id,
research_id,
user_content="Probe question",
include_research_meta=True,
)
with _service_db(SessionLocal):
result = service.get_original_attempt_query(session_id, research_id)
assert result == "Probe question"
def test_falls_back_to_chatmessage_query_when_meta_missing(
self, setup_database_for_all_tests
):
"""Older rows predate research_meta; the fallback lookup by
ChatMessage.research_id + role='user' must succeed."""
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_id = _make_session(db, username)
research_id = str(uuid.uuid4())
_seed_attempt(
db,
username,
session_id,
research_id,
user_content="Legacy query",
include_research_meta=False,
)
with _service_db(SessionLocal):
result = service.get_original_attempt_query(session_id, research_id)
assert result == "Legacy query"
def test_missing_research_raises(self, setup_database_for_all_tests):
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
with SessionLocal() as db:
session_id = _make_session(db, username)
with _service_db(SessionLocal):
with pytest.raises(AttemptNotFound):
service.get_original_attempt_query(
session_id, str(uuid.uuid4())
)
# ===========================================================================
# HTTP-level: DELETE /api/chat/sessions/<sid>/attempts/<rid>
# ===========================================================================
class TestDeleteAttemptRoute:
"""HTTP tests for the delete-attempt endpoint."""
def test_delete_happy_path(self, authenticated_client):
"""DELETE removes the attempt and returns 200."""
create_resp = authenticated_client.post(
"/api/chat/sessions",
json={"initial_query": "test"},
content_type="application/json",
)
session_id = json.loads(create_resp.data)["session_id"]
# Drive a real send_message with mocked spawn so we get a real
# ResearchHistory + ChatMessage + step row to delete.
with patch(
"local_deep_research.web.routers.chat.start_research_process"
):
send_resp = authenticated_client.post(
f"/api/chat/sessions/{session_id}/messages",
json={"content": "what is X?", "trigger_research": True},
content_type="application/json",
)
assert send_resp.status_code == 200
research_id = json.loads(send_resp.data)["research_id"]
assert research_id is not None
# Sanity: research exists, message_count is at least 1.
get_resp = authenticated_client.get(f"/api/chat/sessions/{session_id}")
assert get_resp.status_code == 200
assert json.loads(get_resp.data)["session"]["message_count"] >= 1
# Now delete the attempt.
del_resp = authenticated_client.delete(
f"/api/chat/sessions/{session_id}/attempts/{research_id}"
)
assert del_resp.status_code == 200
assert json.loads(del_resp.data)["success"] is True
def test_delete_missing_research_returns_404(self, authenticated_client):
create_resp = authenticated_client.post(
"/api/chat/sessions",
json={"initial_query": "test"},
content_type="application/json",
)
session_id = json.loads(create_resp.data)["session_id"]
del_resp = authenticated_client.delete(
f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}"
)
assert del_resp.status_code == 404
def test_delete_missing_session_returns_404(self, authenticated_client):
"""Unknown session_id → 404 (research can't belong to it)."""
del_resp = authenticated_client.delete(
f"/api/chat/sessions/{uuid.uuid4()}/attempts/{uuid.uuid4()}"
)
assert del_resp.status_code == 404
def test_delete_in_progress_returns_409(self, authenticated_client):
"""IN_PROGRESS research with a live thread → 409 with
active_research_id."""
create_resp = authenticated_client.post(
"/api/chat/sessions",
json={"initial_query": "test"},
content_type="application/json",
)
session_id = json.loads(create_resp.data)["session_id"]
with patch(
"local_deep_research.web.routers.chat.start_research_process"
):
send_resp = authenticated_client.post(
f"/api/chat/sessions/{session_id}/messages",
json={"content": "what is X?", "trigger_research": True},
content_type="application/json",
)
research_id = json.loads(send_resp.data)["research_id"]
# Patch is_research_thread_alive to True so delete_attempt
# treats the just-spawned research as live.
with patch(
"local_deep_research.chat.service.is_research_thread_alive",
return_value=True,
):
del_resp = authenticated_client.delete(
f"/api/chat/sessions/{session_id}/attempts/{research_id}"
)
assert del_resp.status_code == 409
body = json.loads(del_resp.data)
assert body["success"] is False
assert body["active_research_id"] == research_id
# ===========================================================================
# HTTP-level: POST /api/chat/sessions/<sid>/attempts/<rid>/retry
# ===========================================================================
class TestRetryAttemptRoute:
"""HTTP tests for the retry-attempt endpoint."""
def test_retry_happy_path_returns_new_research_id(
self, authenticated_client
):
"""Retry of a FAILED attempt: returns 200 + a fresh research_id
+ message_id."""
create_resp = authenticated_client.post(
"/api/chat/sessions",
json={"initial_query": "test"},
content_type="application/json",
)
session_id = json.loads(create_resp.data)["session_id"]
with patch(
"local_deep_research.web.routers.chat.start_research_process"
):
send_resp = authenticated_client.post(
f"/api/chat/sessions/{session_id}/messages",
json={"content": "what is X?", "trigger_research": True},
content_type="application/json",
)
old_research_id = json.loads(send_resp.data)["research_id"]
# The retry route's stale-row sweep only fires for rows older
# than the grace window (30s); the just-spawned research is
# brand-new so the sweep skips it and the per-session guard
# would refuse with 409. Patch the cap check to short-circuit
# so we can exercise the actual delete + re-spawn path. The
# cap-check itself is covered by the dedicated 409 test below.
# Also patch is_research_thread_alive=False so delete_attempt's
# own IN_PROGRESS check reclaims the row instead of refusing.
with (
patch(
"local_deep_research.web.routers.chat._enforce_chat_session_research_slot",
return_value=None,
),
patch(
"local_deep_research.chat.service.is_research_thread_alive",
return_value=False,
),
patch(
"local_deep_research.web.routers.chat.start_research_process"
),
):
retry_resp = authenticated_client.post(
f"/api/chat/sessions/{session_id}/attempts/{old_research_id}/retry"
)
assert retry_resp.status_code == 200, retry_resp.data
body = json.loads(retry_resp.data)
assert body["success"] is True
new_research_id = body["research_id"]
new_message_id = body["message_id"]
assert new_research_id is not None
assert new_message_id is not None
# The retry produced a DIFFERENT research id (the old one was
# deleted; new UUID allocated).
assert new_research_id != old_research_id
def test_retry_missing_research_returns_404(self, authenticated_client):
create_resp = authenticated_client.post(
"/api/chat/sessions",
json={"initial_query": "test"},
content_type="application/json",
)
session_id = json.loads(create_resp.data)["session_id"]
retry_resp = authenticated_client.post(
f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}/retry"
)
assert retry_resp.status_code == 404
def test_retry_on_missing_session_returns_404(self, authenticated_client):
retry_resp = authenticated_client.post(
f"/api/chat/sessions/{uuid.uuid4()}/attempts/{uuid.uuid4()}/retry"
)
assert retry_resp.status_code == 404
def test_retry_archived_session_returns_409(self, authenticated_client):
"""Archived sessions are read-only; retry must refuse."""
create_resp = authenticated_client.post(
"/api/chat/sessions",
json={"initial_query": "test"},
content_type="application/json",
)
session_id = json.loads(create_resp.data)["session_id"]
# Archive it.
archived = authenticated_client.patch(
f"/api/chat/sessions/{session_id}",
json={"status": "archived"},
content_type="application/json",
)
assert archived.status_code == 200
retry_resp = authenticated_client.post(
f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}/retry"
)
assert retry_resp.status_code == 409
# ===========================================================================
# CSRF enforcement
# ===========================================================================
class TestAttemptEndpointsCSRF:
"""DELETE and POST retry must reject requests without a CSRF token."""
def test_delete_without_csrf_token_rejected(
self, csrf_authenticated_client
):
client, token = csrf_authenticated_client
create_resp = client.post(
"/api/chat/sessions",
json={"initial_query": "Test"},
content_type="application/json",
headers={"X-CSRFToken": token},
)
assert create_resp.status_code == 200
session_id = json.loads(create_resp.data)["session_id"]
# DELETE without token — must be rejected (FastAPI CSRF
# middleware returns 403; Flask-WTF used 400).
response = client.delete(
f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}"
)
assert response.status_code == 403
def test_retry_without_csrf_token_rejected(self, csrf_authenticated_client):
client, token = csrf_authenticated_client
create_resp = client.post(
"/api/chat/sessions",
json={"initial_query": "Test"},
content_type="application/json",
headers={"X-CSRFToken": token},
)
assert create_resp.status_code == 200
session_id = json.loads(create_resp.data)["session_id"]
# POST retry without token — must be rejected (FastAPI CSRF
# middleware returns 403; Flask-WTF used 400).
response = client.post(
f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}/retry"
)
assert response.status_code == 403
@pytest.mark.parametrize(
"failure_kind,expected_status",
[
("generic", 500),
("capacity", 429),
("duplicate", 409),
],
)
def test_retry_spawn_rejection_preserves_recoverable_query(
setup_database_for_all_tests, failure_kind, expected_status
):
"""A rejected replacement must retain the query after deleting the old turn.
Reverting preserve_attempt removes the only remaining query and research
row. The saved replacement must be terminal, retryable and consume no slot.
"""
from local_deep_research.exceptions import (
DuplicateResearchError,
SystemAtCapacityError,
)
from local_deep_research.web.research_state import (
get_user_research_start_lock,
)
from local_deep_research.web.routers import chat
SessionLocal = setup_database_for_all_tests
username = f"retry_{uuid.uuid4().hex[:8]}"
query = "Retain this query when worker registration fails"
old_id = str(uuid.uuid4())
with SessionLocal() as db:
sid = _make_session(db, username)
_seed_attempt(db, username, sid, old_id, user_content=query)
lock = get_user_research_start_lock(username)
failures = {
"generic": RuntimeError("synthetic private worker details"),
"capacity": SystemAtCapacityError("synthetic capacity failure"),
"duplicate": DuplicateResearchError("synthetic duplicate failure"),
}
spawned = []
@contextmanager
def route_db(*_args, **_kwargs):
with SessionLocal() as db:
yield db
async def same_thread(fn):
return fn()
def reject_spawn(research_id, *_args, **_kwargs):
assert lock.locked()
spawned.append(research_id)
raise failures[failure_kind]
with (
_service_db(SessionLocal),
patch.object(chat, "get_user_db_session", route_db),
patch.object(chat, "run_db_sync", same_thread),
patch.object(chat, "resolve_user_password", return_value=("pw", False)),
patch.object(chat, "get_user_password", return_value="pw"),
patch.object(
chat, "_check_chat_research_slot_locked", return_value=None
),
patch.object(chat, "_load_settings", return_value={}),
patch.object(chat, "ChatContextManager") as context,
patch.object(chat, "start_research_process", side_effect=reject_spawn),
):
context.return_value.build_research_context.return_value = {
"is_multi_turn": False
}
response = asyncio.run(
inspect.unwrap(chat.retry_attempt)(
MagicMock(), sid, old_id, username
)
)
assert response.status_code == expected_status
assert b"synthetic" not in response.body
assert len(spawned) == 1
assert not lock.locked()
# Resolving the replacement through the real service proves that its
# metadata still points to the surviving query and can drive retry.
assert (
ChatService(username).get_original_attempt_query(sid, spawned[0])
== query
)
# Discover the replacement through the same message readback used by
# the client, rather than relying only on the mocked spawn's ID.
timeline = ChatService(username).get_session_messages(sid)
assert len(timeline) == 1
assert timeline[0]["research_id"] == spawned[0]
assert (
ChatService(username).get_original_attempt_query(
sid, timeline[0]["research_id"]
)
== query
)
with SessionLocal() as db:
rows = db.query(ResearchHistory).filter_by(chat_session_id=sid).all()
assert len(rows) == 1
assert rows[0].id == spawned[0] != old_id
assert rows[0].status == ResearchStatus.FAILED.value
assert rows[0].completed_at
messages = db.query(ChatMessage).filter_by(session_id=sid).all()
assert len(messages) == 1
assert messages[0].content == query
assert (
rows[0].research_meta["submission"]["message_id"] == messages[0].id
)
assert db.query(ChatSession).filter_by(id=sid).one().message_count == 1
assert (
db.query(UserActiveResearch).filter_by(username=username).count()
== 0
)
# ---------------------------------------------------------------------------
# Retry route: admission-gate scope, gated recheck, and context filtering.
# ---------------------------------------------------------------------------
@contextmanager
def _retry_route(SessionLocal, **overrides):
"""Drive ``retry_attempt`` against the test DB with the spawn mocked.
The real ``_check_chat_research_slot_locked`` runs unless overridden,
so the gated recheck is exercised. Yields the dict of patch mocks.
"""
from local_deep_research.web.routers import chat
@contextmanager
def route_db(*_args, **_kwargs):
with SessionLocal() as db:
yield db
async def same_thread(fn):
return fn()
with (
_service_db(SessionLocal),
patch.object(chat, "get_user_db_session", route_db),
patch.object(chat, "run_db_sync", same_thread),
patch.object(chat, "resolve_user_password", return_value=("pw", False)),
patch.object(chat, "get_user_password", return_value="pw"),
patch.object(
chat,
"_load_settings",
**({"return_value": {}} | overrides.pop("load_settings", {})),
),
patch.object(chat, "ChatContextManager") as context,
patch.object(chat, "start_research_process") as start,
):
context.return_value.build_research_context.return_value = {
"is_multi_turn": False
}
yield {"context": context, "start": start}
def _call_retry(username, sid, rid):
from local_deep_research.web.routers import chat
return asyncio.run(
inspect.unwrap(chat.retry_attempt)(MagicMock(), sid, rid, username)
)
def test_delete_attempt_rows_defers_the_rag_purge(
setup_database_for_all_tests,
):
"""The gate-safe half deletes rows and returns targets without purging."""
from local_deep_research.research_library.deletion.services.document_deletion import (
DocumentDeletionService,
)
SessionLocal = setup_database_for_all_tests
username = f"rows_{uuid.uuid4().hex[:8]}"
rid = str(uuid.uuid4())
with SessionLocal() as db:
sid = _make_session(db, username)
_seed_attempt(db, username, sid, rid)
document_id, collection_id = _seed_attempt_document(db, rid)
with (
_service_db(SessionLocal),
patch.object(
DocumentDeletionService, "purge_deleted_research_documents"
) as purge,
):
targets = ChatService(username).delete_attempt_rows(sid, rid)
purge.assert_not_called()
assert targets == [(document_id, [collection_id])]
with SessionLocal() as db:
assert db.query(ResearchHistory).filter_by(id=rid).count() == 0
def test_retry_purges_old_attempt_rag_only_after_releasing_the_gate(
setup_database_for_all_tests,
):
"""The vector-store purge must not run under the per-user admission gate.
The queue tick acquires every user's gate in one loop, so slow FAISS IO
under one user's gate would stall dispatch for all users.
"""
from local_deep_research.research_library.deletion.services.document_deletion import (
DocumentDeletionService,
)
from local_deep_research.web.research_state import (
get_user_research_start_lock,
)
SessionLocal = setup_database_for_all_tests
username = f"purge_{uuid.uuid4().hex[:8]}"
old_id = str(uuid.uuid4())
with SessionLocal() as db:
sid = _make_session(db, username)
_seed_attempt(db, username, sid, old_id)
document_id, collection_id = _seed_attempt_document(db, old_id)
lock = get_user_research_start_lock(username)
purges = []
def record_purge(_self, targets):
# Record rather than assert: purge_attempt_rag swallows exceptions.
purges.append((targets, lock.locked()))
with (
_retry_route(SessionLocal) as mocks,
patch.object(
DocumentDeletionService,
"purge_deleted_research_documents",
record_purge,
),
):
response = _call_retry(username, sid, old_id)
assert response.status_code == 200, response.body
mocks["start"].assert_called_once()
assert purges == [([(document_id, [collection_id])], False)]
assert not lock.locked()
def test_retry_that_raced_past_the_fast_fail_is_refused_by_the_recheck(
setup_database_for_all_tests,
):
"""A start registered during context prep is caught before the delete.
Without the gated recheck the old attempt would be deleted and the
replacement would then collide on the per-session unique index,
destroying the user's turn without admitting its replacement.
"""
from local_deep_research.web.research_state import (
get_user_research_start_lock,
)
SessionLocal = setup_database_for_all_tests
username = f"race_{uuid.uuid4().hex[:8]}"
old_id = str(uuid.uuid4())
competing_id = str(uuid.uuid4())
with SessionLocal() as db:
sid = _make_session(db, username)
user_msg_id, _ = _seed_attempt(db, username, sid, old_id)
def competing_start_then_settings(_username):
# Another start on this chat commits while retry builds context.
with SessionLocal() as db:
db.add(
ResearchHistory(
id=competing_id,
query="competing start",
mode="quick",
status=ResearchStatus.IN_PROGRESS.value,
created_at=datetime.now(UTC).isoformat(),
chat_session_id=sid,
)
)
db.commit()
return {}
with _retry_route(
SessionLocal,
load_settings={"side_effect": competing_start_then_settings},
) as mocks:
response = _call_retry(username, sid, old_id)
assert response.status_code == 409, response.body
assert json.loads(response.body)["active_research_id"] == competing_id
mocks["start"].assert_not_called()
assert not get_user_research_start_lock(username).locked()
with SessionLocal() as db:
# The old attempt survives the refused retry.
assert db.query(ResearchHistory).filter_by(id=old_id).count() == 1
assert db.query(ChatMessage).filter_by(id=user_msg_id).count() == 1
def test_retry_context_excludes_the_attempt_being_retried(
setup_database_for_all_tests,
):
"""The retried attempt's own turn must not become its prior context.
Its user message is linked only through research_meta (research_id
NULL) and its answer through research_id; both must be filtered.
"""
SessionLocal = setup_database_for_all_tests
username = f"ctx_{uuid.uuid4().hex[:8]}"
earlier_id = str(uuid.uuid4())
old_id = str(uuid.uuid4())
with SessionLocal() as db:
sid = _make_session(db, username)
_seed_attempt(
db,
username,
sid,
earlier_id,
research_status=ResearchStatus.COMPLETED.value,
user_content="earlier question",
assistant_content="earlier answer",
)
_seed_attempt(
db,
username,
sid,
old_id,
user_content="retried question",
assistant_content="failed partial answer",
)
with _retry_route(SessionLocal) as mocks:
response = _call_retry(username, sid, old_id)
assert response.status_code == 200, response.body
context_messages = mocks["context"].call_args.args[1]
assert [m["content"] for m in context_messages] == [
"earlier question",
"earlier answer",
]
build = mocks["context"].return_value.build_research_context
build.assert_called_once_with(current_query="retried question")
def test_get_session_messages_include_steps_false_returns_only_turns(
setup_database_for_all_tests,
):
"""include_steps=False spends ``limit`` on conversation turns only."""
from datetime import timedelta
SessionLocal = setup_database_for_all_tests
username = f"steps_{uuid.uuid4().hex[:8]}"
rid = str(uuid.uuid4())
with SessionLocal() as db:
sid = _make_session(db, username)
_seed_attempt(
db,
username,
sid,
rid,
user_content="the question",
assistant_content="the answer",
)
# Newer step rows that would crowd turns out of a merged window.
later = datetime.now(UTC) + timedelta(minutes=5)
for seq in range(2, 6):
db.add(
ChatProgressStep(
id=str(uuid.uuid4()),
research_id=rid,
session_id=sid,
phase="search",
content=f"step {seq}",
sequence_number=seq,
created_at=later + timedelta(seconds=seq),
)
)
db.commit()
with _service_db(SessionLocal):
service = ChatService(username)
turns = service.get_session_messages(sid, limit=2, include_steps=False)
merged = service.get_session_messages(sid, limit=2)
assert [m["content"] for m in turns] == ["the question", "the answer"]
# Control: the default merged window is filled by the newer steps.
assert all(m["message_type"] == "step" for m in merged)