~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
perf(research): async cores for citation handlers and full-search URL filter — tranche 3 of #5854 (#6249)
LearningCircuitc7f01f08a05e
diff --git a/changelog.d/6249.misc.md b/changelog.d/6249.misc.mdnew file mode 100644index 0000000000..f4eadbda78--- /dev/null+++ b/changelog.d/6249.misc.md@@ -0,0 +1 @@+The citation handlers and full-search URL-quality filter gain async counterparts for the upcoming async research runner, while existing callers continue to use the synchronous APIs. Both citation streaming paths now accept message content blocks, preserve text spacing, and retain partial answers after a stream failure. Production async adoption still depends on the client lifecycle and token accounting work in #6293 and #6294. Third tranche of #5854.diff --git a/src/local_deep_research/citation_handlers/base_citation_handler.py b/src/local_deep_research/citation_handlers/base_citation_handler.pyindex 3f4671cf06..767ad3839c 100644--- a/src/local_deep_research/citation_handlers/base_citation_handler.py+++ b/src/local_deep_research/citation_handlers/base_citation_handler.py@@ -9,7 +9,7 @@ from langchain_core.documents import Documentfrom loguru import loggerfrom ..utilities.type_utils import unwrap_setting-from ..utilities.json_utils import get_llm_response_text+from ..utilities.json_utils import _coerce_content_blocks, get_llm_response_textclass BaseCitationHandler(ABC):@@ -25,6 +25,64 @@ class BaseCitationHandler(ABC):"""Set a callback that receives each streamed LLM token."""self.stream_callback = callback+ def _handle_chunk(self, chunk: Any, chunks: List[str]) -> None:+ """Normalize one streamed chunk, record it and push it to the callback.++ Shared by the sync and async streaming paths so the two differ only+ in the LLM call line.+ """+ text = (+ chunk+ if isinstance(chunk, str)+ else getattr(chunk, "content", str(chunk))+ )+ if isinstance(text, list):+ # Keep spaces and split reasoning tags intact until chunks join.+ text = _coerce_content_blocks(text)+ if text:+ chunks.append(text)+ # Bind to a local so mypy sees the Optional narrowed — the+ # attribute is Optional[Callable] and this helper is called+ # from both streaming paths after their own None checks.+ callback = self.stream_callback+ if callback is not None:+ try:+ callback(text)+ except Exception:+ logger.debug(+ "stream_callback failed"+ ) # Non-critical: don't break synthesis++ def _join_chunks(self, chunks: List[str]) -> str:+ """Normalize the joined chunks exactly like the invoke() path does.++ ``.stream()`` / ``.astream()`` bypass the normalization in+ ProcessingLLMWrapper.invoke / ainvoke, so without+ this a reasoning model's ``<think>…</think>`` would leak into the+ persisted answer. The live token stream is a separate concern.+ """+ return get_llm_response_text("".join(chunks))++ def _partial_after_stream_failure(self, chunks: List[str]) -> Optional[str]:+ """Resolve a mid-stream failure: partial text, or ``None`` to fall back.++ If any chunks already crossed the wire to the client, restarting via+ a full ``invoke()`` would (a) double-bill the LLM and (b) cause the+ frontend's accumulated streamed text to diverge from the new full+ response — the chat bubble then shows partial chunks while the DB row+ carries the invoke()-result. Only fall back when nothing was emitted.+ """+ if chunks:+ logger.warning(+ "Stream errored after {} chunks; returning partial "+ "content (no invoke() fallback to avoid double-bill "+ "and UI/DB divergence)",+ len(chunks),+ )+ return self._join_chunks(chunks)+ logger.debug("Stream failed before any chunk; falling back to invoke()")+ return None+def _invoke_with_streaming(self, prompt: str) -> str:"""Invoke the LLM, streaming tokens through the callback if set.@@ -32,64 +90,77 @@ class BaseCitationHandler(ABC):Falls back to a single ``invoke()`` call when no callback isregistered or when the LLM does not support ``.stream()``.+ Stays on the synchronous LangChain API: citation handlers run inside+ per-run research threads with no event loop, and langchain's async+ httpx client is process-cached and loop-bound, so driving the async+ core on a throwaway per-call loop would break or re-send every call+ after the first (see #6293).+Returns:The complete response text."""if self.stream_callback and hasattr(self.llm, "stream"):- chunks = []+ chunks: List[str] = []try:for chunk in self.llm.stream(prompt):- text = (- chunk- if isinstance(chunk, str)- else getattr(chunk, "content", str(chunk))- )- if text:- chunks.append(text)- try:- self.stream_callback(text)- except Exception:- logger.debug(- "stream_callback failed"- ) # Non-critical: don't break synthesis- # Normalize the joined chunks exactly like the invoke() path- # below: .stream() bypasses ProcessingLLMWrapper.invoke (which- # is the only place <think> blocks are stripped), so without- # this a reasoning model's <think>…</think> would leak into the- # persisted answer. The live token stream is a separate concern.- return get_llm_response_text("".join(chunks))+ self._handle_chunk(chunk, chunks)+ return self._join_chunks(chunks)except Exception:- # If any chunks already crossed the wire to the client,- # restarting via .invoke() would (a) double-bill the LLM- # and (b) cause the frontend's accumulated streamed text- # to diverge from the new full response — the chat bubble- # then shows partial chunks while the DB row carries the- # invoke()-result. Only fall back when nothing was emitted.- if chunks:- logger.warning(- "Stream errored after {} chunks; returning partial "- "content (no invoke() fallback to avoid double-bill "- "and UI/DB divergence)",- len(chunks),- )- return get_llm_response_text("".join(chunks))- logger.debug(- "Stream failed before any chunk; falling back to invoke()"- )+ partial = self._partial_after_stream_failure(chunks)+ if partial is not None:+ return partial- # No callback (non-chat research) or stream unavailable: delegate to- # the same normalization _invoke_text uses, so <think> blocks- # are stripped and str/object responses are handled uniformly.- return get_llm_response_text(self.llm.invoke(prompt))+ # No callback (non-chat research), stream unavailable, or the stream+ # died before the first chunk: delegate to the same normalization+ # _invoke_text uses, so <think> blocks are stripped and str/object+ # responses are handled uniformly.+ return self._invoke_text(prompt)++ async def _invoke_with_streaming_async(self, prompt: str) -> str:+ """Async counterpart of :meth:`_invoke_with_streaming`.++ Additive: no production caller awaits it yet. It exists for the+ research-runner tranche of #5854, which will drive the handlers from+ a single long-lived event loop; only then does the async LangChain+ API become safe to use here (#6293). The streaming semantics are the+ sync path's, shared through the same helpers — including returning+ the PARTIAL text after a mid-stream failure instead of restarting+ with a full call.+ """+ if self.stream_callback and hasattr(self.llm, "astream"):+ chunks: List[str] = []+ try:+ async for chunk in self.llm.astream(prompt):+ self._handle_chunk(chunk, chunks)+ return self._join_chunks(chunks)+ except Exception:+ partial = self._partial_after_stream_failure(chunks)+ if partial is not None:+ return partial++ return await self._invoke_text_async(prompt)def _invoke_text(self, prompt: str) -> str:"""Invoke the LLM and return normalized text.Handles both message objects (``.content``) and raw string responses,and strips ``<think>`` reasoning blocks via ``get_llm_response_text``.++ Synchronous for the same reason as :meth:`_invoke_with_streaming`."""return get_llm_response_text(self.llm.invoke(prompt))+ async def _invoke_text_async(self, prompt: str) -> str:+ """Async counterpart of :meth:`_invoke_text`.++ Additive: no production caller awaits it yet (see+ :meth:`_invoke_with_streaming_async`). Configured models expose+ ``ainvoke`` through ``ProcessingLLMWrapper``. Custom injected LLMs+ must also provide ``ainvoke`` to use this async API; it does not+ fall back to blocking synchronous invocation.+ """+ return get_llm_response_text(await self.llm.ainvoke(prompt))+def get_setting(self, key: str, default=None):"""Get a setting value from the snapshot."""if key in self.settings_snapshot:diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.pyindex e53c0cc23e..1d9fbc787c 100644--- a/src/local_deep_research/web_search_engines/engines/full_search.py+++ b/src/local_deep_research/web_search_engines/engines/full_search.py@@ -49,13 +49,11 @@ class FullSearchResults:# specific scope; used to evaluate per-URL fetches below.self.egress_context = egress_context- def check_urls(self, results: List[Dict], query: str) -> List[Dict]:- if not results:- return results-+ def _url_quality_prompt(self, results: List[Dict], query: str) -> str:+ """Build the URL-quality prompt shared by the sync and async paths."""now = datetime.now(UTC)current_time = now.strftime("%Y-%m-%d")- prompt = f"""ONLY Return a JSON array. The response contains no letters. Evaluate these URLs for:+ return f"""ONLY Return a JSON array. The response contains no letters. Evaluate these URLs for:1. Timeliness (today: {current_time})2. Factual accuracy (cross-reference major claims)3. Source reliability (prefer official company websites, established news outlets)@@ -68,17 +66,56 @@ class FullSearchResults:ONLY Return a JSON array of indices (0-based) and nothing else. No letters.Example response: \n[0, 2, 4]\n\n"""+ def _keep_selected(self, results: List[Dict], response: Any) -> List[Dict]:+ """Turn the LLM's index array into the filtered result list."""+ response_text = get_llm_response_text(response)+ good_indices = extract_json(response_text, expected_type=list)++ if good_indices is None:+ good_indices = []++ return [r for i, r in enumerate(results) if i in good_indices]++ def _url_filter_error_message(self, error: Exception) -> str:+ """Build the scrubbed log message for an LLM-side filter failure."""+ safe_msg = scrub_error(error)+ return f"URL filtering error ({type(error).__name__}): {safe_msg}"++ def _unfiltered_fallback(self, results: List[Dict]) -> List[Dict]:+ """Fall back to unfiltered results after an LLM-side filter failure.++ The ``logger.exception(...)`` call itself stays in each+ ``except Exception as e:`` block below (sync and async) rather than+ here, so the caught exception stays visible to+ ``.pre-commit-hooks/check-sensitive-logging.py`` — it tracks+ ``except ... as name`` bindings, and a helper taking the exception+ as a plain parameter falls outside what it can see.+ """+ logger.warning(+ "URL quality filter unavailable — returning {} unfiltered "+ "results as fallback",+ len(results),+ )+ return results # Fall back to original results on LLM error++ def check_urls(self, results: List[Dict], query: str) -> List[Dict]:+ """Filter results down to the URLs the LLM judges usable.++ Stays on the synchronous LangChain API: FullSearchResults runs inside+ per-run research threads with no event loop, and langchain's async+ httpx client is process-cached and loop-bound, so driving the async+ core on a throwaway per-call loop would break or re-send every call+ after the first (see #6293).+ """+ if not results:+ return results++ prompt = self._url_quality_prompt(results, query)+try:if self.llm is None:return results- response = self.llm.invoke(prompt)- response_text = get_llm_response_text(response)- good_indices = extract_json(response_text, expected_type=list)-- if good_indices is None:- good_indices = []-- return [r for i, r in enumerate(results) if i in good_indices]+ return self._keep_selected(results, self.llm.invoke(prompt))except PolicyDeniedError:# The URL-quality LLM was denied by egress policy (e.g. a cloud# LLM under require_local / PRIVATE_ONLY). Do NOT fall through to@@ -86,16 +123,37 @@ class FullSearchResults:# proceed despite the user's policy refusing the LLM. Fail closed.raiseexcept Exception as e:- safe_msg = scrub_error(e)- logger.exception(- f"URL filtering error ({type(e).__name__}): {safe_msg}"- )- logger.warning(- "URL quality filter unavailable — returning {} unfiltered "- "results as fallback",- len(results),- )- return results # Fall back to original results on LLM error+ safe_msg = self._url_filter_error_message(e)+ logger.exception(safe_msg)+ return self._unfiltered_fallback(results)++ async def _check_urls_async(+ self, results: List[Dict], query: str+ ) -> List[Dict]:+ """Async counterpart of :meth:`check_urls`.++ Additive: no production caller awaits it yet. It exists for the+ research-runner tranche of #5854, which will drive the search engines+ from a single long-lived event loop; only then does the async+ LangChain API become safe to use here (#6293).+ """+ if not results:+ return results++ prompt = self._url_quality_prompt(results, query)++ try:+ if self.llm is None:+ return results+ return self._keep_selected(results, await self.llm.ainvoke(prompt))+ except PolicyDeniedError:+ # Fail closed exactly like the sync path: an egress-policy denial+ # must not fall through to the unfiltered-results fallback.+ raise+ except Exception as e:+ safe_msg = self._url_filter_error_message(e)+ logger.exception(safe_msg)+ return self._unfiltered_fallback(results)def run(self, query: str):# Step 1: Get search resultsdiff --git a/tests/citation_handlers/conftest.py b/tests/citation_handlers/conftest.pyindex 94b195d163..2c20e968d6 100644--- a/tests/citation_handlers/conftest.py+++ b/tests/citation_handlers/conftest.py@@ -1,23 +1,42 @@"""Shared fixtures for citation handler tests."""import pytest-from unittest.mock import Mock+from unittest.mock import AsyncMock, Mock+++def _make_mock_llm(response):+ """A mock LLM exposing the full sync + async LangChain surface.++ ``stream``/``astream`` return REAL (async) generators rather than bare+ Mocks: a Mock return value is not iterable, so a test that sets a stream+ callback would silently land in the handler's ``except Exception``+ fallback and quietly test the wrong branch.+ """+ llm = Mock()+ llm.invoke = Mock(return_value=response)+ llm.ainvoke = AsyncMock(return_value=response)++ def _stream(_prompt):+ yield response++ async def _astream(_prompt):+ yield response++ llm.stream = Mock(side_effect=_stream)+ llm.astream = Mock(side_effect=_astream)+ return llm@pytest.fixturedef mock_llm():"""Create a mock LLM that returns configurable responses."""- llm = Mock()- llm.invoke.return_value = Mock(content="Test response with citation [1].")- return llm+ return _make_mock_llm(Mock(content="Test response with citation [1]."))@pytest.fixturedef mock_llm_string_response():"""Create a mock LLM that returns string responses directly."""- llm = Mock()- llm.invoke.return_value = "Test string response with citation [1]."- return llm+ return _make_mock_llm("Test string response with citation [1].")@pytest.fixturediff --git a/tests/citation_handlers/test_async_cores.py b/tests/citation_handlers/test_async_cores.pynew file mode 100644index 0000000000..cef345650c--- /dev/null+++ b/tests/citation_handlers/test_async_cores.py@@ -0,0 +1,301 @@+"""The sync/async split of the citation-handler LLM calls (#5854).++Two invariants are pinned here:++* the sync entry points (``_invoke_text`` / ``_invoke_with_streaming``) stay+ on the synchronous LangChain API and never start an event loop — langchain's+ async httpx client is process-cached and loop-bound, so a throwaway per-call+ loop would break or re-send every call after the first (#6293);+* the async cores (``_invoke_text_async`` /+ ``_invoke_with_streaming_async``) use only the async API. They are additive:+ no production caller awaits them yet.+"""++import asyncio+from unittest.mock import AsyncMock, Mock++import pytest++from local_deep_research.citation_handlers.standard_citation_handler import (+ StandardCitationHandler,+)+++def _forbid_event_loops(monkeypatch):+ """Make any attempt to start an event loop fail loudly."""++ def _boom(*args, **kwargs):+ raise AssertionError(+ "the sync path must not create an event loop (#6293)"+ )++ monkeypatch.setattr(asyncio, "run", _boom)+ monkeypatch.setattr(asyncio, "new_event_loop", _boom)+ monkeypatch.setattr(asyncio, "Runner", _boom)+++def _dual_api_llm(chunks=None, response="full response"):+ """An LLM exposing BOTH the sync and the async API.++ Exposing both is what makes the sync-path assertions discriminating: the+ handler could reach either, and the test proves it picks the sync one.+ """++ async def _astream(_prompt):+ for chunk in chunks or []:+ yield Mock(content=chunk)++ def _stream(_prompt):+ for chunk in chunks or []:+ yield Mock(content=chunk)++ llm = Mock()+ llm.invoke = Mock(return_value=Mock(content=response))+ llm.ainvoke = AsyncMock(return_value=Mock(content=response))+ llm.stream = Mock(side_effect=_stream)+ llm.astream = Mock(side_effect=_astream)+ return llm+++class TestSyncEntryPointsStartNoEventLoop:+ """The sync entry points use ``invoke``/``stream``, no loop involved."""++ def test_invoke_text_uses_sync_invoke(self, monkeypatch):+ _forbid_event_loops(monkeypatch)+ llm = _dual_api_llm(response="sync answer")+ handler = StandardCitationHandler(llm=llm)++ assert handler._invoke_text("prompt") == "sync answer"++ llm.invoke.assert_called_once_with("prompt")+ llm.ainvoke.assert_not_called()++ def test_invoke_with_streaming_uses_sync_stream(self, monkeypatch):+ _forbid_event_loops(monkeypatch)+ llm = _dual_api_llm(chunks=["one ", "two"])+ handler = StandardCitationHandler(llm=llm)+ callback = Mock()+ handler.set_stream_callback(callback)++ assert handler._invoke_with_streaming("prompt") == "one two"++ llm.stream.assert_called_once_with("prompt")+ llm.astream.assert_not_called()+ llm.ainvoke.assert_not_called()+ assert callback.call_count == 2++ def test_invoke_with_streaming_without_callback_uses_sync_invoke(+ self, monkeypatch+ ):+ _forbid_event_loops(monkeypatch)+ llm = _dual_api_llm(chunks=["ignored"], response="sync answer")+ handler = StandardCitationHandler(llm=llm)++ assert handler._invoke_with_streaming("prompt") == "sync answer"++ llm.invoke.assert_called_once_with("prompt")+ llm.stream.assert_not_called()+ llm.ainvoke.assert_not_called()+ llm.astream.assert_not_called()+++class TestAsyncCores:+ """The async cores use only ``ainvoke``/``astream``."""++ @pytest.mark.asyncio+ async def test_invoke_text_async_awaits_ainvoke(self):+ llm = _dual_api_llm(response="async answer")+ handler = StandardCitationHandler(llm=llm)++ assert await handler._invoke_text_async("prompt") == "async answer"++ llm.ainvoke.assert_awaited_once_with("prompt")+ llm.invoke.assert_not_called()++ @pytest.mark.asyncio+ async def test_invoke_with_streaming_async_awaits_astream(self):+ llm = _dual_api_llm(chunks=["one ", "two"])+ handler = StandardCitationHandler(llm=llm)+ callback = Mock()+ handler.set_stream_callback(callback)++ result = await handler._invoke_with_streaming_async("prompt")++ assert result == "one two"+ llm.astream.assert_called_once_with("prompt")+ llm.stream.assert_not_called()+ llm.invoke.assert_not_called()+ assert callback.call_count == 2++ @pytest.mark.asyncio+ async def test_invoke_with_streaming_async_without_callback_awaits_ainvoke(+ self,+ ):+ llm = _dual_api_llm(chunks=["ignored"], response="async answer")+ handler = StandardCitationHandler(llm=llm)++ result = await handler._invoke_with_streaming_async("prompt")++ assert result == "async answer"+ llm.ainvoke.assert_awaited_once_with("prompt")+ llm.astream.assert_not_called()+ llm.invoke.assert_not_called()++ @pytest.mark.asyncio+ async def test_invoke_with_streaming_async_falls_back_before_first_chunk(+ self,+ ):+ """A stream that dies before emitting anything falls back to ainvoke."""+ llm = _dual_api_llm(response="async fallback")+ llm.astream = Mock(side_effect=Exception("stream error"))+ handler = StandardCitationHandler(llm=llm)+ handler.set_stream_callback(Mock())++ result = await handler._invoke_with_streaming_async("prompt")++ assert result == "async fallback"+ llm.astream.assert_called_once()+ llm.ainvoke.assert_awaited_once_with("prompt")++ @pytest.mark.asyncio+ async def test_invoke_with_streaming_async_returns_empty_partial_after_think_only_failure(+ self,+ ):+ """A mid-stream failure whose only chunks are ``<think>...</think>``+ content strips to an empty string after normalization. That empty+ partial must still be returned — not treated as "nothing happened"+ (which would restart with a fresh, double-billed ``ainvoke()`` call).+ Pins the ``is not None`` check in ``_partial_after_stream_failure``+ callers: a truthiness check would treat "" as falsy and fall back.+ """++ async def _think_only(_prompt):+ yield Mock(content="<think>")+ yield Mock(content="x</think>")+ raise Exception("connection dropped")++ llm = _dual_api_llm(response="never used")+ llm.astream = Mock(side_effect=_think_only)+ handler = StandardCitationHandler(llm=llm)+ received = []+ handler.set_stream_callback(received.append)++ result = await handler._invoke_with_streaming_async("prompt")++ assert result == ""+ llm.ainvoke.assert_not_called()+ llm.invoke.assert_not_called()++ @pytest.mark.asyncio+ async def test_invoke_with_streaming_async_returns_partial_on_mid_stream_failure(+ self,+ ):+ """Same contract as the sync path: no full-call restart after chunks+ already reached the client (double-bill + UI/DB divergence)."""++ async def _partial(_prompt):+ yield Mock(content="partial ")+ yield Mock(content="content")+ raise Exception("connection dropped")++ llm = _dual_api_llm(response="never used")+ llm.astream = Mock(side_effect=_partial)+ handler = StandardCitationHandler(llm=llm)+ received = []+ handler.set_stream_callback(received.append)++ result = await handler._invoke_with_streaming_async("prompt")++ assert result == "partial content"+ assert received == ["partial ", "content"]+ llm.ainvoke.assert_not_called()+ llm.invoke.assert_not_called()+++class TestStreamContentBlocks:+ """Sync and async streams accept message content blocks as text chunks."""++ @pytest.mark.asyncio+ @pytest.mark.parametrize("use_async", [False, True])+ @pytest.mark.parametrize(+ "chunks,received,answer",+ [+ (+ [+ [{"type": "text", "text": "one "}],+ ["two", {"text": " three"}],+ ],+ ["one ", "two three"],+ "one two three",+ ),+ (+ [+ [{"type": "tool_use", "id": "tool"}],+ [{"type": "thinking", "thinking": "hidden"}],+ ],+ [],+ "",+ ),+ (+ [+ [{"type": "text", "text": "<thi"}],+ [{"text": "nk>hidden</think>"}],+ [{"text": " answer"}],+ ],+ ["<thi", "nk>hidden</think>", " answer"],+ "answer",+ ),+ ],+ ids=["text-and-spaces", "nontext-only", "split-think-tags"],+ )+ async def test_content_blocks(self, use_async, chunks, received, answer):+ llm = _dual_api_llm(chunks=chunks)+ handler = StandardCitationHandler(llm=llm)+ actual = []+ handler.set_stream_callback(actual.append)++ if use_async:+ result = await handler._invoke_with_streaming_async("prompt")+ llm.astream.assert_called_once_with("prompt")+ llm.stream.assert_not_called()+ else:+ result = handler._invoke_with_streaming("prompt")+ llm.stream.assert_called_once_with("prompt")+ llm.astream.assert_not_called()++ assert result == answer+ assert actual == received+ assert all(isinstance(chunk, str) for chunk in actual)+ llm.invoke.assert_not_called()+ llm.ainvoke.assert_not_called()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("use_async", [False, True])+ async def test_partial_blocks_do_not_restart(self, use_async):+ def _partial(_prompt):+ yield Mock(content=[{"type": "text", "text": "partial "}])+ yield Mock(content=[{"text": "answer"}])+ raise RuntimeError("connection dropped")++ async def _apartial(prompt):+ for chunk in _partial(prompt):+ yield chunk++ llm = _dual_api_llm(response="never used")+ llm.stream = Mock(side_effect=_partial)+ llm.astream = Mock(side_effect=_apartial)+ handler = StandardCitationHandler(llm=llm)+ received = []+ handler.set_stream_callback(received.append)++ if use_async:+ result = await handler._invoke_with_streaming_async("prompt")+ llm.stream.assert_not_called()+ else:+ result = handler._invoke_with_streaming("prompt")+ llm.astream.assert_not_called()++ assert result == "partial answer"+ assert received == ["partial ", "answer"]+ llm.invoke.assert_not_called()+ llm.ainvoke.assert_not_called()diff --git a/tests/citation_handlers/test_streaming.py b/tests/citation_handlers/test_streaming.pyindex ec56c53975..066e5f06a0 100644--- a/tests/citation_handlers/test_streaming.py+++ b/tests/citation_handlers/test_streaming.py@@ -154,6 +154,35 @@ class TestStreamingInvocation:mock_llm.invoke.assert_called_once()assert result == "Fallback response"+ def test_streaming_llm_that_fails_immediately_falls_back_to_invoke(self):+ """The ``should_fail`` streaming stub reaches the invoke() fallback.++ ``MockLLMWithStreaming(should_fail=True)`` raises out of ``stream()``+ before yielding anything, which is the one case where the handler is+ allowed to restart with a full ``invoke()`` — nothing has crossed the+ wire to the client yet, so there is no double-bill and no UI/DB+ divergence. Unlike the Mock-based test above, this one exercises the+ fallback through a duck-typed generator-based LLM.+ """+ from local_deep_research.citation_handlers.standard_citation_handler import (+ StandardCitationHandler,+ )++ mock_llm = MockLLMWithStreaming(+ chunks=["never", " emitted"], should_fail=True+ )+ handler = StandardCitationHandler(llm=mock_llm)+ callback = Mock()+ handler.set_stream_callback(callback)++ result = handler._invoke_with_streaming("test prompt")++ assert mock_llm.stream_called+ callback.assert_not_called()+ mock_llm.invoke.assert_called_once_with("test prompt")+ # invoke()'s canned response is the joined chunk text.+ assert result == "never emitted"+def test_invoke_with_streaming_returns_partial_after_mid_stream_failure(self,):diff --git a/tests/web_search_engines/engines/test_full_search.py b/tests/web_search_engines/engines/test_full_search.pyindex a8d4b7b290..ee0842a6bb 100644--- a/tests/web_search_engines/engines/test_full_search.py+++ b/tests/web_search_engines/engines/test_full_search.py@@ -7,7 +7,9 @@ Tests cover:- Full search workflow"""-from unittest.mock import Mock, patch+import asyncio+from unittest.mock import AsyncMock, Mock, patch+import pytest@@ -146,6 +148,28 @@ class TestCheckUrls:assert filtered == results+ def test_check_urls_prompt_contains_query_and_results(self):+ """The prompt passed to llm.invoke carries the query and results."""+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_llm = Mock()+ mock_llm.invoke.return_value = Mock(content="[0]")+ mock_web_search = Mock()++ engine = FullSearchResults(llm=mock_llm, web_search=mock_web_search)++ results = [+ {"link": "https://example.com/1", "title": "Result 1"},+ ]++ engine.check_urls(results, "unique test query xyz123")++ prompt = mock_llm.invoke.call_args[0][0]+ assert "unique test query xyz123" in prompt+ assert "https://example.com/1" in prompt+def test_check_urls_invalid_json(self):"""Check URLs returns empty on invalid JSON response."""from local_deep_research.web_search_engines.engines.full_search import (@@ -455,3 +479,147 @@ class TestJSRenderingForwardingFromSettingsSnapshot:[{"link": "https://example.com/1", "title": "T"}])assert mock_batch.call_args.kwargs.get("enable_js_rendering") is True+++class TestCheckUrlsSyncAsyncSplit:+ """The sync/async split of the URL-quality LLM call (#5854).++ ``check_urls`` stays on the synchronous LangChain API and starts no event+ loop — langchain's async httpx client is process-cached and loop-bound, so+ a throwaway per-call loop would break or re-send every call after the+ first (#6293). ``_check_urls_async`` is the additive async counterpart;+ no production caller awaits it yet.+ """++ @staticmethod+ def _dual_api_llm(content="[0]"):+ """An LLM exposing BOTH APIs, so the assertions discriminate."""+ llm = Mock()+ llm.invoke = Mock(return_value=Mock(content=content))+ llm.ainvoke = AsyncMock(return_value=Mock(content=content))+ return llm++ @staticmethod+ def _forbid_event_loops(monkeypatch):+ def _boom(*args, **kwargs):+ raise AssertionError(+ "check_urls must not create an event loop (#6293)"+ )++ monkeypatch.setattr(asyncio, "run", _boom)+ monkeypatch.setattr(asyncio, "new_event_loop", _boom)+ monkeypatch.setattr(asyncio, "Runner", _boom)++ def test_check_urls_uses_sync_invoke_and_starts_no_loop(self, monkeypatch):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ self._forbid_event_loops(monkeypatch)+ mock_llm = self._dual_api_llm("[1]")+ engine = FullSearchResults(llm=mock_llm, web_search=Mock())++ results = [+ {"link": "https://example.com/1", "title": "Result 1"},+ {"link": "https://example.com/2", "title": "Result 2"},+ ]++ filtered = engine.check_urls(results, "test query")++ assert filtered == [results[1]]+ mock_llm.invoke.assert_called_once()+ mock_llm.ainvoke.assert_not_called()++ def test_check_urls_empty_results_starts_no_loop(self, monkeypatch):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ self._forbid_event_loops(monkeypatch)+ mock_llm = self._dual_api_llm()+ engine = FullSearchResults(llm=mock_llm, web_search=Mock())++ assert engine.check_urls([], "test query") == []+ mock_llm.invoke.assert_not_called()+ mock_llm.ainvoke.assert_not_called()++ @pytest.mark.asyncio+ async def test_check_urls_async_awaits_ainvoke(self):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_llm = self._dual_api_llm("[1]")+ engine = FullSearchResults(llm=mock_llm, web_search=Mock())++ results = [+ {"link": "https://example.com/1", "title": "Result 1"},+ {"link": "https://example.com/2", "title": "Result 2"},+ ]++ filtered = await engine._check_urls_async(results, "test query")++ assert filtered == [results[1]]+ mock_llm.ainvoke.assert_awaited_once()+ mock_llm.invoke.assert_not_called()++ @pytest.mark.asyncio+ async def test_check_urls_async_falls_back_to_unfiltered_on_error(self):+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_llm = self._dual_api_llm()+ mock_llm.ainvoke = AsyncMock(side_effect=Exception("LLM error"))+ engine = FullSearchResults(llm=mock_llm, web_search=Mock())++ results = [{"link": "https://example.com/1", "title": "Result 1"}]++ assert await engine._check_urls_async(results, "q") == results++ def test_check_urls_reraises_policy_denied(self):+ """Fail closed exactly like the async path: an egress-policy denial+ must not fall through to the unfiltered-results fallback."""+ from local_deep_research.security.egress.policy import (+ Decision,+ PolicyDeniedError,+ )+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_llm = self._dual_api_llm()+ denial = PolicyDeniedError(+ Decision(allowed=False, reason="require_local")+ )+ mock_llm.invoke = Mock(side_effect=denial)+ engine = FullSearchResults(llm=mock_llm, web_search=Mock())++ with pytest.raises(PolicyDeniedError):+ engine.check_urls(+ [{"link": "https://example.com/1", "title": "Result 1"}], "q"+ )++ @pytest.mark.asyncio+ async def test_check_urls_async_reraises_policy_denied(self):+ """Fail closed exactly like the sync path: an egress-policy denial+ must not fall through to the unfiltered-results fallback."""+ from local_deep_research.security.egress.policy import (+ Decision,+ PolicyDeniedError,+ )+ from local_deep_research.web_search_engines.engines.full_search import (+ FullSearchResults,+ )++ mock_llm = self._dual_api_llm()+ denial = PolicyDeniedError(+ Decision(allowed=False, reason="require_local")+ )+ mock_llm.ainvoke = AsyncMock(side_effect=denial)+ engine = FullSearchResults(llm=mock_llm, web_search=Mock())++ with pytest.raises(PolicyDeniedError):+ await engine._check_urls_async(+ [{"link": "https://example.com/1", "title": "Result 1"}], "q"+ )