Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix: hold admission through worker registration (#6074)

LearningCircuit31009ba63d2a
diff --git a/.github/workflows/fastapi-migration-quality.yml b/.github/workflows/fastapi-migration-quality.yml
index f68cbbadec..fd31f88de6 100644
--- a/.github/workflows/fastapi-migration-quality.yml
+++ b/.github/workflows/fastapi-migration-quality.yml
@@ -16,6 +16,7 @@ on:
- package-lock.json
- vite.config.js
- .pre-commit-hooks/check-silent-exceptions.py
+ - src/local_deep_research/chat/service.py
- src/local_deep_research/web/fastapi_app.py
- src/local_deep_research/web/app.py
- src/local_deep_research/web/server_config.py
@@ -43,6 +44,7 @@ on:
- tests/hooks/test_check_url_for_targets.py
- tests/hooks/test_check_no_flask.py
- tests/ci/test_fastapi_migration_quality_workflow.py
+ - tests/chat/test_chat_attempt_delete_retry.py
- tests/web/templates/test_url_for_links.py
- tests/infrastructure_tests/test_urls_js.py
- tests/security/test_csrf_e2e_flow.py
@@ -271,6 +273,8 @@ jobs:
tests/web/routers/test_settings_persistence_contracts.py::TestLockGuardCensusOverTheWholeRouter::test_router_matches_the_documented_inventory \
tests/web/routers/test_settings_validation_and_engine_icons.py::TestValidateSettingOptionalNumerics \
tests/web/routers/test_start_research_port_gaps.py::test_race_condition_after_commit_demotes_the_run_to_the_queue \
+ tests/web/routers/test_start_research_port_gaps.py::test_direct_claim_keeps_gate_until_worker_registration \
+ tests/chat/test_chat_attempt_delete_retry.py::test_retry_spawn_rejection_preserves_recoverable_query \
tests/web/routers/test_zotero_router_contracts.py \
tests/news/test_news_run_subscription_ported.py::TestSubscriptionFolderUpdate \
tests/research_library/routes/test_rag_routes_coverage_main_port.py::TestIndexDocument::test_rejects_non_boolean_force_reindex_before_indexing \
diff --git a/changelog.d/6074.bugfix.md b/changelog.d/6074.bugfix.md
new file mode 100644
index 0000000000..324f464125
--- /dev/null
+++ b/changelog.d/6074.bugfix.md
@@ -0,0 +1 @@
+Starting a research (directly, as a follow-up, or from chat) now holds the per-user admission lock until its worker is registered, so a queue check or a login from another tab can no longer mistake the brand-new run for a crashed one and reclaim it as failed. When a chat retry cannot start its worker, the retried question is now kept as a failed attempt that can be retried or deleted, instead of disappearing. Chat follow-up questions also no longer lose earlier conversation turns from their context on chats with many research progress steps.
diff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.py
index 26910c02e6..3edb22e9cf 100644
--- a/src/local_deep_research/chat/service.py
+++ b/src/local_deep_research/chat/service.py
@@ -556,6 +556,7 @@ class ChatService:
offset: int = 0,
before_created_at: Optional[str] = None,
before_id: Optional[str] = None,
+ include_steps: bool = True,
) -> List[Dict[str, Any]]:
"""
Get messages for a session, server-side merged with progress steps.
@@ -587,6 +588,14 @@ class ChatService:
before_id: Optional ID of an entry at the cursor timestamp in this
session. Resolves its sequence and kind to break timestamp ties;
requires before_created_at. Missing/deleted entries are invalid.
+ include_steps: When False, ``chat_progress_steps`` rows are
+ excluded entirely (not merged in) so ``limit`` counts only
+ genuine ``ChatMessage`` conversation turns. Callers that
+ build LLM context (rather than render the client timeline)
+ want this — otherwise a single retried/verbose attempt's
+ progress-step rows can fill the whole merged window and
+ push real conversation history out of it, even though
+ downstream context building discards step rows anyway.
Returns:
List of message + step data dictionaries, ordered by
@@ -710,6 +719,10 @@ class ChatService:
.limit(fetch_n)
.all()
)
+ # Skip the step query entirely when the caller only wants
+ # conversation turns (include_steps=False) — an empty steps
+ # list here means `limit` is spent solely on ChatMessage
+ # rows below, instead of step rows crowding them out.
steps = (
step_q.order_by(
step_timestamp.desc(),
@@ -718,6 +731,8 @@ class ChatService:
)
.limit(fetch_n)
.all()
+ if include_steps
+ else []
)
merged: List[Dict[str, Any]] = []
@@ -1061,6 +1076,47 @@ class ChatService:
return False
def delete_attempt(self, session_id: str, research_id: str) -> bool:
+ """Delete one chat attempt, then purge its documents' RAG data.
+
+ Thin wrapper over ``delete_attempt_rows`` followed by
+ ``purge_attempt_rag``; see ``delete_attempt_rows`` for the row
+ semantics and raised exceptions. Callers holding the per-user
+ admission gate must call the two halves separately and run the
+ purge after releasing the gate: the purge does per-collection
+ vector-store IO under FAISS locks, and the queue tick acquires
+ every user's gate in turn.
+
+ Returns:
+ True if the attempt existed and was deleted.
+ """
+ rag_targets = self.delete_attempt_rows(session_id, research_id)
+ self.purge_attempt_rag(rag_targets)
+ return True
+
+ def purge_attempt_rag(
+ self, rag_targets: list[tuple[str, list[str]]]
+ ) -> None:
+ """Purge vectors/chunks for documents a deleted attempt owned.
+
+ Best-effort: the rows are already committed as deleted, so a
+ failure is logged rather than raised.
+ """
+ if not rag_targets:
+ return
+ try:
+ from ..research_library.deletion.services.document_deletion import (
+ DocumentDeletionService,
+ )
+
+ DocumentDeletionService(
+ self.username
+ ).purge_deleted_research_documents(rag_targets)
+ except Exception:
+ logger.exception("Failed to purge RAG data for a deleted attempt")
+
+ def delete_attempt_rows(
+ self, session_id: str, research_id: str
+ ) -> list[tuple[str, list[str]]]:
"""Permanently delete one chat attempt (research + its messages + steps).
An "attempt" is the user message that triggered a research, the
@@ -1089,8 +1145,13 @@ class ChatService:
session_id: ID of the parent chat session (scoped lookup).
research_id: ID of the research attempt to delete.
+ Does NOT purge RAG data for library documents the attempt owned;
+ pass the returned targets to ``purge_attempt_rag`` once any
+ admission gate has been released.
+
Returns:
- True if the attempt existed and was deleted.
+ The ``(document_id, collection_ids)`` targets whose RAG data
+ should be purged (empty when there is nothing to purge).
Raises:
AttemptNotFound: research_id does not belong to session_id.
@@ -1260,15 +1321,6 @@ class ChatService:
db.commit()
- if deleted and rag_targets:
- from ..research_library.deletion.services.document_deletion import (
- DocumentDeletionService,
- )
-
- DocumentDeletionService(
- self.username
- ).purge_deleted_research_documents(rag_targets)
-
# Phase 3 — post-commit in-memory cleanup. The worker's own
# finally block calls cleanup_research too, so this is a
# no-op for the in-progress path; for the stale-IN_PROGRESS
@@ -1281,7 +1333,7 @@ class ChatService:
f"research={short_id(research_id)} "
f"({removed_messages} messages)"
)
- return True
+ return list(rag_targets) if deleted else []
except (AttemptNotFound, AttemptInProgress):
raise
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 2665298da7..736470e752 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -1034,6 +1034,14 @@ class QueueProcessorV2:
# logout/rekey: per-user admission gate before database/session work.
# Taking a pooled session first and then blocking on the gate creates a
# resource cycle when the gate holder itself needs a connection.
+ # The acquire blocks without a timeout on purpose. Direct starts,
+ # follow-ups and chat send/retry hold this gate until their worker is
+ # registered (or its spawn-failure cleanup finishes), so a slow DB or
+ # spawn there delays this loop, and with it queue dispatch and pending
+ # progress/error writes for every user, until that holder returns. The
+ # wait is bounded by that start. A timeout that then carried on without
+ # the gate would let this tick reclaim a committed claim before its
+ # worker is registered.
admission_lock = self._get_user_critical_lock(username)
admission_lock.acquire()
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index 803204321b..7b3d2c52ec 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -485,11 +485,21 @@ def _perform_post_login_tasks_body(
try:
from ...database.session_context import get_user_db_session
from ..queue.processor_v2 import queue_processor
-
- with get_user_db_session(username, password) as db_session:
- queue_processor.reconcile_orphan_active_research(
- username, db_session
- )
+ from ..research_state import user_research_start_gate
+
+ # Earlier post-login steps reuse this thread-local session. End any
+ # read transaction before taking the process-wide gate -> DB order.
+ with get_user_db_session(username, password) as ordering_session:
+ ordering_session.rollback()
+
+ # A concurrent start holds this same gate until worker registration,
+ # so login reconciliation cannot mistake its fresh durable claim for
+ # a server-restart orphan.
+ with user_research_start_gate(username):
+ with get_user_db_session(username, password) as db_session:
+ queue_processor.reconcile_orphan_active_research(
+ username, db_session
+ )
except Exception:
logger.exception(
f"Post-login research reconciliation failed for {_log_value_preview(username)}"
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index e03c0ff62d..326f940808 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -56,6 +56,10 @@ from ..routes.globals import (
is_research_thread_alive,
reclaim_stale_user_active_research,
)
+from ..research_state import (
+ get_user_research_start_lock,
+ user_research_start_gate,
+)
from ..services.research_service import (
clamp_user_max_concurrent,
run_research_process,
@@ -239,30 +243,61 @@ def _validate_title(title) -> tuple[str, int] | None:
def _cleanup_chat_send_rows(
- username, research_id, message_id, session_id, reason: str
+ username,
+ research_id,
+ message_id,
+ session_id,
+ reason: str,
+ *,
+ preserve_attempt=False,
) -> None:
"""Undo the user-message + research_history rows committed by send_message
when ``start_research_process`` rejects the spawn.
- Used by both the ``DuplicateResearchError`` (409) and
- ``SystemAtCapacityError`` (429) paths. Failure to clean up is logged at
- ERROR level so orphan rows + inflated message_count are visible to ops.
+ Used by the ``DuplicateResearchError`` (409), ``SystemAtCapacityError``
+ (429), and generic spawn-failure (500) paths. Failure to clean up is logged
+ at ERROR level so orphan rows + inflated message_count are visible to ops.
+ Retry preserves the replacement query as a failed attempt because the old
+ attempt has already been removed. Its active claim is still released.
"""
try:
with get_user_db_session(username) as cleanup_db:
- cleanup_db.query(ResearchHistory).filter_by(id=research_id).delete()
- cleanup_db.query(ChatMessage).filter_by(id=message_id).delete()
+ if preserve_attempt:
+ research = (
+ cleanup_db.query(ResearchHistory)
+ .filter_by(id=research_id, chat_session_id=session_id)
+ .first()
+ )
+ if research is not None:
+ research.status = ResearchStatus.FAILED.value
+ research.completed_at = datetime.now(UTC).isoformat()
+ # The failed replacement has no assistant response to
+ # expose its ID. Link its retained query directly so the
+ # reloaded timeline can offer Retry and Delete actions.
+ message = (
+ cleanup_db.query(ChatMessage)
+ .filter_by(id=message_id, session_id=session_id)
+ .first()
+ )
+ if message is not None:
+ message.research_id = research_id
+ else:
+ cleanup_db.query(ResearchHistory).filter_by(
+ id=research_id
+ ).delete()
+ cleanup_db.query(ChatMessage).filter_by(id=message_id).delete()
# Drop the per-user-cap tracking row too (the spawn never
# started, so no live thread owns it). research_id is a fresh
# UUID, so this only ever matches our own just-inserted row.
cleanup_db.query(UserActiveResearch).filter_by(
username=username, research_id=research_id
).delete()
- cleanup_db.execute(
- sa_update(ChatSession)
- .where(ChatSession.id == session_id)
- .values(message_count=ChatSession.message_count - 1)
- )
+ if not preserve_attempt:
+ cleanup_db.execute(
+ sa_update(ChatSession)
+ .where(ChatSession.id == session_id)
+ .values(message_count=ChatSession.message_count - 1)
+ )
cleanup_db.commit()
except DB_EXCEPTIONS:
logger.exception(
@@ -784,6 +819,7 @@ async def send_message(
return data
def _impl():
+ admission_lock = None
try:
if not data or not data.get("content"):
return JSONResponse(
@@ -859,7 +895,16 @@ async def send_message(
)
# Pre-fetch existing messages for context decisions.
- messages = service.get_session_messages(session_id, limit=20)
+ # include_steps=False keeps `limit` spent entirely on genuine
+ # ChatMessage conversation turns. Progress-step rows would
+ # otherwise dominate this 20-entry window on a research-heavy
+ # session and push real conversation history out of it before
+ # ChatContextManager ever sees it — and ChatContextManager
+ # discards step rows anyway, so there is no reason to spend the
+ # window budget on them here.
+ messages = service.get_session_messages(
+ session_id, limit=20, include_steps=False
+ )
research_id = None
research_mode = "none"
@@ -891,111 +936,27 @@ async def send_message(
status_code=401,
)
- # ---- Concurrency guards (per-session + global per-user) ----
- # Both guards run in one transaction so a stale-row reclaim
- # is visible to the count check below it.
- #
- # Sweep AGE NOTE: a brand-new IN_PROGRESS row briefly exists
- # before its worker registers in `_active_research`. Only
- # reclaim rows older than the spawn grace cutoff so we don't
- # kill our own freshly-inserted research from a racing send.
- _STALE_RESEARCH_GRACE_SECONDS = 30
- grace_cutoff_dt = datetime.now(UTC) - timedelta(
- seconds=_STALE_RESEARCH_GRACE_SECONDS
- )
- # ResearchHistory.created_at is a String column (ISO-8601);
- # UserActiveResearch.started_at is a UtcDateTime column.
- grace_cutoff_iso = grace_cutoff_dt.isoformat()
- with get_user_db_session(username) as cap_db:
- # 1. Reclaim stale chat-session research rows whose
- # worker thread is dead AND older than the grace cutoff.
- stale_chat = (
- cap_db.query(ResearchHistory)
- .filter(
- ResearchHistory.chat_session_id == session_id,
- ResearchHistory.status
- == ResearchStatus.IN_PROGRESS,
- ResearchHistory.created_at < grace_cutoff_iso,
- )
- .all()
+ # ChatService's reads above reuse a thread-local Session and
+ # leave its read transaction open. Release that connection
+ # before taking the admission gate: every producer follows
+ # gate -> DB, and reversing the order here can deadlock under
+ # pool exhaustion with a gate holder waiting for a connection.
+ with get_user_db_session(username) as ordering_db:
+ ordering_db.rollback()
+
+ # Short gated fast-fail before the potentially slow context
+ # build below. The authoritative check is repeated after that
+ # work and retained through claim + worker registration.
+ with user_research_start_gate(username):
+ cap_error = _check_chat_research_slot_locked(
+ username, session_id
)
- reclaimed_chat = False
- for row in stale_chat:
- if not is_research_thread_alive(row.id):
- logger.warning(
- f"Reclaiming stale chat research {row.id[:8]}... "
- f"(thread dead) on chat {session_id[:8]}..."
- )
- row.status = ResearchStatus.FAILED
- cleanup_research(row.id)
- reclaimed_chat = True
- if reclaimed_chat:
- cap_db.commit()
-
- # 2. Per-session guard: at most one live research per chat.
- existing_session_research = (
- cap_db.query(ResearchHistory)
- .filter_by(
- chat_session_id=session_id,
- status=ResearchStatus.IN_PROGRESS,
- )
- .first()
- )
- if existing_session_research:
- return JSONResponse(
- {
- "success": False,
- "error": "Research already in progress on this chat session. Stop it before sending a new message.",
- "active_research_id": existing_session_research.id,
- },
- status_code=409,
- )
-
- # 3. Reclaim stale UserActiveResearch rows so the count
- # below isn't inflated by dead threads. Same grace
- # window applied via started_at.
- if reclaim_stale_user_active_research(
- cap_db,
- username,
- grace_cutoff_dt=grace_cutoff_dt,
- logger=logger,
- ):
- cap_db.commit()
-
- # 4. Global per-user cap (mirrors
- # research_routes.start_research). Without this,
- # multiple chat tabs let a user bypass the cap.
- active_count = (
- cap_db.query(UserActiveResearch)
- .filter_by(
- username=username,
- status=ResearchStatus.IN_PROGRESS,
- )
- .count()
- )
- # Clamp to the server-wide semaphore ceiling (#5549):
- # app.max_concurrent_researches is user-editable but the
- # semaphore it gates is global, so an unclamped read lets
- # one user raise their own limit past the operator's and
- # starve everyone else.
- max_concurrent = clamp_user_max_concurrent(
- SettingsManager(db_session=cap_db).get_setting(
- "app.max_concurrent_researches", 3
- )
- )
- if active_count >= max_concurrent:
- return JSONResponse(
- {
- "success": False,
- "error": (
- f"Concurrent research limit reached "
- f"({active_count}/{max_concurrent}). "
- "Wait for an existing research to finish."
- ),
- },
- status_code=429,
- )
- # ---- end concurrency guards ----
+ if cap_error is not None:
+ message, status, active_research_id = cap_error
+ payload = {"success": False, "error": message}
+ if active_research_id is not None:
+ payload["active_research_id"] = active_research_id
+ return JSONResponse(payload, status_code=status)
# Settings + context (read-only — fine to do after the cap
# check, before the atomic write).
@@ -1040,6 +1001,29 @@ async def send_message(
status_code=400,
)
+ # End the cached read transaction before taking the stable
+ # per-user gate (gate -> DB is the process-wide lock order).
+ with get_user_db_session(username) as ordering_db:
+ ordering_db.rollback()
+
+ pending_admission_lock = get_user_research_start_lock(username)
+ pending_admission_lock.acquire()
+ admission_lock = pending_admission_lock
+
+ # Context preparation can take long enough for another start
+ # to consume the last slot. Reconcile and recheck under the
+ # gate that remains held through commit, registration, and
+ # every spawn-failure cleanup return below.
+ cap_error = _check_chat_research_slot_locked(
+ username, session_id
+ )
+ if cap_error is not None:
+ message, status, active_research_id = cap_error
+ payload = {"success": False, "error": message}
+ if active_research_id is not None:
+ payload["active_research_id"] = active_research_id
+ return JSONResponse(payload, status_code=status)
+
# ---- Atomic write: user message + research row in ONE txn ----
# Closes the orphan window: any IntegrityError or
# concurrent-delete on the research insert rolls back the user
@@ -1102,12 +1086,15 @@ async def send_message(
try:
db_session.commit()
except IntegrityError:
- # Two near-simultaneous POSTs both passed the
- # per-session guard; the partial unique index on
- # (chat_session_id) WHERE status='in_progress'
- # (migration 0010) catches the loser here. Rolling
- # back also undoes the user-message INSERT and the
- # message_count increment — no orphan.
+ # The admission gate is held from the recheck through
+ # this commit, so no other chat send or retry in this
+ # process can pass the per-session guard meanwhile.
+ # The partial unique index on (chat_session_id) WHERE
+ # status='in_progress' (migration 0010) is the
+ # backstop for a writer outside that gate and catches
+ # the loser here. Rolling back also undoes the
+ # user-message INSERT and the message_count
+ # increment — no orphan.
db_session.rollback()
logger.warning(
f"Concurrent in-progress research race for chat {session_id[:8]}..."
@@ -1250,6 +1237,30 @@ async def send_message(
},
status_code=429,
)
+ except Exception:
+ # Thread construction/registration can fail for reasons
+ # other than duplicate ownership or capacity (for example,
+ # RuntimeError from threading.Thread.start). The durable
+ # message, research, and per-user claim already exist, so
+ # undo all of them before releasing the admission gate.
+ logger.exception(
+ f"Failed to spawn chat research "
+ f"{research_id[:8]}... (chat {session_id[:8]}...)"
+ )
+ _cleanup_chat_send_rows(
+ username,
+ research_id,
+ message_id,
+ session_id,
+ "spawn failure",
+ )
+ return JSONResponse(
+ {
+ "success": False,
+ "error": "Failed to start research. Please try again.",
+ },
+ status_code=500,
+ )
logger.info(
f"Started chat research {research_id[:8]}... for chat {session_id[:8]}..."
@@ -1271,37 +1282,117 @@ async def send_message(
{"success": False, "error": "Failed to send message"},
status_code=500,
)
+ finally:
+ if admission_lock is not None:
+ admission_lock.release()
return await run_db_sync(_impl)
+def _check_chat_research_slot_locked(
+ username: str, session_id: str
+) -> tuple[str, int, str | None] | None:
+ """Reconcile and check chat admission while the caller holds its gate.
+
+ The caller must acquire ``user_research_start_gate(username)`` before
+ entering this helper. Opening the DB here preserves the process-wide
+ gate-before-session order. The read transaction is explicitly ended
+ before returning so a later gate acquisition cannot form a pool cycle.
+
+ Rows older than the 30-second spawn grace window whose worker is dead
+ are reclaimed before the slot checks run: this session's IN_PROGRESS
+ research rows first, then the user's ``UserActiveResearch`` slots. Once
+ that window has passed, a crashed worker's rows therefore cannot trip
+ the per-session 409 or the per-user 429. Returns
+ ``(error_message, http_status, active_research_id)`` to reject the
+ request, else ``None``.
+ """
+ grace_cutoff_dt = datetime.now(UTC) - timedelta(seconds=30)
+ grace_cutoff_iso = grace_cutoff_dt.isoformat()
+
+ with get_user_db_session(username) as cap_db:
+ try:
+ stale_chat = (
+ cap_db.query(ResearchHistory)
+ .filter(
+ ResearchHistory.chat_session_id == session_id,
+ ResearchHistory.status == ResearchStatus.IN_PROGRESS,
+ ResearchHistory.created_at < grace_cutoff_iso,
+ )
+ .all()
+ )
+ reclaimed_chat = False
+ for row in stale_chat:
+ if not is_research_thread_alive(row.id):
+ logger.warning(
+ f"Reclaiming stale chat research {row.id[:8]}... "
+ f"(thread dead) on chat {session_id[:8]}..."
+ )
+ row.status = ResearchStatus.FAILED
+ cleanup_research(row.id)
+ reclaimed_chat = True
+ if reclaimed_chat:
+ cap_db.commit()
+
+ if reclaim_stale_user_active_research(
+ cap_db,
+ username,
+ grace_cutoff_dt=grace_cutoff_dt,
+ logger=logger,
+ ):
+ cap_db.commit()
+
+ cap_error = _enforce_chat_session_research_slot(
+ cap_db, username, session_id
+ )
+ if cap_error is None:
+ return None
+
+ message, status = cap_error
+ active_research_id = None
+ if status == 409:
+ active_row = (
+ cap_db.query(ResearchHistory.id)
+ .filter_by(
+ chat_session_id=session_id,
+ status=ResearchStatus.IN_PROGRESS,
+ )
+ .first()
+ )
+ if active_row is not None:
+ active_research_id = active_row[0]
+ return message, status, active_research_id
+ finally:
+ cap_db.rollback()
+
+
def _enforce_chat_session_research_slot(
cap_db, username: str, session_id: str
) -> tuple[str, int] | None:
"""Reject send/retry when this chat session or user is at capacity.
- Runs inside the caller's ``cap_db`` transaction so the stale-row
- reclaims it performs are visible to the count check below it.
+ Runs inside the caller's ``cap_db`` transaction after any stale-row
+ reclaims, so those writes are visible to the count check below it.
Returns ``(error_message, http_status)`` when the request should be
rejected, else ``None``.
Two checks:
1. Per-session guard: at most one live research per chat session.
- Mirrors the same check in send_message's inline block.
2. Per-user global cap: at most ``app.max_concurrent_researches``
researches per user across ALL sessions. Mirrors
research start_research.
- DOES NOT include the stale-row reclaim sweep — the caller does that
- first via ``reclaim_stale_user_active_research`` so the count check
- sees accurate numbers.
+ DOES NOT include the stale-row reclaim sweep. Its only caller,
+ ``_check_chat_research_slot_locked``, first reclaims dead rows older
+ than its grace window so neither check counts them.
"""
# Per-session guard. Note: this fires for ANY in-progress research
# on the session, INCLUDING the target research on a retry path.
- # Retry routes must therefore ensure the target is not in-progress
- # (typically via delete_attempt's AttemptInProgress semantics)
- # BEFORE calling this.
+ # That is how retry refuses a target whose worker is still live,
+ # before anything is deleted. A target whose worker died more than the
+ # 30-second grace window ago has already been reclaimed by the caller's
+ # sweep, so it cannot block its own retry.
existing_session_research = (
cap_db.query(ResearchHistory)
.filter_by(
@@ -1325,8 +1416,10 @@ def _enforce_chat_session_research_slot(
)
.count()
)
- # Clamp to the server-wide semaphore ceiling (#5549) — same reasoning
- # as the send_message cap above.
+ # Clamp to the server-wide semaphore ceiling (#5549):
+ # app.max_concurrent_researches is user-editable but the semaphore it
+ # gates is global, so an unclamped read would let one user raise their
+ # own limit past the operator's and starve everyone else.
max_concurrent = clamp_user_max_concurrent(
SettingsManager(db_session=cap_db).get_setting(
"app.max_concurrent_researches", 3
@@ -1424,6 +1517,9 @@ async def retry_attempt(
"""
def _impl():
+ admission_lock = None
+ service = None
+ rag_targets: list[tuple[str, list[str]]] = []
try:
service = ChatService(username)
@@ -1466,74 +1562,24 @@ async def retry_attempt(
status_code=401,
)
- # Per-session + per-user concurrency guards. Same sweep pattern
- # as send_message: reclaim stale rows older than the grace
- # window first so the count check is accurate, then refuse if
- # this session OR the user is at capacity.
- #
- # If the TARGET research is still IN_PROGRESS, the per-session
- # guard catches it here and returns 409 — the user must Stop it
- # first. (delete_attempt would also catch this via
- # AttemptInProgress, but failing earlier — before any rows are
- # touched — keeps the failure cheap.)
- _STALE_RESEARCH_GRACE_SECONDS = 30
- grace_cutoff_dt = datetime.now(UTC) - timedelta(
- seconds=_STALE_RESEARCH_GRACE_SECONDS
- )
- grace_cutoff_iso = grace_cutoff_dt.isoformat()
- with get_user_db_session(username) as cap_db:
- # Reclaim stale chat-session research rows whose worker is
- # dead AND older than the grace cutoff. Mirrors
- # send_message's sweep.
- stale_chat = (
- cap_db.query(ResearchHistory)
- .filter(
- ResearchHistory.chat_session_id == session_id,
- ResearchHistory.status == ResearchStatus.IN_PROGRESS,
- ResearchHistory.created_at < grace_cutoff_iso,
- )
- .all()
+ # get_session() leaves the reused thread-local Session in a read
+ # transaction. End it before the early gate acquisition so retry
+ # follows the same gate -> DB order as every other producer.
+ with get_user_db_session(username) as ordering_db:
+ ordering_db.rollback()
+
+ # Cheap gated fast-fail before context preparation. If the target
+ # is still live this returns 409 before any destructive work.
+ with user_research_start_gate(username):
+ cap_error = _check_chat_research_slot_locked(
+ username, session_id
)
- reclaimed_chat = False
- for row in stale_chat:
- if not is_research_thread_alive(row.id):
- logger.warning(
- f"Reclaiming stale chat research {row.id[:8]}... "
- f"(thread dead) on chat {session_id[:8]}..."
- )
- row.status = ResearchStatus.FAILED
- cleanup_research(row.id)
- reclaimed_chat = True
- if reclaimed_chat:
- cap_db.commit()
-
- # Reclaim stale UserActiveResearch rows globally for this
- # user, so the per-user cap count below isn't inflated.
- if reclaim_stale_user_active_research(
- cap_db,
- username,
- grace_cutoff_dt=grace_cutoff_dt,
- logger=logger,
- ):
- cap_db.commit()
-
- cap_error = _enforce_chat_session_research_slot(
- cap_db, username, session_id
- )
- if cap_error is not None:
- msg, status = cap_error
- if status == 409:
- return JSONResponse(
- {
- "success": False,
- "error": msg,
- "active_research_id": research_id,
- },
- status_code=409,
- )
- return JSONResponse(
- {"success": False, "error": msg}, status_code=status
- )
+ if cap_error is not None:
+ message, status, active_research_id = cap_error
+ payload = {"success": False, "error": message}
+ if active_research_id is not None:
+ payload["active_research_id"] = active_research_id
+ return JSONResponse(payload, status_code=status)
# Fetch original user content BEFORE deleting the old attempt.
# After delete_attempt the row is gone, so this lookup must
@@ -1562,35 +1608,50 @@ async def retry_attempt(
status_code=400,
)
- # Delete the old attempt. By this point the target is guaranteed
- # not IN_PROGRESS (the per-session guard above would have
- # caught it), so this should not raise AttemptInProgress — but
- # catch it anyway in case of a narrow race.
- try:
- service.delete_attempt(session_id, research_id)
- except AttemptInProgress:
- return JSONResponse(
- {
- "success": False,
- "error": (
- "Research is in progress. Stop it before retrying."
- ),
- "active_research_id": research_id,
- },
- status_code=409,
+ # Build the replacement context before deleting anything, but
+ # exclude the target attempt in memory so it cannot become its
+ # own prior context. Current rows link the triggering user message
+ # through research_meta; legacy rows carry research_id directly.
+ original_message_id = None
+ with get_user_db_session(username) as attempt_db:
+ attempt_row = (
+ attempt_db.query(ResearchHistory)
+ .filter(
+ ResearchHistory.id == research_id,
+ ResearchHistory.chat_session_id == session_id,
+ )
+ .first()
)
- except AttemptNotFound:
- # Concurrent retry already deleted the target.
- return JSONResponse(
- {"success": False, "error": "Attempt not found"},
- status_code=404,
+ if attempt_row is None:
+ return JSONResponse(
+ {"success": False, "error": "Attempt not found"},
+ status_code=404,
+ )
+ submission = (attempt_row.research_meta or {}).get(
+ "submission", {}
)
-
- # Re-fetch messages list AFTER the delete so the context
- # builder doesn't see the just-removed attempt (otherwise the
- # new research would treat the retried query as a follow-up to
- # itself).
- messages = service.get_session_messages(session_id, limit=20)
+ if isinstance(submission, dict):
+ candidate = submission.get("message_id")
+ if isinstance(candidate, str) and candidate:
+ original_message_id = candidate
+
+ # include_steps=False keeps `limit` spent entirely on genuine
+ # ChatMessage conversation turns. Progress-step rows (there can
+ # be dozens per attempt, most recently from the very attempt
+ # being retried) would otherwise dominate the merged window used
+ # by get_session_messages() for client rendering and push real
+ # conversation history out of it before this filter ever runs —
+ # ChatContextManager discards step rows anyway, so there is no
+ # reason to spend the window budget on them here.
+ messages = service.get_session_messages(
+ session_id, limit=50, include_steps=False
+ )
+ messages = [
+ message
+ for message in messages
+ if message.get("research_id") != research_id
+ and message.get("id") != original_message_id
+ ][-20:]
settings_snapshot = _load_settings(username)
context_manager = ChatContextManager(
@@ -1629,6 +1690,51 @@ async def retry_attempt(
status_code=400,
)
+ # End all cached read transactions before taking the stable gate.
+ with get_user_db_session(username) as ordering_db:
+ ordering_db.rollback()
+
+ pending_admission_lock = get_user_research_start_lock(username)
+ pending_admission_lock.acquire()
+ admission_lock = pending_admission_lock
+
+ # Nothing destructive has happened yet. Recheck under the gate
+ # retained through delete, replacement claim, spawn, and cleanup.
+ cap_error = _check_chat_research_slot_locked(username, session_id)
+ if cap_error is not None:
+ message, status, active_research_id = cap_error
+ payload = {"success": False, "error": message}
+ if active_research_id is not None:
+ payload["active_research_id"] = active_research_id
+ return JSONResponse(payload, status_code=status)
+
+ # Delete only after the authoritative gated recheck, so losing a
+ # race cannot destroy the user's old attempt without admitting its
+ # replacement. The RAG purge for documents the old attempt owned
+ # is deferred until the gate is released (see finally below): it
+ # does vector-store IO under FAISS locks, and the queue tick
+ # acquires every user's gate in turn.
+ try:
+ rag_targets = service.delete_attempt_rows(
+ session_id, research_id
+ )
+ except AttemptInProgress:
+ return JSONResponse(
+ {
+ "success": False,
+ "error": (
+ "Research is in progress. Stop it before retrying."
+ ),
+ "active_research_id": research_id,
+ },
+ status_code=409,
+ )
+ except AttemptNotFound:
+ return JSONResponse(
+ {"success": False, "error": "Attempt not found"},
+ status_code=404,
+ )
+
research_mode = "quick"
new_research_id = str(uuid.uuid4())
@@ -1767,6 +1873,7 @@ async def retry_attempt(
new_message_id,
session_id,
"duplicate",
+ preserve_attempt=True,
)
return JSONResponse(
{
@@ -1788,6 +1895,7 @@ async def retry_attempt(
new_message_id,
session_id,
"capacity",
+ preserve_attempt=True,
)
return JSONResponse(
{
@@ -1799,6 +1907,27 @@ async def retry_attempt(
},
status_code=429,
)
+ except Exception:
+ logger.exception(
+ f"Failed to spawn retried chat research "
+ f"{new_research_id[:8]}... "
+ f"(chat {session_id[:8]}...)"
+ )
+ _cleanup_chat_send_rows(
+ username,
+ new_research_id,
+ new_message_id,
+ session_id,
+ "retry spawn failure",
+ preserve_attempt=True,
+ )
+ return JSONResponse(
+ {
+ "success": False,
+ "error": "Failed to retry research. Please try again.",
+ },
+ status_code=500,
+ )
logger.info(
f"Retried chat attempt as research "
@@ -1821,5 +1950,13 @@ async def retry_attempt(
{"success": False, "error": "Failed to retry attempt"},
status_code=500,
)
+ finally:
+ if admission_lock is not None:
+ admission_lock.release()
+ # The old attempt's rows are committed as deleted whatever
+ # happened after, so purge its RAG data now that the gate is
+ # free. Best-effort: purge_attempt_rag logs its own failures.
+ if rag_targets and service is not None:
+ service.purge_attempt_rag(rag_targets)
return await run_db_sync(_impl)
diff --git a/src/local_deep_research/web/routers/followup.py b/src/local_deep_research/web/routers/followup.py
index dc1735d5db..1a0ad33d76 100644
--- a/src/local_deep_research/web/routers/followup.py
+++ b/src/local_deep_research/web/routers/followup.py
@@ -184,6 +184,7 @@ async def start_followup(
def _start_followup_sync(data, username):
+ admission_lock = None
try:
from ..services.research_service import (
start_research_process,
@@ -191,6 +192,7 @@ def _start_followup_sync(data, username):
clamp_user_max_concurrent,
)
from ..routes.globals import reclaim_stale_user_active_research
+ from ..research_state import get_user_research_start_lock
from ...database.models import UserActiveResearch
import threading
import uuid
@@ -338,6 +340,20 @@ def _start_followup_sync(data, username):
)
)
+ # The helpers above reuse a thread-local session and may leave a read
+ # transaction open. End it before taking the process-wide lock order
+ # used by direct starts and queue replay: admission gate, then DB.
+ with get_user_db_session(username) as ordering_session:
+ ordering_session.rollback()
+
+ # Retain the same stable per-user gate from stale-row reconciliation
+ # through durable claim, worker registration, and failure cleanup.
+ # Otherwise this route can reclaim a direct start in its pre-register
+ # window, or have its own new claim reclaimed by queue replay.
+ pending_admission_lock = get_user_research_start_lock(username)
+ pending_admission_lock.acquire()
+ admission_lock = pending_admission_lock
+
# Reclaim stale rows + count active. Mirrors the try/except in
# research_routes.start_research: if the check itself fails we fall
# back to allowing the start (the global semaphore is still a
@@ -657,3 +673,6 @@ def _start_followup_sync(data, username):
{"success": False, "error": "An internal error has occurred."},
status_code=500,
)
+ finally:
+ if admission_lock is not None:
+ admission_lock.release()
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 9779572ff9..19996e6e01 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -1473,6 +1473,7 @@ def _start_research_sync(
# deliberately retained and re-enters this RLock to document the exact
# count -> claim section.
admission_lock = get_user_research_start_lock(username)
+ hold_admission_gate_until_spawn = False
admission_lock.acquire()
try:
with get_user_db_session(username) as db_session:
@@ -1568,6 +1569,14 @@ def _start_research_sync(
except Exception:
logger.warning("Could not recheck active count")
+ # The durable claim is not live until start_research_process registers
+ # its worker in the in-memory research registry. Queue replay uses that
+ # registry to distinguish live rows from stale ones, so releasing the
+ # shared gate here would let it reclaim this brand-new claim as FAILED
+ # before the worker exists. Keep the gate through registration (and
+ # through any spawn-failure cleanup) below.
+ hold_admission_gate_until_spawn = True
+
except Exception:
logger.exception("Failed to create research entry")
return JSONResponse(
@@ -1575,36 +1584,44 @@ def _start_research_sync(
status_code=500,
)
finally:
- admission_lock.release()
+ # Queued and failed claims return from the section above and must not
+ # retain the gate. A successful direct claim transfers responsibility
+ # for releasing it to the prepare/spawn try-finally below.
+ if not hold_admission_gate_until_spawn:
+ admission_lock.release()
# Only start the research if not queued
if not should_queue:
- # Save the research strategy to the database before starting the thread
try:
- from ..services.research_service import save_research_strategy
+ # Save the research strategy to the database before starting the
+ # thread. This remains inside the admission gate so no queue tick
+ # can reclaim the durable claim before registration.
+ try:
+ from ..services.research_service import save_research_strategy
- save_research_strategy(research_id, strategy, username=username)
- except Exception:
- logger.warning("Could not save research strategy")
+ save_research_strategy(research_id, strategy, username=username)
+ except Exception:
+ logger.warning("Could not save research strategy")
- # Debug logging for settings snapshot
- snapshot_data = research_settings.get("settings_snapshot", {})
- log_settings(snapshot_data, "Settings snapshot being passed to thread")
- if "search.tool" in snapshot_data:
- logger.debug(
- f"search.tool in snapshot: {snapshot_data['search.tool']}"
+ # Debug logging for settings snapshot
+ snapshot_data = research_settings.get("settings_snapshot", {})
+ log_settings(
+ snapshot_data, "Settings snapshot being passed to thread"
)
- else:
- logger.debug("search.tool NOT in snapshot")
-
- # Start the research process with the selected parameters.
- # If the spawn raises, the UserActiveResearch + IN_PROGRESS
- # ResearchHistory rows persisted above would otherwise be
- # permanently orphaned (no thread, no cleanup path). Catch any
- # exception, mark the research FAILED, delete the active row,
- # and return 500 — same contract as the queue processor's
- # terminal-failure branch introduced in #3481.
- try:
+ if "search.tool" in snapshot_data:
+ logger.debug(
+ f"search.tool in snapshot: {snapshot_data['search.tool']}"
+ )
+ else:
+ logger.debug("search.tool NOT in snapshot")
+
+ # Start the research process with the selected parameters.
+ # If the spawn raises, the UserActiveResearch + IN_PROGRESS
+ # ResearchHistory rows persisted above would otherwise be
+ # permanently orphaned (no thread, no cleanup path). Catch any
+ # exception, mark the research FAILED, delete the active row,
+ # and return 500 — same contract as the queue processor's
+ # terminal-failure branch introduced in #3481.
research_thread = start_research_process(
research_id,
query,
@@ -1676,7 +1693,7 @@ def _start_research_sync(
)
except Exception:
logger.exception(
- f"Failed to spawn research thread for {research_id}"
+ f"Failed to prepare or spawn research thread for {research_id}"
)
try:
with get_user_db_session(username) as cleanup_session:
@@ -1707,6 +1724,12 @@ def _start_research_sync(
},
status_code=500,
)
+ finally:
+ # start_research_process registers the worker before returning.
+ # On failure, the exception handlers above finish durable cleanup
+ # before this runs. Either way, queue replay can now safely inspect
+ # the claim after acquiring the shared gate.
+ admission_lock.release()
# Update the active research record with the actual thread ID.
try:
diff --git a/src/local_deep_research/web/static/js/components/chat.js b/src/local_deep_research/web/static/js/components/chat.js
index 37795ed54c..86960ee56d 100644
--- a/src/local_deep_research/web/static/js/components/chat.js
+++ b/src/local_deep_research/web/static/js/components/chat.js
@@ -558,6 +558,36 @@
await loadSession(sessionIdAtRequest);
}
+ // Retry answers that leave the chat as it was: the app or the framework
+ // sends them before retry_attempt touches any attempt, and nothing after
+ // that point sends them. 400 (rejected input), 401 (session), 403 (CSRF),
+ // and 405, 413 and 422 (the method, body size and request checks that run
+ // before the route). After any other failure the retry may have run, so
+ // the chat is reloaded: 404, 409, 429 and 500 are also sent after the old
+ // attempt was deleted (changed elsewhere, a run is live, or the
+ // replacement could not start and was kept as a failed attempt under a
+ // new ID), and any other 5xx (usually a proxy: 502/503/504, Cloudflare's
+ // 520/524) does not say how far the route got: it does slow work (an
+ // LLM summary, a wait for the admission gate) before it replaces the
+ // attempt and keeps going after a proxy stops waiting. If the reload
+ // fails, the view stays (see handleRetryAttempt).
+ const RETRY_UNCHANGED_CHAT_STATUSES = new Set([400, 401, 403, 405, 413, 422]);
+
+ /**
+ * Whether a failed retry may have changed the chat on the server, so
+ * that what is on screen could be stale and is worth reloading: true
+ * unless the answer is one of the refusals above.
+ */
+ function retryMayHaveChangedChat(error) {
+ // No status: no HTTP answer was read. Either fetch() rejected (offline,
+ // a DNS failure or a connection reset; a reset can come after the
+ // server had the request, and the route keeps running once the client
+ // is gone), or the server answered 2xx with an unusable answer (an
+ // unreadable body, no research_id). The retry itself may have run.
+ if (!error || error.status === undefined) return true;
+ return !RETRY_UNCHANGED_CHAT_STATUSES.has(error.status);
+ }
+
/**
* Retry a chat attempt: delete the failed/prior turn, then re-submit
* the same content as a fresh research run. Server returns the new
@@ -601,9 +631,11 @@
sendBtn.disabled = true;
// Show the thinking indicator BEFORE the await so the user sees
- // immediate feedback. The old attempt's DOM stays in place
- // until the new research is dispatched, then we reload — that
- // way a failed retry leaves the original turn intact.
+ // immediate feedback. A rejected spawn can retain a failed
+ // replacement with a different attempt ID, and a lost answer can hide
+ // a retry that ran, so a failure reloads the chat unless it is one of
+ // the refusals sent before any attempt is touched (see
+ // retryMayHaveChangedChat), which leave the original turn in place.
const thinkingEl = showThinking('Retrying attempt…');
try {
@@ -641,10 +673,41 @@
const display = raw && !/^Request failed \(\d+\)$/.test(raw)
? raw
: 'Failed to retry attempt. Please try again.';
+ // When the chat may have changed, read its new state BEFORE the
+ // view is touched. If that read fails as well (the network or
+ // the backend is down, the session expired), the chat and its
+ // session id stay exactly as they are and the retry error is
+ // shown below; a reload that clears the chat first would lose
+ // both.
+ let current = null;
+ if (retryMayHaveChangedChat(e)) {
+ try {
+ current = await fetchSessionState(sessionIdAtRequest);
+ } catch (reloadError) {
+ _log.error('Chat: reload after retry failure failed', reloadError);
+ }
+ if (!ownsAttempt()) return;
+ }
+ if (!current) {
+ addMessageToUI('assistant', display);
+ // eslint-disable-next-line require-atomic-updates -- handleRetryAttempt checks isProcessing at entry; no concurrent call can reach here
+ isProcessing = false;
+ sendBtn.disabled = !chatInput.value.trim();
+ return;
+ }
+ // Swap in the state just read: it replaces stale controls with
+ // the retained attempt's ID, and a pre-spawn admission rejection
+ // can also reveal a live run, whose processing state loadSession()
+ // restores.
+ const recoveryLoadGeneration = sessionLoadGeneration + 1;
+ await loadSession(sessionIdAtRequest, current);
+ // Loading advances the generation, so ownsAttempt() now refers
+ // to the old view. Check ownership of this recovery instead.
+ if (sessionId !== sessionIdAtRequest ||
+ sessionInteractionGeneration !== interactionGenerationAtRequest ||
+ sessionLoadGeneration !== recoveryLoadGeneration) return;
addMessageToUI('assistant', display);
- // eslint-disable-next-line require-atomic-updates -- handleRetryAttempt checks isProcessing at entry; no concurrent call can reach here
- isProcessing = false;
- sendBtn.disabled = !chatInput.value.trim();
+ sendBtn.disabled = isProcessing || !chatInput.value.trim();
}
}
@@ -699,9 +762,14 @@
const r = await fetch(url, options);
if (!r.ok) {
const err = await r.json().catch(() => ({}));
- throw new Error(
+ const failure = new Error(
err.error || err.detail || `Request failed (${r.status})`
);
+ // The status tells a caller which answer it got (see
+ // retryMayHaveChangedChat). A rejected fetch() and a 2xx that
+ // fails later have none.
+ failure.status = r.status;
+ throw failure;
}
const data = await r.json();
if (!data.success) throw new Error(data.error || 'Request failed');
@@ -935,9 +1003,23 @@
}
/**
- * Load an existing session.
+ * Fetch a session's info and latest messages without touching the view,
+ * in the shape loadSession() accepts as ``prefetched``.
+ */
+ async function fetchSessionState(id) {
+ const session = await apiGet(`/api/chat/sessions/${id}`);
+ const messages = await apiGet(`/api/chat/sessions/${id}/messages`);
+ return { session, messages };
+ }
+
+ /**
+ * Load an existing session. loadSession() clears the view before it
+ * fetches, so a failed load ends on the welcome screen with no session.
+ * A caller that must keep the chat on failure fetches first with
+ * fetchSessionState() and passes the result as ``prefetched``: the load
+ * then makes no request and cannot fail on the network.
*/
- async function loadSession(id) {
+ async function loadSession(id, prefetched = null) {
const ownLoadGeneration = ++sessionLoadGeneration;
const interactionGenerationAtLoad = sessionInteractionGeneration;
const ownsLoad = () => (
@@ -949,7 +1031,9 @@
resetActiveResearchState();
// Load session info
- const sessionData = await apiGet(`/api/chat/sessions/${id}`);
+ const sessionData = prefetched
+ ? prefetched.session
+ : await apiGet(`/api/chat/sessions/${id}`);
if (!ownsLoad()) return;
// Update title
@@ -958,7 +1042,9 @@
}
// Load messages
- const messagesData = await apiGet(`/api/chat/sessions/${id}/messages`);
+ const messagesData = prefetched
+ ? prefetched.messages
+ : await apiGet(`/api/chat/sessions/${id}/messages`);
if (!ownsLoad()) return;
if (messagesData.messages.length > 0) {
diff --git a/tests/chat/test_chat_admission_stale_reclaim.py b/tests/chat/test_chat_admission_stale_reclaim.py
new file mode 100644
index 0000000000..f4e374bfc1
--- /dev/null
+++ b/tests/chat/test_chat_admission_stale_reclaim.py
@@ -0,0 +1,290 @@
+"""Route-level pins for the stale-row reclaim in chat admission.
+
+On both send and retry, ``_check_chat_research_slot_locked``
+(web/routers/chat.py) reclaims stale rows before it runs the slot checks in
+``_enforce_chat_session_research_slot``. A row is stale when its worker is
+dead and it is older than the 30-second spawn grace window. Two kinds are
+reclaimed:
+
+* an IN_PROGRESS ``ResearchHistory`` row on the chat session, which would
+ otherwise trip the one-research-per-session 409;
+* the user's ``UserActiveResearch`` slot, which would otherwise count
+ toward the per-user cap and return 429.
+
+These tests drive the real routes against the real per-user database. The
+first send's worker is stubbed out, so its research never registers. Its
+rows are then aged past the grace window. Each test sends the same request
+twice: once while the worker is reported alive, as a control that must be
+refused, and once while it is reported dead, which must be admitted. Only
+the liveness verdict differs, so the admission is the reclaim's doing.
+Each test fails if the reclaim it covers is dropped or moved after the slot
+checks.
+"""
+
+import json
+from contextlib import contextmanager
+from datetime import UTC, datetime, timedelta
+from unittest.mock import patch
+
+from local_deep_research.constants import ResearchStatus
+from local_deep_research.database.models import (
+ ResearchHistory,
+ UserActiveResearch,
+)
+from local_deep_research.database.session_context import get_user_db_session
+from local_deep_research.web import research_state
+from local_deep_research.web.routers import chat
+
+# Far past the 30-second grace window in _check_chat_research_slot_locked.
+_STALE_AGE = timedelta(minutes=10)
+
+
+def _username(client) -> str:
+ response = client.get("/auth/check")
+ assert response.status_code == 200, response.text
+ return response.json()["username"]
+
+
+def _create_session(client) -> str:
+ response = client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "Stale reclaim"},
+ content_type="application/json",
+ )
+ assert response.status_code == 200, response.data
+ return json.loads(response.data)["session_id"]
+
+
+def _send(client, session_id: str, content: str):
+ return client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": content, "trigger_research": True},
+ content_type="application/json",
+ )
+
+
+def _retry(client, session_id: str, research_id: str):
+ return client.post(
+ f"/api/chat/sessions/{session_id}/attempts/{research_id}/retry"
+ )
+
+
+def _start_research_with_dead_worker(client, session_id: str, content: str):
+ """Send a research message whose worker never registers."""
+ with patch.object(chat, "start_research_process"):
+ response = _send(client, session_id, content)
+ assert response.status_code == 200, response.data
+ research_id = json.loads(response.data)["research_id"]
+ assert research_id
+ assert research_state.is_research_thread_alive(research_id) is False
+ return research_id
+
+
+def _age_past_grace_window(username: str, research_id: str) -> None:
+ """Backdate the research row and its slot past the grace window."""
+ stale_at = datetime.now(UTC) - _STALE_AGE
+ with get_user_db_session(username) as db:
+ aged_research = (
+ db.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .update({ResearchHistory.created_at: stale_at.isoformat()})
+ )
+ aged_slots = (
+ db.query(UserActiveResearch)
+ .filter_by(username=username, research_id=research_id)
+ .update({UserActiveResearch.started_at: stale_at})
+ )
+ db.commit()
+ assert (aged_research, aged_slots) == (1, 1)
+
+
+def _statuses(username: str, research_id: str):
+ """Return ``(research status, slot status)``; None for a missing row."""
+ with get_user_db_session(username) as db:
+ research = db.query(ResearchHistory).filter_by(id=research_id).first()
+ slot = (
+ db.query(UserActiveResearch)
+ .filter_by(username=username, research_id=research_id)
+ .first()
+ )
+ statuses = (
+ None if research is None else research.status,
+ None if slot is None else slot.status,
+ )
+ # The session is thread-local and reused: end the read here.
+ db.rollback()
+ return statuses
+
+
+@contextmanager
+def _worker_liveness(*, alive: bool):
+ """Report every worker as alive or dead to both reclaim passes.
+
+ The session-row pass reads the name chat.py bound at import, so it is
+ stubbed on the chat module. A patch on ``web.routes.globals`` would not
+ reach it. ``reclaim_stale_user_active_research`` reads the name from
+ ``web.research_state``.
+ """
+ with (
+ patch.object(
+ chat, "is_research_thread_alive", return_value=alive
+ ) as session_alive,
+ patch.object(
+ research_state, "is_research_thread_alive", return_value=alive
+ ) as slot_alive,
+ ):
+ yield session_alive, slot_alive
+
+
+def test_send_reclaims_a_dead_session_research_past_the_grace_window(
+ authenticated_client,
+):
+ """A crashed research on this chat must not 409 the next send.
+
+ Covers the session-row reclaim. Dropping the slot reclaim also fails
+ it, through the stale slot's final status.
+ """
+ client = authenticated_client
+ username = _username(client)
+ session_id = _create_session(client)
+ stale_id = _start_research_with_dead_worker(
+ client, session_id, "first question"
+ )
+ _age_past_grace_window(username, stale_id)
+
+ # Control: the same aged rows with a live worker still hold the slot.
+ with (
+ _worker_liveness(alive=True),
+ patch.object(chat, "start_research_process") as spawn,
+ ):
+ blocked = _send(client, session_id, "second question")
+ assert blocked.status_code == 409, blocked.data
+ assert json.loads(blocked.data)["active_research_id"] == stale_id
+ spawn.assert_not_called()
+ assert _statuses(username, stale_id) == (
+ ResearchStatus.IN_PROGRESS,
+ ResearchStatus.IN_PROGRESS,
+ )
+
+ with (
+ _worker_liveness(alive=False) as (session_alive, _slot_alive),
+ patch.object(chat, "start_research_process") as spawn,
+ ):
+ admitted = _send(client, session_id, "second question")
+ assert admitted.status_code == 200, admitted.data
+ new_id = json.loads(admitted.data)["research_id"]
+ assert new_id not in (None, stale_id)
+ spawn.assert_called_once()
+ assert spawn.call_args.args[0] == new_id
+ session_alive.assert_any_call(stale_id)
+ assert _statuses(username, stale_id) == (
+ ResearchStatus.FAILED,
+ ResearchStatus.FAILED,
+ )
+ assert _statuses(username, new_id) == (
+ ResearchStatus.IN_PROGRESS,
+ ResearchStatus.IN_PROGRESS,
+ )
+
+
+def test_send_reclaims_a_dead_slot_past_the_grace_window(authenticated_client):
+ """A stale slot from another chat must not hold the user's last slot.
+
+ Covers the slot reclaim alone: the other chat has no research row of
+ its own, so the session-row reclaim finds nothing there.
+ """
+ client = authenticated_client
+ username = _username(client)
+ busy_session = _create_session(client)
+ other_session = _create_session(client)
+
+ with patch.object(chat, "clamp_user_max_concurrent", return_value=1):
+ stale_id = _start_research_with_dead_worker(
+ client, busy_session, "first question"
+ )
+ _age_past_grace_window(username, stale_id)
+
+ # Control: with a live worker the stale-aged slot still counts.
+ with (
+ _worker_liveness(alive=True),
+ patch.object(chat, "start_research_process") as spawn,
+ ):
+ blocked = _send(client, other_session, "question elsewhere")
+ assert blocked.status_code == 429, blocked.data
+ assert "concurrent research limit" in (
+ json.loads(blocked.data)["error"].lower()
+ )
+ spawn.assert_not_called()
+ assert _statuses(username, stale_id)[1] == ResearchStatus.IN_PROGRESS
+
+ with (
+ _worker_liveness(alive=False) as (_session_alive, slot_alive),
+ patch.object(chat, "start_research_process") as spawn,
+ ):
+ admitted = _send(client, other_session, "question elsewhere")
+
+ assert admitted.status_code == 200, admitted.data
+ new_id = json.loads(admitted.data)["research_id"]
+ assert new_id not in (None, stale_id)
+ spawn.assert_called_once()
+ assert spawn.call_args.args[0] == new_id
+ slot_alive.assert_any_call(stale_id)
+ assert _statuses(username, stale_id)[1] == ResearchStatus.FAILED
+ assert _statuses(username, new_id) == (
+ ResearchStatus.IN_PROGRESS,
+ ResearchStatus.IN_PROGRESS,
+ )
+
+
+def test_retry_reclaims_its_own_dead_attempt_past_the_grace_window(
+ authenticated_client,
+):
+ """Retrying a crashed attempt must not be refused as still running.
+
+ Covers both reclaims on the retry route: without the session-row one
+ the retry gets 409, and under a cap of one it gets 429 without the slot
+ reclaim.
+ """
+ client = authenticated_client
+ username = _username(client)
+ session_id = _create_session(client)
+
+ with patch.object(chat, "clamp_user_max_concurrent", return_value=1):
+ stale_id = _start_research_with_dead_worker(
+ client, session_id, "crashed question"
+ )
+ _age_past_grace_window(username, stale_id)
+
+ # Control: a live worker still owns the attempt, so nothing is
+ # deleted and the retry is refused.
+ with (
+ _worker_liveness(alive=True),
+ patch.object(chat, "start_research_process") as spawn,
+ ):
+ blocked = _retry(client, session_id, stale_id)
+ assert blocked.status_code == 409, blocked.data
+ assert json.loads(blocked.data)["active_research_id"] == stale_id
+ spawn.assert_not_called()
+ assert _statuses(username, stale_id) == (
+ ResearchStatus.IN_PROGRESS,
+ ResearchStatus.IN_PROGRESS,
+ )
+
+ with (
+ _worker_liveness(alive=False) as (session_alive, _slot_alive),
+ patch.object(chat, "start_research_process") as spawn,
+ ):
+ retried = _retry(client, session_id, stale_id)
+
+ assert retried.status_code == 200, retried.data
+ new_id = json.loads(retried.data)["research_id"]
+ assert new_id not in (None, stale_id)
+ spawn.assert_called_once()
+ assert spawn.call_args.args[:2] == (new_id, "crashed question")
+ session_alive.assert_any_call(stale_id)
+ # The reclaimed attempt was replaced, not left behind.
+ assert _statuses(username, stale_id) == (None, None)
+ assert _statuses(username, new_id) == (
+ ResearchStatus.IN_PROGRESS,
+ ResearchStatus.IN_PROGRESS,
+ )
diff --git a/tests/chat/test_chat_attempt_delete_retry.py b/tests/chat/test_chat_attempt_delete_retry.py
index 60de741f97..04cbdb1f02 100644
--- a/tests/chat/test_chat_attempt_delete_retry.py
+++ b/tests/chat/test_chat_attempt_delete_retry.py
@@ -20,12 +20,14 @@ Coverage in this file:
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 patch
+from unittest.mock import MagicMock, patch
import pytest
@@ -42,6 +44,7 @@ from local_deep_research.database.models import (
ChatSession,
ChatSessionStatus,
ResearchHistory,
+ UserActiveResearch,
)
@@ -170,6 +173,81 @@ def _seed_attempt(
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(
@@ -263,79 +341,19 @@ class TestDeleteAttemptService:
):
"""Chat teardown uses the same vector-before-chunk purge as history."""
from local_deep_research.database.models import (
- Collection,
Document,
DocumentChunk,
- DocumentCollection,
- SourceType,
- )
- from local_deep_research.database.models.library import (
- EmbeddingProvider,
)
SessionLocal = setup_database_for_all_tests
username = f"alice_{uuid.uuid4().hex[:8]}"
service = ChatService(username=username)
research_id = str(uuid.uuid4())
- document_id = str(uuid.uuid4())
- collection_id = str(uuid.uuid4())
- chunk_text = "private chat research chunk"
with SessionLocal() as db:
session_id = _make_session(db, username)
_seed_attempt(db, username, session_id, research_id)
- 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()
+ document_id, collection_id = _seed_attempt_document(db, research_id)
events = []
@@ -1011,3 +1029,388 @@ class TestAttemptEndpointsCSRF:
f"/api/chat/sessions/{session_id}/attempts/{uuid.uuid4()}/retry"
)
assert response.status_code == 403
+
+
+ "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)
diff --git a/tests/chat/test_chat_followup_contracts.py b/tests/chat/test_chat_followup_contracts.py
index 33209a85c6..f431f0bc53 100644
--- a/tests/chat/test_chat_followup_contracts.py
+++ b/tests/chat/test_chat_followup_contracts.py
@@ -24,7 +24,9 @@ endpoint return 200":
* ``TestCrossUserResearchIds`` -- a foreign research id is ABSENT (per-user
encrypted DBs), not refused; every negative has an owner-side control
through the identical path.
-* ``TestConcurrentSends`` -- two sends racing on one session.
+* ``TestConcurrentSends`` -- two sends racing on one session, and the
+ commit-time backstop behind the admission gate, reached through a row a
+ test thread writes outside that gate.
* ``TestErrorSurfaces`` -- the LLM boundary raises; is the session still
usable afterwards?
* ``TestUserDatabaseErrorWrapping`` -- encrypted driver errors must reach
@@ -838,17 +840,18 @@ class TestCrossUserChatAndFollowUp:
)
-def _collide_on_commit(client, session_id, stub):
- """Drive two sends into a COMMIT-time collision, deterministically.
+def _race_past_the_fast_fail(client, session_id, stub):
+ """Let request B start and commit while request A waits between checks.
Request A is started on a thread and parked inside the real
- ``_load_settings`` -- after the route's per-session SELECT guard, before
- its atomic write. The wrapper calls the genuine function and only delays
- the caller; no product behaviour is faked. Request B then runs to
- completion (its guard sees nothing in progress, so it commits), after
- which A is released and its commit hits the partial unique index.
-
- Returns ``({"a": <A response>, "b": <B response>}, <loser response>)``.
+ ``_load_settings`` -- after the route's short gated fast-fail, before
+ its authoritative recheck under the per-user admission gate. The
+ wrapper calls the genuine function and only delays the caller; no
+ product behaviour is faked. Request B then runs to completion (its
+ checks see nothing in progress, so it commits and registers its
+ worker), after which A is released and runs its recheck.
+
+ Returns ``({"a": <A response>, "b": <B response>}, <A response>)``.
"""
import local_deep_research.web.routers.chat as chat_router
@@ -868,8 +871,8 @@ def _collide_on_commit(client, session_id, stub):
def _run_a():
outcome["a"] = _send(client, session_id, "racer A")
- # Hold the worker inside analyze_topic so the winner stays IN_PROGRESS
- # while the loser is still committing.
+ # Hold the worker inside analyze_topic so B stays IN_PROGRESS while A
+ # runs its recheck.
stub.gate = threading.Event()
thread = threading.Thread(target=_run_a)
try:
@@ -888,6 +891,76 @@ def _collide_on_commit(client, session_id, stub):
return outcome, outcome["a"]
+def _collide_on_commit(client, username, session_id):
+ """Drive one send into a COMMIT-time collision, deterministically.
+
+ Two sends in this process no longer meet at COMMIT. The per-user
+ admission gate is held from the authoritative recheck through the
+ commit, so the later send is refused by its recheck instead (see
+ ``_race_past_the_fast_fail``). The partial unique index
+ ``ux_research_history_chat_session_in_progress`` and the route's
+ ``except IntegrityError`` remain the backstop for a writer that does
+ not take this process's gate. To reach it, the send is parked inside
+ the real ``ChatService.insert_message_in_db`` -- after its gated recheck
+ passed, before its atomic write touches the database -- while another
+ thread, standing in for such a writer, commits an IN_PROGRESS research
+ row on the same chat. The send is then released and its commit hits
+ the index. The wrapper calls the genuine method and only delays the
+ caller; no product behaviour is faked.
+
+ Returns ``(<send response>, <competing research id>)``.
+ """
+ from datetime import UTC, datetime
+
+ import local_deep_research.web.routers.chat as chat_router
+ from local_deep_research.constants import ResearchStatus
+ from local_deep_research.database.models import ResearchHistory
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.database.thread_local_session import (
+ thread_cleanup,
+ )
+
+ # The class the route instantiates (the chat conftest rebinds the
+ # genuine one before every test).
+ service_cls = chat_router.ChatService
+ real_insert = service_cls.insert_message_in_db
+ competing_id = str(uuid.uuid4())
+ started: list = []
+ committed: list = []
+
+ @thread_cleanup
+ def _ungated_writer():
+ with get_user_db_session(username) as db:
+ db.add(
+ ResearchHistory(
+ id=competing_id,
+ query="written outside the admission gate",
+ mode="quick",
+ status=ResearchStatus.IN_PROGRESS.value,
+ created_at=datetime.now(UTC).isoformat(),
+ chat_session_id=session_id,
+ )
+ )
+ db.commit()
+ committed.append(competing_id)
+
+ def _timing_hook(self, db, *args, **kwargs):
+ if not started:
+ started.append(True)
+ writer = threading.Thread(target=_ungated_writer)
+ writer.start()
+ writer.join(timeout=20)
+ return real_insert(self, db, *args, **kwargs)
+
+ with patch.object(service_cls, "insert_message_in_db", _timing_hook):
+ response = _send(client, session_id, "racer A")
+
+ assert committed == [competing_id], "the competing row was never written"
+ return response, competing_id
+
+
# ==========================================================================
# 5. Concurrency on a single chat session
# ==========================================================================
@@ -949,31 +1022,39 @@ class TestConcurrentSends:
("assistant", ANSWER),
]
- def test_commit_collision_keeps_the_session_consistent(
+ def test_send_that_raced_past_the_fast_fail_is_refused_by_the_recheck(
self, app, stub_research_boundary
):
- """Force the *commit-time* collision (not the SELECT guard).
-
- The route's per-session SELECT guard only catches a second send once
- the first has already committed its IN_PROGRESS row. Two sends that
- both pass that guard collide on the partial unique index
- ``ux_research_history_chat_session_in_progress`` at COMMIT. This test
- schedules exactly that interleaving -- request A is parked inside the
- real ``_load_settings`` (a pure timing hook; the real settings read
- still runs) until B has fully committed -- and pins the resulting
- STATE. The response code A gets is covered separately by
- ``test_commit_collision_should_be_409_not_500`` below.
+ """A send that passed the fast-fail while another send started is
+ refused by its recheck, never reaching its atomic write.
+
+ Request A is parked in ``_load_settings`` while request B commits
+ and registers its worker. A's authoritative recheck runs after that
+ wait, under the per-user admission gate that a passing recheck keeps
+ through the commit and the worker registration. It sees B's
+ IN_PROGRESS row and answers with the per-session guard's 409, which
+ names B's research. This interleaving used to collide with B at COMMIT,
+ because the route checked only once, before ``_load_settings``. The
+ loser then got the commit handler's shorter message and no research
+ id. The commit-time collision is now reached only by a writer that
+ bypasses the gate; see ``_collide_on_commit``.
"""
client, username = _new_user(app)
- session_id = _create_session(client, "commit race")
+ session_id = _create_session(client, "fast-fail race")
- outcome, _loser = _collide_on_commit(
+ outcome, loser = _race_past_the_fast_fail(
client, session_id, stub_research_boundary
)
winner = outcome["b"]
assert winner.status_code == 200, winner.text[:300]
winner_id = _json(winner)["research_id"]
+ assert loser.status_code == 409, (loser.status_code, loser.text[:300])
+ assert _json(loser)["error"] == (
+ "Research already in progress on this chat session. "
+ "Stop it before sending a new message."
+ )
+ assert _json(loser)["active_research_id"] == winner_id
assert _await_research(winner_id)
# Exactly one research reached the strategy...
@@ -981,8 +1062,7 @@ class TestConcurrentSends:
stub_research_boundary.analyzed
)
# ...exactly one turn pair is persisted (the loser left no orphan
- # user message behind, which is the invariant the atomic write
- # exists to protect)...
+ # user message behind)...
assert _conversation_turns(_messages(client, session_id)) == [
("user", "racer B"),
("assistant", ANSWER),
@@ -995,6 +1075,9 @@ class TestConcurrentSends:
from local_deep_research.database.session_context import (
get_user_db_session,
)
+ from local_deep_research.web.research_state import (
+ get_user_research_start_lock,
+ )
with get_user_db_session(username) as db:
assert [r.id for r in db.query(ResearchHistory).all()] == [
@@ -1003,16 +1086,81 @@ class TestConcurrentSends:
# The winner's concurrency row was cleaned up when it
# finished; the loser never left one behind either.
assert db.query(UserActiveResearch).all() == []
+ # The refusal released the gate it was holding.
+ assert not get_user_research_start_lock(username).locked()
- def test_commit_collision_should_be_409_not_500(
+ def test_commit_collision_keeps_the_session_consistent(
self, app, stub_research_boundary
):
- client, _username = _new_user(app)
+ """Force the *commit-time* collision (not the SELECT guard).
+
+ Parking request A inside ``_load_settings`` until request B has
+ committed used to schedule this collision. A now rechecks under the
+ admission gate after that wait, so that interleaving is refused by
+ the recheck instead and never reaches COMMIT
+ (``test_send_that_raced_past_the_fast_fail_is_refused_by_the_recheck``
+ above). The partial unique index
+ ``ux_research_history_chat_session_in_progress`` still catches a
+ writer outside this process's gate, so ``_collide_on_commit`` has
+ such a writer commit an IN_PROGRESS row while the send sits between
+ its recheck and its atomic write. This test pins the resulting
+ STATE. The response is covered by
+ ``test_commit_collision_should_be_409_not_500`` below.
+ """
+ client, username = _new_user(app)
session_id = _create_session(client, "commit race")
- outcome, loser = _collide_on_commit(
- client, session_id, stub_research_boundary
+
+ loser, competing_id = _collide_on_commit(client, username, session_id)
+ assert loser.status_code == 409, (loser.status_code, loser.text[:300])
+
+ # The losing send never reached the strategy...
+ assert stub_research_boundary.constructions == []
+ # ...left no orphan user message behind, which is the invariant
+ # the atomic write exists to protect...
+ assert _conversation_turns(_messages(client, session_id)) == []
+ # ...and left no phantom concurrency accounting either.
+ from local_deep_research.database.models import (
+ ChatSession,
+ ResearchHistory,
+ UserActiveResearch,
+ )
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.web.research_state import (
+ get_user_research_start_lock,
)
- assert outcome["b"].status_code == 200, outcome["b"].text[:300]
+
+ with get_user_db_session(username) as db:
+ assert [r.id for r in db.query(ResearchHistory).all()] == [
+ competing_id
+ ]
+ assert db.query(UserActiveResearch).all() == []
+ # The rollback also undid the message_count increment.
+ assert (
+ db.query(ChatSession.message_count)
+ .filter_by(id=session_id)
+ .scalar()
+ == 0
+ )
+ # The collision released the gate the send was holding.
+ assert not get_user_research_start_lock(username).locked()
+
+ def test_commit_collision_should_be_409_not_500(
+ self, app, stub_research_boundary
+ ):
+ """The commit-time collision answers 409, not an opaque 500.
+
+ This drove two real sends into the collision until the admission
+ gate was held from the recheck through the commit. That pair is now
+ refused by the recheck with the per-session guard's longer message
+ (pinned by
+ ``test_send_that_raced_past_the_fast_fail_is_refused_by_the_recheck``),
+ so the collision is reached through a writer outside the gate.
+ """
+ client, username = _new_user(app)
+ session_id = _create_session(client, "commit race")
+ loser, _competing_id = _collide_on_commit(client, username, session_id)
assert loser.status_code == 409, (loser.status_code, loser.text[:300])
assert _json(loser)["error"] == (
"Research already in progress on this chat session."
diff --git a/tests/chat/test_chat_send_message_followups.py b/tests/chat/test_chat_send_message_followups.py
index 88694116ca..80ba4070e1 100644
--- a/tests/chat/test_chat_send_message_followups.py
+++ b/tests/chat/test_chat_send_message_followups.py
@@ -9,16 +9,42 @@ Specifically covers:
as HTTP 404, not 500.
* DuplicateResearchError from start_research_process is caught
explicitly, both side-effect rows are rolled back, response is 409.
+* any other spawn failure is cleaned up the same way and answers a
+ fixed 500.
* global per-user concurrent-research cap enforced for chat-triggered
research (via UserActiveResearch + app.max_concurrent_researches).
+* the per-user admission gate stays held from the slot recheck until
+ start_research_process returns, whatever the spawn does.
tests/chat/test_chat_concurrency_guard.py covers the per-session 409
invariant; these tests cover the remaining error branches.
"""
import json
+import threading
from unittest.mock import patch
+import pytest
+
+from local_deep_research.constants import ResearchStatus
+from local_deep_research.database.models import (
+ ChatMessage,
+ ChatSession,
+ ResearchHistory,
+ UserActiveResearch,
+)
+from local_deep_research.database.session_context import get_user_db_session
+from local_deep_research.database.thread_local_session import thread_cleanup
+from local_deep_research.exceptions import (
+ DuplicateResearchError,
+ SystemAtCapacityError,
+)
+from local_deep_research.web.research_state import (
+ get_user_research_start_lock,
+)
+
+_SPAWN = "local_deep_research.web.routers.chat.start_research_process"
+
def _create_session(client, query="Test"):
resp = client.post(
@@ -30,6 +56,61 @@ def _create_session(client, query="Test"):
return json.loads(resp.data)["session_id"]
+def _username(client) -> str:
+ resp = client.get("/auth/check")
+ assert resp.status_code == 200, resp.text
+ return resp.json()["username"]
+
+
+def _send(client, session_id, content):
+ return client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": content, "trigger_research": True},
+ content_type="application/json",
+ )
+
+
+def _claim_statuses(username, research_id):
+ """Return ``(research status, slot status)``; None for a missing row."""
+ with get_user_db_session(username) as db:
+ research = db.query(ResearchHistory).filter_by(id=research_id).first()
+ slot = (
+ db.query(UserActiveResearch)
+ .filter_by(username=username, research_id=research_id)
+ .first()
+ )
+ statuses = (
+ None if research is None else research.status,
+ None if slot is None else slot.status,
+ )
+ # The session is thread-local and reused: end the read here.
+ db.rollback()
+ return statuses
+
+
+def _send_leftovers(username, session_id, research_id, content):
+ """Count what one send left behind.
+
+ Returns ``(research rows, slot rows, user messages with this content,
+ the session's message_count)``.
+ """
+ with get_user_db_session(username) as db:
+ leftovers = (
+ db.query(ResearchHistory).filter_by(id=research_id).count(),
+ db.query(UserActiveResearch)
+ .filter_by(username=username, research_id=research_id)
+ .count(),
+ db.query(ChatMessage)
+ .filter_by(session_id=session_id, content=content)
+ .count(),
+ db.query(ChatSession.message_count)
+ .filter_by(id=session_id)
+ .scalar(),
+ )
+ db.rollback()
+ return leftovers
+
+
class TestSessionDeletedRace:
"""When the session row vanishes between the existence-check and the
UPDATE...RETURNING inside insert_message_in_db, the route must return
@@ -206,36 +287,18 @@ class TestGlobalPerUserCap:
patch(
"local_deep_research.web.routers.chat.start_research_process"
),
- # Treat the first research's (stubbed-spawn) thread as alive.
- # Two independent cleanup paths would otherwise delete the first
- # send's UserActiveResearch row before the second send's cap check
- # sees it (dropping active_count back to 0 → flaky 200 instead of
- # 429). Because the spawn is stubbed, the row has no real thread /
- # no _active_research entry, so it looks "done" to both paths:
- #
- # 1. reclaim_stale_user_active_research (run inline by
- # chat.routes.send_message) — flips IN_PROGRESS rows whose
- # thread is dead, gated only by a 30s grace window on
- # started_at. Patching is_research_thread_alive -> True
- # short-circuits before the grace check, so a >30s GC stall
- # between the two sequential posts can no longer trip it.
- #
- # 2. cleanup_completed_research before_request middleware
- # (web/auth/cleanup_middleware.py) — sampled on ~1% of
- # requests, deletes UserActiveResearch rows whose
- # research_id is not in _active_research. Patching
- # is_research_active -> True makes the middleware skip the
- # row, so the 1% sample can no longer trip it.
- #
- # Both patches model the production invariant (a live research's
- # row is left alone) without the timing/lottery dependencies that
- # surfaced under heavy CI load on the 36k-test xdist lane.
- patch(
- "local_deep_research.web.routes.globals.is_research_thread_alive",
- return_value=True,
- ),
+ # Treat the first research's (stubbed-spawn) worker as alive.
+ # The stub never registers it, so a stall of more than 30
+ # seconds between the two posts would age its UserActiveResearch
+ # row past the admission grace window. The second send's slot
+ # reclaim would then free it: a flaky 200 instead of 429. That
+ # reclaim (reclaim_stale_user_active_research) looks the liveness
+ # name up in web.research_state. A patch on web.routes.globals
+ # reaches neither it nor chat.py, which binds its names at
+ # import. The before_request cleanup middleware that also
+ # deleted such rows under Flask has no FastAPI successor.
patch(
- "local_deep_research.web.routes.globals.is_research_active",
+ "local_deep_research.web.research_state.is_research_thread_alive",
return_value=True,
),
):
@@ -325,3 +388,111 @@ class TestSystemAtCapacityErrorCleanup:
msgs = json.loads(list_resp.data)["messages"]
user_contents = [m["content"] for m in msgs if m["role"] == "user"]
assert "should-be-cleaned-up-on-capacity" not in user_contents
+
+
+class TestGenericSpawnFailureCleanup:
+ """start_research_process can fail for reasons other than a duplicate
+ or a capacity rejection, for example a RuntimeError from Thread.start.
+ The route must undo the message, research row and per-user slot it
+ committed, and answer a fixed 500. Without that branch the RuntimeError
+ falls through to the route-wide handler. That is still a 500, but the
+ leftover IN_PROGRESS row then refuses the next send on this chat with
+ 409 until the 30-second grace window has passed, and the slot counts
+ toward the per-user cap until a later sweep reclaims it.
+ """
+
+ def test_spawn_failure_returns_500_and_removes_the_committed_rows(
+ self, authenticated_client
+ ):
+ client = authenticated_client
+ username = _username(client)
+ session_id = _create_session(client)
+ content = "should-be-cleaned-up-on-spawn-failure"
+ before = _send_leftovers(username, session_id, "none", content)
+ assert before[:3] == (0, 0, 0)
+ spawned = []
+
+ def fail_spawn(research_id, *_args, **_kwargs):
+ spawned.append(research_id)
+ raise RuntimeError("synthetic private worker details")
+
+ with patch(_SPAWN, side_effect=fail_spawn):
+ resp = _send(client, session_id, content)
+
+ assert resp.status_code == 500, resp.data
+ body = json.loads(resp.data)
+ assert body["success"] is False
+ assert b"synthetic" not in resp.data
+ assert len(spawned) == 1
+ assert (
+ _send_leftovers(username, session_id, spawned[0], content) == before
+ )
+
+ # Nothing is left inside the grace window to refuse the next send.
+ with patch(_SPAWN) as spawn:
+ again = _send(client, session_id, "send again after the failure")
+ assert again.status_code == 200, again.data
+ spawn.assert_called_once()
+
+
+class TestAdmissionGateHeldThroughRegistration:
+ """send_message holds the per-user admission gate from its authoritative
+ slot recheck through the claim commit and start_research_process.
+
+ A queue tick or a login reconcile that took the gate between the commit
+ and the worker's registration would find a committed claim with no live
+ worker and reclaim it as failed. While the spawn runs, another thread
+ reads the committed claim and tries a non-blocking acquire of the same
+ gate, which must fail. Narrowing the hold back to a ``with`` block
+ around the recheck alone lets that acquire succeed. Once the route has
+ answered, the gate must be free again, whatever the spawn did.
+ """
+
+ @pytest.mark.parametrize(
+ ("spawn_error", "expected_status"),
+ [
+ (None, 200),
+ (RuntimeError("synthetic worker start failure"), 500),
+ (SystemAtCapacityError("synthetic capacity failure"), 429),
+ (DuplicateResearchError("synthetic duplicate failure"), 409),
+ ],
+ ids=["registered", "spawn-error", "capacity", "duplicate"],
+ )
+ def test_competing_acquire_fails_until_the_spawn_returns(
+ self, authenticated_client, spawn_error, expected_status
+ ):
+ client = authenticated_client
+ username = _username(client)
+ session_id = _create_session(client)
+ gate = get_user_research_start_lock(username)
+ seen_by_contender = []
+
+ @thread_cleanup
+ def contend(research_id):
+ acquired = gate.acquire(blocking=False)
+ if acquired:
+ gate.release()
+ seen_by_contender.append(
+ (_claim_statuses(username, research_id), acquired)
+ )
+
+ def at_registration(research_id, *_args, **_kwargs):
+ # Record, do not assert, here: the route turns an exception
+ # raised by the spawn into a 500, which would hide the failure.
+ contender = threading.Thread(target=contend, args=(research_id,))
+ contender.start()
+ contender.join(timeout=10)
+ if spawn_error is not None:
+ raise spawn_error
+
+ with patch(_SPAWN, side_effect=at_registration) as spawn:
+ resp = _send(client, session_id, "gate held through the spawn")
+
+ assert resp.status_code == expected_status, resp.data
+ spawn.assert_called_once()
+ # The claim was committed and visible to another thread, yet that
+ # thread could not take the gate.
+ assert seen_by_contender == [
+ ((ResearchStatus.IN_PROGRESS, ResearchStatus.IN_PROGRESS), False)
+ ]
+ assert not gate.locked()
diff --git a/tests/followup/test_followup_context_contracts.py b/tests/followup/test_followup_context_contracts.py
index d41875c01a..2b150a847e 100644
--- a/tests/followup/test_followup_context_contracts.py
+++ b/tests/followup/test_followup_context_contracts.py
@@ -721,10 +721,11 @@ class TestMultiTurnContextBounds:
``chat.max_findings_to_include`` is read straight from the snapshot
with no ceiling, so the manager itself imposes no fixed bound. The
- effective bound comes from the caller: both chat router call sites
- fetch ``get_session_messages(session_id, limit=20)``, so at most 20
- turns can ever be offered. Recorded so a future change to either half
- is visible.
+ effective bound comes from the caller: ``send_message`` fetches
+ ``get_session_messages(session_id, limit=20, include_steps=False)``,
+ and ``retry_attempt`` fetches ``limit=50``, drops the attempt being
+ retried and keeps the last 20, so at most 20 turns can ever be
+ offered. Recorded so a future change to either half is visible.
"""
from local_deep_research.chat.context import ChatContextManager
diff --git a/tests/js/components/chat-retry-recovery.test.js b/tests/js/components/chat-retry-recovery.test.js
new file mode 100644
index 0000000000..3e00f7df7e
--- /dev/null
+++ b/tests/js/components/chat-retry-recovery.test.js
@@ -0,0 +1,427 @@
+/**
+ * Retry failure must expose the persisted replacement through real chat
+ * controls. A retry that cannot have changed the chat keeps the current view,
+ * and so does a reload that fails.
+ */
+import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest';
+
+function buildChatDom() {
+ // Static literal (no interpolation) so no-unsanitized/property is
+ // satisfied; SESSION_ID must match this meta content.
+ document.head.innerHTML = `
+ <meta name="chat-session-id" content="sess-1">
+ `;
+ document.body.innerHTML = `
+ <div id="chat-welcome"></div>
+ <textarea id="chat-input"></textarea>
+ <button id="send-btn"></button>
+ <button id="new-chat-btn"></button>
+ <div id="chat-title"></div>
+ <div id="chat-messages" role="log"></div>
+ <template id="thinking-template">
+ <div class="ldr-chat-message ldr-chat-message-assistant ldr-chat-message-thinking" role="status">
+ <div class="ldr-chat-message-avatar"><i class="fas fa-robot"></i></div>
+ <div class="ldr-chat-message-content">
+ <div class="ldr-chat-thinking-text" hidden></div>
+ <div class="ldr-chat-thinking-dots"><span></span><span></span><span></span></div>
+ </div>
+ </div>
+ </template>
+ <template id="message-template">
+ <div class="ldr-chat-message">
+ <div class="ldr-chat-message-avatar"><i class="fas fa-user"></i></div>
+ <div class="ldr-chat-message-content">
+ <div class="ldr-chat-message-text"></div>
+ <div class="ldr-chat-message-meta"><span class="ldr-chat-message-time"></span></div>
+ </div>
+ </div>
+ </template>
+ `;
+}
+
+const flush = async () => {
+ for (let i = 0; i < 30; i++) await Promise.resolve();
+};
+const response = (payload, status = 200) => ({
+ ok: status < 400, status, json: async () => payload,
+});
+const click = (el) => el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+// A proxy error page: the body is not JSON, so apiPost has no message to show.
+const proxyPage = (status) => ({
+ ok: false, status, json: async () => { throw new SyntaxError('Unexpected token < in JSON'); },
+});
+const RETRY_URL = '/api/chat/sessions/sess-1/attempts/original-id/retry';
+
+describe('chat retry failure recovery', () => {
+ let failed;
+ let status;
+ let active;
+ let delayPost;
+ let releasePost;
+ let delayReadback;
+ let releaseReadback;
+ let posts;
+ let networkDown;
+ let connectionResetAfterRetry;
+ let unreadableAnswer;
+ let answerBody;
+ let reloadFails;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ buildChatDom();
+ failed = false;
+ active = null;
+ status = 500;
+ delayPost = false;
+ delayReadback = false;
+ posts = [];
+ networkDown = false;
+ connectionResetAfterRetry = false;
+ unreadableAnswer = false;
+ answerBody = { success: false, error: 'Could not start replacement.' };
+ // null, or { at: 'session' | 'messages', status } (status 0 = the
+ // connection drops): the read of the chat that follows a retry fails.
+ reloadFails = null;
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ window.api = { getCsrfToken: () => '' };
+ window.ui = { renderMarkdown: (text) => text };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => ({ on: vi.fn(), off: vi.fn() })),
+ };
+ globalThis.fetch = vi.fn(async (url, options = {}) => {
+ const path = String(url);
+ // A dead connection: fetch() rejects without any HTTP response.
+ if (networkDown) throw new TypeError('Failed to fetch');
+ if (options.method === 'POST' && path.endsWith('/retry')) {
+ posts.push(path);
+ if (delayPost) await new Promise(resolve => { releasePost = resolve; });
+ failed = true;
+ // The backend ran the retry, but the connection was reset
+ // before an answer came back: fetch() rejects, no HTTP answer.
+ if (connectionResetAfterRetry) throw new TypeError('Failed to fetch');
+ if (unreadableAnswer) {
+ return {
+ ok: true,
+ status: 200,
+ json: async () => { throw new SyntaxError('Unexpected token < in JSON'); },
+ };
+ }
+ return answerBody === null
+ ? proxyPage(status)
+ : response(answerBody, status);
+ }
+ if (failed && reloadFails && !options.method) {
+ const read = path.endsWith('/messages') ? 'messages' : 'session';
+ if (read === reloadFails.at) {
+ if (reloadFails.status === 0) throw new TypeError('Failed to fetch');
+ return response(
+ { success: false, error: 'Database connection required' },
+ reloadFails.status,
+ );
+ }
+ }
+ if (path.endsWith('/messages')) {
+ if (failed && delayReadback) {
+ await new Promise(resolve => { releaseReadback = resolve; });
+ }
+ return response({
+ success: true,
+ messages: [{
+ id: failed ? 'replacement-query' : 'original-answer',
+ role: failed ? 'user' : 'assistant',
+ content: failed ? 'Saved query' : 'Original answer',
+ message_type: failed ? 'query' : 'response',
+ research_id: failed ? 'replacement-id' : 'original-id',
+ created_at: '2026-09-20T00:00:00Z',
+ }],
+ has_more: false,
+ in_progress_research_id: failed ? active : null,
+ });
+ }
+ return response({ success: true, session: { id: 'sess-1', title: 'Saved chat' }, sessions: [] });
+ });
+ await import('@js/components/chat.js');
+ await flush();
+ });
+
+ afterEach(() => {
+ networkDown = false;
+ // Cancels any restored research timers before removing the DOM.
+ document.getElementById('new-chat-btn')?.click();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.innerHTML = '';
+ document.head.innerHTML = '';
+ });
+
+ // Types a draft (so the send button state is observable), clicks Retry on
+ // the original answer and returns the requests made after that click.
+ const retryOriginal = async () => {
+ document.getElementById('chat-input').value = 'draft question';
+ const requestsBefore = globalThis.fetch.mock.calls.length;
+ click(document.querySelector('[data-research-id="original-id"] [data-action="retry"]'));
+ await flush();
+ return () => globalThis.fetch.mock.calls.slice(requestsBefore).map(([url]) => String(url));
+ };
+
+ // The chat is exactly as before the click, and the retry error is shown.
+ const expectChatKept = (shown) => {
+ const original = document.querySelector('[data-research-id="original-id"]');
+ expect(original).not.toBeNull();
+ expect(original.textContent).toContain('Original answer');
+ expect(document.getElementById('chat-messages').textContent).toContain(shown);
+ expect(document.getElementById('chat-welcome').style.display).not.toBe('flex');
+ expect(document.querySelector('.ldr-chat-message-thinking')).toBeNull();
+ expect(document.getElementById('send-btn').disabled).toBe(false);
+ };
+
+ // The next message must go to this chat. With the session id dropped it
+ // would create a new chat, and with isProcessing stuck it would not send.
+ const sendNext = async () => {
+ const input = document.getElementById('chat-input');
+ input.value = 'next question';
+ input.dispatchEvent(new Event('input'));
+ const requestsBefore = globalThis.fetch.mock.calls.length;
+ click(document.getElementById('send-btn'));
+ await flush();
+ return globalThis.fetch.mock.calls.slice(requestsBefore)
+ .filter(([, options]) => options?.method === 'POST')
+ .map(([url]) => String(url));
+ };
+
+ it.each([404, 409, 429, 500])('rebinds Retry/Delete after status %s and retries the saved ID', async code => {
+ status = code;
+ click(document.querySelector('[data-research-id="original-id"] [data-action="retry"]'));
+ await flush();
+ expect(document.querySelector('[data-research-id="original-id"]')).toBeNull();
+ const replacement = document.querySelector('[data-research-id="replacement-id"]');
+ expect(replacement).not.toBeNull();
+ expect(replacement.querySelector('[data-action="delete"]')).not.toBeNull();
+ click(replacement.querySelector('[data-action="retry"]'));
+ await flush();
+ expect(posts).toEqual([
+ '/api/chat/sessions/sess-1/attempts/original-id/retry',
+ '/api/chat/sessions/sess-1/attempts/replacement-id/retry',
+ ]);
+ });
+
+ it('retains busy state when reloading an admission rejection reveals a live run', async () => {
+ active = 'competing-run';
+ status = 429;
+ document.getElementById('chat-input').value = 'another query';
+ click(document.querySelector('[data-action="retry"]'));
+ await flush();
+ expect(window.socket.subscribeToResearch).toHaveBeenCalled();
+ expect(document.getElementById('send-btn').disabled).toBe(true);
+ click(document.querySelector('[data-research-id="replacement-id"] [data-action="retry"]'));
+ await flush();
+ expect(posts).toHaveLength(1);
+ });
+
+ it('ignores a late retry error after switching to a new chat', async () => {
+ delayPost = true;
+ click(document.querySelector('[data-action="retry"]'));
+ await flush();
+ expect(releasePost).toBeTypeOf('function');
+ document.getElementById('new-chat-btn').click();
+ releasePost();
+ await flush();
+ expect(document.querySelector('[data-research-id="replacement-id"]')).toBeNull();
+ expect(document.getElementById('chat-messages').textContent).not.toContain('Could not start replacement');
+ });
+
+ it('ignores late recovery messages after switching to a new chat', async () => {
+ delayReadback = true;
+ click(document.querySelector('[data-action="retry"]'));
+ await flush();
+ expect(releaseReadback).toBeTypeOf('function');
+ document.getElementById('new-chat-btn').click();
+ releaseReadback();
+ await flush();
+ expect(document.querySelector('[data-research-id="replacement-id"]')).toBeNull();
+ expect(document.getElementById('chat-messages').textContent).not.toContain('Saved query');
+ });
+
+ it('does not append a stale retry error after a newer load of the same chat', async () => {
+ delayReadback = true;
+ click(document.querySelector('[data-action="retry"]'));
+ await flush();
+ const finishOldRecovery = releaseReadback;
+ expect(finishOldRecovery).toBeTypeOf('function');
+
+ delayReadback = false;
+ await window.chatComponent.loadSession('sess-1');
+ finishOldRecovery();
+ await flush();
+
+ expect(document.querySelector('[data-research-id="replacement-id"]')).not.toBeNull();
+ expect(document.getElementById('chat-messages').textContent).not.toContain('Could not start replacement');
+ });
+
+ it.each([
+ ['an error status', false, 'Could not start replacement.'],
+ ['an unreadable success body', true, 'Unexpected token < in JSON'],
+ ])('reloads after the server answered the retry with %s', async (_label, unreadable, shown) => {
+ unreadableAnswer = unreadable;
+ const requestsBefore = globalThis.fetch.mock.calls.length;
+ click(document.querySelector('[data-research-id="original-id"] [data-action="retry"]'));
+ await flush();
+
+ // The chat is read once, before the view is swapped; the swap itself
+ // makes no request, so it cannot fail on the network.
+ const urls = globalThis.fetch.mock.calls.slice(requestsBefore).map(([url]) => String(url));
+ expect(urls).toEqual([
+ RETRY_URL,
+ '/api/chat/sessions/sess-1',
+ '/api/chat/sessions/sess-1/messages',
+ ]);
+ expect(document.querySelector('[data-research-id="original-id"]')).toBeNull();
+ expect(document.querySelector('[data-research-id="replacement-id"]')).not.toBeNull();
+ expect(document.getElementById('chat-messages').textContent).toContain(shown);
+ });
+
+ // A proxy's answer does not say how far the retry got. The route
+ // summarizes the chat with the LLM and waits for the admission gate before
+ // it replaces the attempt, and a proxy that stops waiting does not stop
+ // it, so the retry can finish after a 504; a connection cut mid-request
+ // can leave the attempt replaced too (502/503). The same holds for every
+ // status that is not known to come before the route runs: any other 5xx
+ // (501, and Cloudflare's 520 and 524, which stand in for 502 and 504) and
+ // a 4xx the route never sends (410). The mock backend has replaced the
+ // attempt when the answer arrives, so the chat must be reloaded.
+ it.each([410, 501, 502, 503, 504, 520, 524])('reloads after status %s, which is not known to come before the route runs', async code => {
+ status = code;
+ // A proxy's error page is not JSON, so it carries no message.
+ answerBody = null;
+ const requests = await retryOriginal();
+
+ expect(requests()).toEqual([
+ RETRY_URL,
+ '/api/chat/sessions/sess-1',
+ '/api/chat/sessions/sess-1/messages',
+ ]);
+ expect(document.querySelector('[data-research-id="original-id"]')).toBeNull();
+ const replacement = document.querySelector('[data-research-id="replacement-id"]');
+ expect(replacement).not.toBeNull();
+ expect(replacement.querySelector('[data-action="retry"]')).not.toBeNull();
+ expect(replacement.querySelector('[data-action="delete"]')).not.toBeNull();
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Failed to retry attempt. Please try again.');
+ });
+
+ // The app or framework sends these before the route touches any attempt:
+ // rejected input (400), an expired session (401), a failed CSRF check
+ // (403), and the method, body size and request validation checks (405,
+ // 413, 422). The chat cannot have changed, so it is not read again (after
+ // a restart every read would answer 401 as well).
+ it.each([
+ [400, 'Original attempt has no query content to retry.'],
+ [401, 'Database connection required'],
+ [403, 'CSRF token missing'],
+ [405, 'Method Not Allowed'],
+ [413, 'Request too large'],
+ [422, 'Invalid request'],
+ ])('keeps the chat and reloads nothing after status %s', async (code, shown) => {
+ status = code;
+ answerBody = { success: false, error: shown };
+ reloadFails = { at: 'session', status: code };
+ const requests = await retryOriginal();
+
+ expectChatKept(shown);
+ expect(requests()).toEqual([RETRY_URL]);
+ expect(await sendNext()).toEqual(['/api/chat/sessions/sess-1/messages']);
+ });
+
+ // The route answers these after it may have changed the chat, so the chat
+ // is reloaded; when that reload fails the chat and session id stay as they
+ // were and the retry error is shown. Either read of the reload can fail,
+ // and the chat must not be cleared before the second one is answered.
+ it.each([404, 409, 429, 500].flatMap(
+ code => ['session', 'messages'].map(read => [code, read]),
+ ))('keeps the chat and shows the error when the reload after status %s fails at the %s read', async (code, read) => {
+ status = code;
+ reloadFails = { at: read, status: 503 };
+ const requests = await retryOriginal();
+
+ expectChatKept('Could not start replacement.');
+ expect(requests()).toContain('/api/chat/sessions/sess-1');
+ expect(await sendNext()).toEqual(['/api/chat/sessions/sess-1/messages']);
+ });
+
+ // A proxy's 502/503/504 (or a CDN's 524) also arrive while the backend is
+ // really down, and then the reload fails with the same status. The reload
+ // only reads before it swaps, so the chat and session id stay as they were
+ // and the retry error is shown.
+ it.each([502, 503, 504, 524].flatMap(
+ code => ['session', 'messages'].map(read => [code, read]),
+ ))('keeps the chat and shows the error when the reload after a proxy answered %s fails at the %s read', async (code, read) => {
+ status = code;
+ answerBody = null;
+ reloadFails = { at: read, status: code };
+ const requests = await retryOriginal();
+
+ expectChatKept('Failed to retry attempt. Please try again.');
+ expect(requests()).toContain('/api/chat/sessions/sess-1');
+ expect(await sendNext()).toEqual(['/api/chat/sessions/sess-1/messages']);
+ });
+
+ it('keeps the chat and shows the error when the connection drops during the reload', async () => {
+ status = 409;
+ reloadFails = { at: 'messages', status: 0 };
+ await retryOriginal();
+
+ expectChatKept('Could not start replacement.');
+ expect(await sendNext()).toEqual(['/api/chat/sessions/sess-1/messages']);
+ });
+
+ it('keeps the chat and shows the error when the reload after an unreadable success body fails', async () => {
+ unreadableAnswer = true;
+ reloadFails = { at: 'messages', status: 503 };
+ await retryOriginal();
+
+ expectChatKept('Unexpected token < in JSON');
+ expect(await sendNext()).toEqual(['/api/chat/sessions/sess-1/messages']);
+ });
+
+ // fetch() rejects with no HTTP answer when the connection is reset, and a
+ // reset can come after the server has the request: the route goes on to
+ // replace the attempt once the client is gone. The mock backend has
+ // replaced the attempt, so the chat must be reloaded.
+ it('reloads after the connection was reset once the backend had the retry', async () => {
+ connectionResetAfterRetry = true;
+ const requests = await retryOriginal();
+
+ expect(requests()).toEqual([
+ RETRY_URL,
+ '/api/chat/sessions/sess-1',
+ '/api/chat/sessions/sess-1/messages',
+ ]);
+ expect(document.querySelector('[data-research-id="original-id"]')).toBeNull();
+ const replacement = document.querySelector('[data-research-id="replacement-id"]');
+ expect(replacement).not.toBeNull();
+ expect(replacement.querySelector('[data-action="retry"]')).not.toBeNull();
+ expect(replacement.querySelector('[data-action="delete"]')).not.toBeNull();
+ expect(document.getElementById('chat-messages').textContent).toContain('Failed to fetch');
+ });
+
+ it('keeps the current chat and shows the error when the retry gets no answer and the reload fails too', async () => {
+ // The connection is dead, so the reload fails as well.
+ networkDown = true;
+ const requests = await retryOriginal();
+
+ // The reload was tried and failed at its first read.
+ expect(requests()).toEqual([RETRY_URL, '/api/chat/sessions/sess-1']);
+ expectChatKept('Failed to fetch');
+
+ // The kept controls work again once the connection is back.
+ networkDown = false;
+ const original = document.querySelector('[data-research-id="original-id"]');
+ click(original.querySelector('[data-action="retry"]'));
+ await flush();
+ expect(posts).toEqual([RETRY_URL]);
+ expect(document.querySelector('[data-research-id="replacement-id"]')).not.toBeNull();
+ });
+});
diff --git a/tests/web/queue/test_reconcile_orphan_liveness.py b/tests/web/queue/test_reconcile_orphan_liveness.py
index 112877d58f..f2097cfd74 100644
--- a/tests/web/queue/test_reconcile_orphan_liveness.py
+++ b/tests/web/queue/test_reconcile_orphan_liveness.py
@@ -6,6 +6,10 @@ that live research wrongly flagged FAILED (and then delete_attempt could
hard-delete it out from under the running worker). Only genuinely dead-thread
rows (e.g. after a server restart) should be reconciled — matching the
is_research_thread_alive() guard chat.py and the research-start reclaim use.
+
+A brand-new research has no live thread either, between the commit of its
+claim and its worker's registration. The login step therefore reconciles
+under the same per-user admission gate that a start holds across that gap.
"""
import threading
@@ -96,3 +100,84 @@ def test_dead_thread_research_is_failed(session):
assert n == 1, "a dead/unregistered research must be reconciled"
research = session.query(ResearchHistory).filter_by(id=dead_id).first()
assert research.status == ResearchStatus.FAILED
+
+
+def test_login_reconcile_runs_under_the_admission_gate():
+ """Post-login reconciliation must hold the per-user admission gate.
+
+ A start keeps that gate from its claim commit until its worker
+ registers. In that gap the claim has no live thread yet, so a reconcile
+ that ran without the gate would fail it as a restart orphan. The stub
+ reconcile below runs a non-blocking acquire of the same gate from
+ another thread, which must fail. Dropping the
+ ``with user_research_start_gate(username)`` block in
+ ``_perform_post_login_tasks_body`` (web/routers/auth.py) lets it
+ succeed.
+ """
+ import uuid
+ from contextlib import contextmanager
+ from unittest.mock import MagicMock, patch
+
+ from local_deep_research.web.research_state import (
+ get_user_research_start_lock,
+ )
+ from local_deep_research.web.routers import auth as auth_module
+
+ username = f"login_gate_{uuid.uuid4().hex[:8]}"
+ gate = get_user_research_start_lock(username)
+ user_db = MagicMock(name="user_db")
+ reconciled = []
+ competing_acquisitions = []
+
+ @contextmanager
+ def user_db_session(*_args, **_kwargs):
+ yield user_db
+
+ def compete_for_gate():
+ acquired = gate.acquire(blocking=False)
+ competing_acquisitions.append(acquired)
+ if acquired:
+ gate.release()
+
+ def reconcile(name, db_session):
+ reconciled.append((name, db_session))
+ contender = threading.Thread(target=compete_for_gate)
+ contender.start()
+ contender.join(timeout=10)
+ return 0
+
+ # Steps 1 and 4 see a current settings version and backups disabled, so
+ # they do nothing. Step 3's auth DB fails fast inside its own handler.
+ settings_manager = MagicMock()
+ settings_manager.db_version_matches_package.return_value = True
+ settings_manager.get_setting.return_value = False
+
+ with (
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ user_db_session,
+ ),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ return_value=settings_manager,
+ ),
+ patch(
+ "local_deep_research.database.library_init.initialize_library_for_user",
+ return_value={"success": True},
+ ),
+ patch.object(
+ auth_module,
+ "auth_db_session",
+ side_effect=RuntimeError("auth db unavailable"),
+ ),
+ patch(
+ "local_deep_research.web.queue.processor_v2.queue_processor"
+ ) as queue_processor,
+ ):
+ queue_processor.reconcile_orphan_active_research.side_effect = reconcile
+ auth_module._perform_post_login_tasks_body(username, "pw", "sess-1")
+
+ # The step swallows its own errors, so first prove the reconcile ran.
+ assert reconciled == [(username, user_db)]
+ assert competing_acquisitions == [False]
+ assert not gate.locked()
diff --git a/tests/web/routers/test_chat_router_error_edges.py b/tests/web/routers/test_chat_router_error_edges.py
index c2f0c2ae85..45ad461de5 100644
--- a/tests/web/routers/test_chat_router_error_edges.py
+++ b/tests/web/routers/test_chat_router_error_edges.py
@@ -84,6 +84,7 @@ def _service(mocker: MockerFixture) -> MagicMock:
service.get_original_attempt_query.return_value = "retry query"
service.get_session_messages.return_value = []
service.insert_message_in_db.return_value = "message-new"
+ service.delete_attempt_rows.return_value = []
mocker.patch.object(chat, "ChatService", return_value=service)
mocker.patch.object(chat, "run_db_sync", side_effect=_run_inline)
return service
@@ -91,14 +92,11 @@ def _service(mocker: MockerFixture) -> MagicMock:
def _send_cap_db() -> tuple[MagicMock, SimpleNamespace]:
stale_row = SimpleNamespace(id="stale-send", status="in_progress")
- stale_query = MagicMock()
- stale_query.filter.return_value.all.return_value = [stale_row]
- session_query = MagicMock()
- session_query.filter_by.return_value.first.return_value = None
- active_query = MagicMock()
- active_query.filter_by.return_value.count.return_value = 0
cap_db = MagicMock()
- cap_db.query.side_effect = [stale_query, session_query, active_query]
+ query = cap_db.query.return_value
+ query.filter.return_value.all.side_effect = [[stale_row], []]
+ query.filter_by.return_value.first.return_value = None
+ query.filter_by.return_value.count.return_value = 0
return cap_db, stale_row
@@ -254,7 +252,7 @@ async def test_send_rejects_non_string_and_invalid_numeric_settings(
cap_db.query.return_value.filter_by.return_value.first.return_value = None
cap_db.query.return_value.filter_by.return_value.count.return_value = 0
mocker.patch.object(
- chat, "get_user_db_session", side_effect=_db_factory(cap_db)
+ chat, "get_user_db_session", side_effect=_db_factory(cap_db, cap_db)
)
mocker.patch.object(
chat, "resolve_user_password", return_value=("pw", False)
@@ -304,14 +302,16 @@ async def test_send_handles_integrity_race_and_unmapped_write_error(
write_db = MagicMock()
write_db.commit.side_effect = commit_error
mocker.patch.object(
- chat, "get_user_db_session", side_effect=_db_factory(cap_db, write_db)
+ chat,
+ "get_user_db_session",
+ side_effect=_db_factory(cap_db, cap_db, cap_db, cap_db, write_db),
)
mocker.patch.object(
chat, "resolve_user_password", return_value=("pw", False)
)
mocker.patch.object(chat, "_load_settings", return_value=_valid_settings())
mocker.patch.object(
- chat, "reclaim_stale_user_active_research", return_value=True
+ chat, "reclaim_stale_user_active_research", side_effect=[True, False]
)
mocker.patch.object(chat, "is_research_thread_alive", return_value=False)
cleanup = mocker.patch.object(chat, "cleanup_research")
@@ -468,15 +468,20 @@ async def test_retry_rejects_expired_session_and_capacity(
mocker.patch.object(
chat, "resolve_user_password", return_value=("pw", False)
)
- cap_db = MagicMock()
mocker.patch.object(
- chat, "get_user_db_session", side_effect=_db_factory(cap_db, cap_db)
+ chat,
+ "get_user_db_session",
+ side_effect=_db_factory(MagicMock(), MagicMock()),
)
for cap_error, expected in (("busy", 409), ("full", 429)):
mocker.patch.object(
chat,
- "_enforce_chat_session_research_slot",
- return_value=(cap_error, expected),
+ "_check_chat_research_slot_locked",
+ return_value=(
+ cap_error,
+ expected,
+ "research-1" if expected == 409 else None,
+ ),
)
response = await chat.retry_attempt(
MagicMock(spec=Request),
@@ -513,18 +518,21 @@ async def test_retry_rejects_corrupt_or_racing_attempt(
"""
service = _service(mocker)
service.get_original_attempt_query.return_value = original
- service.delete_attempt.side_effect = delete_error
+ service.delete_attempt_rows.side_effect = delete_error
mocker.patch.object(
chat, "resolve_user_password", return_value=("pw", False)
)
mocker.patch.object(
- chat, "get_user_db_session", side_effect=_db_factory(MagicMock())
+ chat,
+ "get_user_db_session",
+ side_effect=_db_factory(MagicMock(), MagicMock(), MagicMock()),
)
+ mocker.patch.object(chat, "_load_settings", return_value=_valid_settings())
mocker.patch.object(
chat, "reclaim_stale_user_active_research", return_value=False
)
mocker.patch.object(
- chat, "_enforce_chat_session_research_slot", return_value=None
+ chat, "_check_chat_research_slot_locked", return_value=None
)
response = await chat.retry_attempt(
MagicMock(spec=Request), "session-1", "research-1", username="alice"
@@ -534,12 +542,12 @@ async def test_retry_rejects_corrupt_or_racing_attempt(
body = json.loads(response.body)
if expected == 400:
assert "no query content to retry" in body["error"]
- service.delete_attempt.assert_not_called()
+ service.delete_attempt_rows.assert_not_called()
else:
# chat.py:1512 (get_original_attempt_query raised AttemptNotFound) and
- # chat.py:1550 (delete_attempt raised it) return identical 404 bodies.
- # Only reaching delete_attempt distinguishes the branch named here.
- service.delete_attempt.assert_called_once_with(
+ # chat.py:1550 (delete_attempt_rows raised it) return identical 404
+ # bodies. Only reaching the delete distinguishes the branch named here.
+ service.delete_attempt_rows.assert_called_once_with(
"session-1", "research-1"
)
if expected == 409:
@@ -563,7 +571,7 @@ async def test_retry_invalid_settings_and_integrity_race(
chat, "reclaim_stale_user_active_research", return_value=False
)
mocker.patch.object(
- chat, "_enforce_chat_session_research_slot", return_value=None
+ chat, "_check_chat_research_slot_locked", return_value=None
)
settings = _valid_settings()
settings["search.questions_per_iteration"] = {"value": None}
@@ -587,7 +595,9 @@ async def test_retry_invalid_settings_and_integrity_race(
"insert", {}, RuntimeError("race")
)
mocker.patch.object(
- chat, "get_user_db_session", side_effect=_db_factory(cap_db, write_db)
+ chat,
+ "get_user_db_session",
+ side_effect=_db_factory(cap_db, cap_db, cap_db, write_db),
)
response = await chat.retry_attempt(
MagicMock(spec=Request), "session-1", "research-1", username="alice"
@@ -608,23 +618,30 @@ async def test_retry_spawn_failure_cleans_up(
_service(mocker)
stale_row = SimpleNamespace(id="stale-research", status="in_progress")
cap_db = MagicMock()
- cap_db.query.return_value.filter.return_value.all.return_value = [stale_row]
+ cap_db.query.return_value.filter.return_value.all.side_effect = [
+ [stale_row],
+ [],
+ ]
+ cap_db.query.return_value.filter_by.return_value.first.return_value = None
+ cap_db.query.return_value.filter_by.return_value.count.return_value = 0
write_db = MagicMock()
cleanup_db = MagicMock()
mocker.patch.object(
chat,
"get_user_db_session",
- side_effect=_db_factory(cap_db, write_db, cleanup_db),
+ side_effect=_db_factory(
+ cap_db, cap_db, cap_db, cap_db, cap_db, write_db, cleanup_db
+ ),
)
mocker.patch.object(
chat, "resolve_user_password", return_value=("pw", False)
)
mocker.patch.object(
- chat, "reclaim_stale_user_active_research", return_value=True
+ chat, "reclaim_stale_user_active_research", side_effect=[True, False]
)
mocker.patch.object(
- chat, "_enforce_chat_session_research_slot", return_value=None
- )
+ chat, "SettingsManager"
+ ).return_value.get_setting.return_value = 3
mocker.patch.object(chat, "_load_settings", return_value=_valid_settings())
mocker.patch.object(chat, "get_user_password", return_value="pw")
mocker.patch.object(chat, "is_research_thread_alive", return_value=False)
@@ -666,7 +683,7 @@ async def test_retry_unmapped_value_error_and_route_exception_return_500(
chat, "reclaim_stale_user_active_research", return_value=False
)
mocker.patch.object(
- chat, "_enforce_chat_session_research_slot", return_value=None
+ chat, "_check_chat_research_slot_locked", return_value=None
)
mocker.patch.object(chat, "_load_settings", return_value=_valid_settings())
mocker.patch.object(
@@ -682,7 +699,12 @@ async def test_retry_unmapped_value_error_and_route_exception_return_500(
mocker.patch.object(
chat,
"get_user_db_session",
- side_effect=_db_factory(MagicMock(), MagicMock()),
+ side_effect=_db_factory(
+ MagicMock(),
+ MagicMock(),
+ MagicMock(),
+ MagicMock(),
+ ),
)
response = await chat.retry_attempt(
MagicMock(spec=Request),
@@ -733,8 +755,15 @@ async def test_send_forwards_custom_endpoint_only_for_openai_endpoint(
_service(mocker)
cap_db, _stale_row = _send_cap_db()
write_db = MagicMock()
+ # send_message opens, in order: an ordering rollback, the gated
+ # fast-fail check, a second ordering rollback, the authoritative gated
+ # recheck, and the atomic write.
mocker.patch.object(
- chat, "get_user_db_session", side_effect=_db_factory(cap_db, write_db)
+ chat,
+ "get_user_db_session",
+ side_effect=_db_factory(
+ MagicMock(), cap_db, MagicMock(), cap_db, write_db
+ ),
)
mocker.patch.object(
chat, "resolve_user_password", return_value=("pw", False)
@@ -776,10 +805,15 @@ async def test_retry_forwards_custom_endpoint_only_for_openai_endpoint(
cap_db = MagicMock()
cap_db.query.return_value.filter.return_value.all.return_value = []
write_db = MagicMock()
+ # retry_attempt opens, in order: an ordering rollback, the gated
+ # fast-fail check, the attempt lookup, a second ordering rollback, the
+ # authoritative gated recheck, and the atomic write.
mocker.patch.object(
chat,
"get_user_db_session",
- side_effect=_db_factory(cap_db, write_db, MagicMock()),
+ side_effect=_db_factory(
+ MagicMock(), cap_db, MagicMock(), MagicMock(), cap_db, write_db
+ ),
)
mocker.patch.object(
chat, "resolve_user_password", return_value=("pw", False)
diff --git a/tests/web/routers/test_followup_capacity_reject.py b/tests/web/routers/test_followup_capacity_reject.py
index cc41518003..6cc09f008a 100644
--- a/tests/web/routers/test_followup_capacity_reject.py
+++ b/tests/web/routers/test_followup_capacity_reject.py
@@ -20,6 +20,7 @@ These tests drive the sync worker directly, which is what lets them assert on
the race branch at all.
"""
+import threading
from unittest.mock import MagicMock, patch
import pytest
@@ -115,7 +116,12 @@ def _settings(max_concurrent):
@pytest.fixture
def patched(monkeypatch):
"""Patch the router's collaborators; yields a handle to configure counts."""
- state = {"session": None, "started": []}
+ state = {
+ "session": None,
+ "started": [],
+ "competing_gate_acquisitions": [],
+ "spawn_error": None,
+ }
def _run(counts, max_concurrent):
session = _FakeSession(counts)
@@ -147,6 +153,24 @@ def patched(monkeypatch):
def _start(*a, **k):
state["started"].append((a, k))
+ from local_deep_research.web.research_state import (
+ get_user_research_start_lock,
+ )
+
+ gate = get_user_research_start_lock("alice")
+
+ def compete_for_gate():
+ acquired = gate.acquire(blocking=False)
+ state["competing_gate_acquisitions"].append(acquired)
+ if acquired:
+ gate.release()
+
+ contender = threading.Thread(target=compete_for_gate)
+ contender.start()
+ contender.join(timeout=5)
+ assert not contender.is_alive()
+ if state["spawn_error"] is not None:
+ raise state["spawn_error"]
with (
patch(SESSION_CTX, _Ctx()),
@@ -193,6 +217,29 @@ def test_recheck_race_rejects_and_does_not_start_research(patched):
)
[email protected]("spawn_fails", [False, True])
+def test_followup_claim_keeps_gate_through_worker_registration(
+ patched, spawn_fails
+):
+ """Queue replay cannot inspect a new claim before spawn or cleanup."""
+ from local_deep_research.web.research_state import (
+ get_user_research_start_lock,
+ )
+
+ if spawn_fails:
+ patched["spawn_error"] = RuntimeError("synthetic spawn failure")
+
+ result = patched["run"](counts=[0, 1], max_concurrent=3)
+
+ assert patched["competing_gate_acquisitions"] == [False]
+ assert not get_user_research_start_lock("alice").locked()
+ if spawn_fails:
+ assert isinstance(result, JSONResponse)
+ assert result.status_code == 500
+ else:
+ assert result["success"] is True
+
+
def test_router_module_has_no_jsonify_reference():
"""Cheap structural pin: `jsonify` is a Flask name this module cannot
resolve, so any reintroduction is a latent NameError."""
diff --git a/tests/web/routers/test_start_research_port_gaps.py b/tests/web/routers/test_start_research_port_gaps.py
index f7353c4e38..368fe81f9b 100644
--- a/tests/web/routers/test_start_research_port_gaps.py
+++ b/tests/web/routers/test_start_research_port_gaps.py
@@ -766,3 +766,55 @@ def test_race_condition_after_commit_demotes_the_run_to_the_queue():
"session under the admission gate"
)
spawn.assert_not_called()
+
+
[email protected]("spawn_fails", [False, True])
+def test_direct_claim_keeps_gate_until_worker_registration(spawn_fails):
+ """A competing queue/reconciliation consumer cannot enter the claim gap.
+
+ Releasing the gate after the DB commit but before spawn lets the competing
+ thread acquire it. Both success and spawn rejection must release it later.
+ """
+ import threading
+
+ from local_deep_research.web.research_state import (
+ get_user_research_start_lock,
+ )
+ from local_deep_research.web.routers.research import _start_research_sync
+
+ session = _flow_session(active_count=0)
+ sm = _make_settings_manager()
+ lock = get_user_research_start_lock("testuser")
+ observed = []
+
+ def competing_consumer():
+ acquired = lock.acquire(blocking=False)
+ observed.append(acquired)
+ if acquired:
+ lock.release()
+
+ def at_registration(*_args, **_kwargs):
+ assert session.commit.called
+ contender = threading.Thread(target=competing_consumer)
+ contender.start()
+ contender.join(timeout=5)
+ assert not contender.is_alive()
+ if spawn_fails:
+ raise RuntimeError("synthetic worker start failure")
+ return MagicMock()
+
+ with _start_mocks(sm, session, spawn=at_registration) as spawn:
+ result = _start_research_sync(
+ {"query": "registration interval", "model": "llama3"},
+ "testuser",
+ "http://testserver/",
+ "session-1",
+ )
+
+ spawn.assert_called_once()
+ assert observed == [False]
+ assert not lock.locked()
+ if spawn_fails:
+ assert result.status_code == 500
+ else:
+ assert result["status"] == "success"
diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.py
index 2f73647b95..901371930e 100644
--- a/tests/web/test_js_fetch_parity.py
+++ b/tests/web/test_js_fetch_parity.py
@@ -997,7 +997,7 @@ LIVE_CASES = (
bad={"rating": "up"},
),
LiveCase(
- js_ref="components/chat.js:2631",
+ js_ref="components/chat.js:2717",
method="PATCH",
url=f"/api/chat/sessions/{NOPE_UUID}",
good={"title": "t"},
diff --git a/tests/web/test_research_state_registry.py b/tests/web/test_research_state_registry.py
index 9b4e966682..baaaa42973 100644
--- a/tests/web/test_research_state_registry.py
+++ b/tests/web/test_research_state_registry.py
@@ -367,16 +367,14 @@ def test_the_census_enumerates_every_known_registry_call_site():
),
(
"web/routers/chat.py",
- "send_message::_impl",
+ "_check_chat_research_slot_locked",
"is_research_thread_alive",
),
- ("web/routers/chat.py", "send_message::_impl", "cleanup_research"),
(
"web/routers/chat.py",
- "retry_attempt::_impl",
- "is_research_thread_alive",
+ "_check_chat_research_slot_locked",
+ "cleanup_research",
),
- ("web/routers/chat.py", "retry_attempt::_impl", "cleanup_research"),
(
"web/routers/followup.py",
"_start_followup_sync",
@@ -415,7 +413,7 @@ def test_the_census_enumerates_every_known_registry_call_site():
"cleanup_research",
),
("chat/service.py", "delete_session", "set_termination_flag"),
- ("chat/service.py", "delete_attempt", "cleanup_research"),
+ ("chat/service.py", "delete_attempt_rows", "cleanup_research"),
# --- background / server-side, ids never come from a request ---
(
"web/queue/processor_v2.py",