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(llm): cancel ongoing LLM request when research/chat is stopped (#6743)

S55fb1d3429ab
diff --git a/changelog.d/+cancel-ongoing-llm-on-stop.bugfix.md b/changelog.d/+cancel-ongoing-llm-on-stop.bugfix.md
new file mode 100644
index 0000000000..d153b7a23d
--- /dev/null
+++ b/changelog.d/+cancel-ongoing-llm-on-stop.bugfix.md
@@ -0,0 +1,8 @@
+Stopping a running research or chat now also aborts its in-flight LLM
+request. LLM wrappers resolve the run's termination flag per call and,
+when streaming preserves token usage (or the output is a plain message),
+consume the model via streaming, so a Stop raised mid-generation aborts
+within one chunk instead of waiting for the full response. Custom
+OpenAI-compatible endpoints without `llm.openai_endpoint.stream_usage`
+and structured-output calls stay on direct invoke (with pre/post checks)
+so token/cost metrics and the dict/Pydantic contract are preserved.
diff --git a/src/local_deep_research/citation_handlers/base_citation_handler.py b/src/local_deep_research/citation_handlers/base_citation_handler.py
index 08645364f2..46f0764fa9 100644
--- a/src/local_deep_research/citation_handlers/base_citation_handler.py
+++ b/src/local_deep_research/citation_handlers/base_citation_handler.py
@@ -223,6 +223,27 @@ class BaseCitationHandler(ABC):
for chunk in self.llm.stream(prompt):
before = len(chunks)
self._handle_chunk(chunk, chunks)
+ # Cooperative abort for unwrapped/custom LLMs whose
+ # own stream() does not check the flag (wrapped LLMs
+ # already raise per chunk via ProcessingLLMWrapper).
+ # Resolved from the thread's search context so handlers
+ # holding a raw model still stop promptly on Stop.
+ # NOTE: ResearchTerminatedException inherits
+ # BaseException, so the ``except Exception`` below lets
+ # it propagate while swallowing only lookup errors.
+ try:
+ from ..llm.cancellation import (
+ get_current_research_id,
+ raise_if_terminated,
+ )
+
+ _rid = get_current_research_id()
+ if _rid:
+ raise_if_terminated(_rid)
+ except Exception:
+ logger.debug(
+ "Termination-flag lookup failed (non-critical)"
+ )
repeated = guard.feed(chunks[before:])
if repeated is not None:
self._log_repetition_abort(repeated, chunks)
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 94f55f05a3..44e1e3eb7f 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -427,9 +427,45 @@ def _log_llm_error(error: Exception) -> None:
class ProcessingLLMWrapper:
- def __init__(self, base_llm, *, owns_llm: bool = True):
+ def __init__(
+ self,
+ base_llm,
+ *,
+ owns_llm: bool = True,
+ research_id=None,
+ provider=None,
+ settings_snapshot=None,
+ structured_output: bool = False,
+ ):
self.base_llm = base_llm
self._owns_llm = owns_llm
+ # Cancellation scope: explicit id wins, otherwise the thread's
+ # search context is consulted per call (see _effective_research_id).
+ # Stored under both names — ``research_id`` for readability and
+ # ``_ldr_research_id`` for the shared bind helper in
+ # llm/cancellation.py (which propagates through nested wrappers).
+ self.research_id = research_id
+ self._ldr_research_id = research_id
+ # Token-accounting gate: the stream-under-invoke path silently
+ # converts every scoped invoke into a streaming request. For the
+ # ``openai_endpoint`` provider that loses token/cost metrics unless
+ # ``llm.openai_endpoint.stream_usage`` is enabled (custom gateways
+ # omit usage on streams, or reject stream_options outright).
+ # The provider + snapshot let _stream_cancel_allowed() make that
+ # tradeoff a decision instead of an accident.
+ self._provider = provider
+ self._settings_snapshot = settings_snapshot
+ # Structured-output contract: a wrapper created via
+ # with_structured_output() wraps a Runnable whose invoke/​stream
+ # yield dicts/Pydantic models, not AIMessageChunks. Reassembling
+ # those through _combine_stream_chunks would corrupt them into an
+ # AIMessage holding str(dict). Such wrappers must use the direct
+ # invoke path (pre/post termination checks still apply).
+ # A bound wrapper must not outlive its run: the id is resolved per
+ # call so re-binding for the next run takes effect without
+ # reconstructing the LLM, and a stale binding is only ever used
+ # for a fail-fast/post-check, never to route into another run.
+ self._ldr_structured_output = structured_output
@staticmethod
def _normalize_response(response: Any) -> Any:
@@ -470,28 +506,627 @@ class ProcessingLLMWrapper:
def _log_llm_error(error: Exception) -> None:
_log_llm_error(error)
+ def _effective_research_id(self):
+ """Resolve the cancellation scope for this call.
+
+ Precedence: explicit ctor id > ``_ldr_research_id`` binding >
+ current thread's search context. Consulted per call so a late
+ ``bind_llm_to_research`` (or context propagation into pool
+ threads) takes effect without reconstructing the LLM.
+ """
+ from ..llm.cancellation import effective_research_id
+
+ return effective_research_id(self, self.research_id)
+
+ def _check_terminated(self, research_id=None):
+ """Raise ``ResearchTerminatedException`` if Stop was requested."""
+ from ..llm.cancellation import raise_if_terminated
+
+ rid = (
+ research_id
+ if research_id is not None
+ else self._effective_research_id()
+ )
+ if rid:
+ raise_if_terminated(rid)
+
+ def _walk_base_chain(self):
+ """Yield self.base_llm and each nested ``base_llm`` once.
+
+ Covers ``Processing -> RateLimited -> ChatModel`` without
+ recursing (each level is a plain attribute read). Cycle-safe:
+ a mis-wired test double that points at itself terminates.
+ """
+ seen = set()
+ cur = getattr(self, "base_llm", None)
+ while cur is not None and id(cur) not in seen:
+ seen.add(id(cur))
+ yield cur
+ try:
+ cur = getattr(cur, "base_llm", None)
+ except Exception:
+ break
+
+ def _underlying_stream_usage(self) -> bool:
+ """True if any wrapped model opts into usage on streams.
+
+ Covers ``ChatOpenAI(stream_usage=True)`` and equivalents that
+ stash ``stream_options.include_usage`` in ``model_kwargs``.
+ """
+ for base in self._walk_base_chain():
+ try:
+ if getattr(base, "stream_usage", None):
+ return True
+ mk = getattr(base, "model_kwargs", None)
+ if isinstance(mk, dict):
+ so = mk.get("stream_options", {})
+ if isinstance(so, dict) and so.get("include_usage"):
+ return True
+ except Exception:
+ continue
+ return False
+
+ def _underlying_disables_streaming(self) -> bool:
+ """True if any wrapped model forbids streaming."""
+ for base in self._walk_base_chain():
+ try:
+ if getattr(base, "disable_streaming", False):
+ return True
+ except Exception:
+ continue
+ return False
+
+ def _stream_cancel_allowed(self) -> bool:
+ """Whether invoke may stream under the hood for cancellation.
+
+ Two gates, both conservative (False keeps the direct invoke path
+ with pre/post termination checks, so Stop still aborts between
+ calls — only mid-generation abort is lost):
+
+ 1. Structured-output wrappers never stream: their chunks are
+ dicts/Pydantic models, and reassembly would corrupt them into
+ ``AIMessage(str(dict))``.
+ 2. ``openai_endpoint`` without usage-on-stream never streams:
+ the reassembled message would carry no ``usage_metadata`` and
+ token/cost metrics would silently go to zero. Opt in via the
+ ``llm.openai_endpoint.stream_usage`` setting (or an underlying
+ model built with ``stream_usage=True``). Other providers stream
+ because their streamed chunks preserve usage via
+ ``usage_metadata``/``response_metadata``.
+ """
+ if getattr(self, "_ldr_structured_output", False):
+ return False
+ if self._underlying_disables_streaming():
+ return False
+ provider = getattr(self, "_provider", None)
+ try:
+ from ..llm.providers.base import normalize_provider
+
+ provider = normalize_provider(provider) if provider else None
+ except Exception:
+ logger.debug(
+ "Provider normalization failed; treating as unknown provider",
+ exc_info=True,
+ )
+ if provider == "openai_endpoint":
+ try:
+ from .thread_settings import get_setting_from_snapshot
+
+ snapshot = getattr(self, "_settings_snapshot", None)
+ if get_setting_from_snapshot(
+ "llm.openai_endpoint.stream_usage",
+ False,
+ settings_snapshot=snapshot,
+ ):
+ return True
+ except Exception:
+ logger.debug(
+ "stream_usage setting lookup failed; "
+ "falling back to model capability",
+ exc_info=True,
+ )
+ # Model-level opt-in covers callers that built ChatOpenAI with
+ # stream_usage=True but have no settings context on this thread.
+ if self._underlying_stream_usage():
+ return True
+ return False
+ # Unknown provider but recognisably a ChatOpenAI-style model with
+ # a custom base_url and no usage-on-stream: same zero-metrics trap
+ # as openai_endpoint (e.g. thread-context fallback where the wrapper
+ # was built without a provider label). Be conservative.
+ for base in self._walk_base_chain():
+ try:
+ if hasattr(base, "stream_usage") and hasattr(
+ base, "openai_api_base"
+ ):
+ if getattr(base, "stream_usage", None):
+ return True
+ if getattr(base, "openai_api_base", None):
+ return False
+ # Default OpenAI endpoint without an explicit opt-in:
+ # the validator enables stream_usage for the default
+ # URL, so a falsy value here is unexpected — fall
+ # through to the safe default below.
+ return False
+ except Exception:
+ continue
+ return True
+
+ @staticmethod
+ def _is_structured_chunk(chunk: Any) -> bool:
+ """True for structured-output chunks (dicts/Pydantic, no .content)."""
+ if isinstance(chunk, dict):
+ return True
+ if isinstance(chunk, str):
+ return False
+ if hasattr(chunk, "content"):
+ return False
+ try:
+ from pydantic import BaseModel as _PydanticBaseModel
+
+ if isinstance(chunk, _PydanticBaseModel):
+ return True
+ except Exception:
+ logger.debug(
+ "Pydantic structured-chunk check failed; treating as unstructured",
+ exc_info=True,
+ )
+ return False
+
+ @staticmethod
+ def _combine_stream_chunks(chunks):
+ """Combine streamed chunks into a single response object.
+
+ ``AIMessageChunk`` parts merge with ``+`` (preserves ``tool_calls``,
+ ``additional_kwargs`` and content-block lists); the merged chunk is
+ converted to a plain ``AIMessage`` so downstream code sees the same
+ shape as ``invoke()``. Plain-string chunks (some test doubles)
+ are joined into an ``AIMessage``. Returns ``None`` when *chunks*
+ is empty (test doubles only — real models raise rather than yield
+ zero chunks) so the caller can fall back to a direct ``invoke()``.
+
+ Structured-output chunks (dicts/Pydantic models without ``.content``)
+ are never reassembled here: returning ``None`` lets the caller fall
+ back to a direct ``invoke()`` that preserves the contract instead of
+ corrupting the payload into ``AIMessage(str(dict))``. That fallback
+ is a second upstream request for one logical call (token callbacks
+ fire twice); callers log a warning when it happens after chunks
+ were already consumed.
+ """
+ if not chunks:
+ return None
+ for chunk in chunks:
+ if isinstance(chunk, dict):
+ return None
+ if isinstance(chunk, str):
+ continue
+ if hasattr(chunk, "content"):
+ continue
+ # Pydantic models (and other parsed outputs) have no .content:
+ # treat as structured, not as text to stringify.
+ try:
+ from pydantic import BaseModel as _PydanticBaseModel
+
+ if isinstance(chunk, _PydanticBaseModel):
+ return None
+ except Exception:
+ logger.debug(
+ "Pydantic structured-chunk check failed; continuing",
+ exc_info=True,
+ )
+ # Unknown non-message shape — only safe to stringify when it
+ # is clearly a message-like object; otherwise fall back.
+ if not hasattr(chunk, "tool_calls") and not hasattr(
+ chunk, "additional_kwargs"
+ ):
+ return None
+ try:
+ # Fast path: message chunks support addition.
+ combined = chunks[0]
+ for chunk in chunks[1:]:
+ try:
+ combined = combined + chunk
+ except Exception:
+ # Mixed shapes — fall back to text join below.
+ combined = None
+ break
+ if combined is not None and hasattr(combined, "content"):
+ try:
+ from langchain_core.messages.utils import (
+ message_chunk_to_message,
+ )
+
+ return message_chunk_to_message(combined)
+ except Exception:
+ return combined
+ except Exception:
+ logger.debug(
+ "Stream-chunk combine via '+' failed; using text fallback"
+ )
+ # Text fallback: join content/text of each chunk.
+ from ..utilities.json_utils import _coerce_content_blocks
+
+ parts = []
+ for chunk in chunks:
+ text = (
+ chunk
+ if isinstance(chunk, str)
+ else getattr(chunk, "content", None)
+ )
+ if text is None:
+ text = str(chunk)
+ if isinstance(text, list):
+ try:
+ text = _coerce_content_blocks(text)
+ except Exception:
+ text = "".join(str(p) for p in text)
+ if text:
+ parts.append(str(text))
+ if not parts:
+ return None
+ return AIMessage(content="".join(parts))
+
+ def _invoke_via_stream(self, *args: Any, **kwargs: Any):
+ """Implement ``invoke`` as stream+reassemble with per-chunk cancel.
+
+ Returns the combined response, or ``None`` when streaming is
+ unavailable (no ``stream`` attr), disallowed (structured-output or
+ usage-unsafe endpoint — see :meth:`_stream_cancel_allowed`), or
+ produced zero chunks (only empty test-double generators — real
+ LangChain models raise inside the generator on failure rather
+ than yielding zero chunks). The caller then falls back to a
+ direct ``invoke()``. Raises ``ResearchTerminatedException``
+ promptly when the flag is set mid-generation; the generator is
+ closed so the underlying HTTP response is released instead of
+ leaking to GC.
+
+ Mid-stream structured fallback (a dict/Pydantic chunk after one
+ or more message chunks were already pulled) also returns ``None``,
+ so the caller issues a *second* upstream request for the same
+ logical call — token callbacks fire for both attempts. No in-app
+ path produces such mixed shapes today (structured-output wrappers
+ are excluded up front via :meth:`_stream_cancel_allowed`), so this
+ is defense-in-depth only; a warning is logged when it triggers so
+ the double request is visible instead of silent.
+ """
+ if getattr(self, "_ldr_structured_output", False):
+ return None
+ stream_fn = getattr(self.base_llm, "stream", None)
+ if stream_fn is None:
+ return None
+ research_id = self._effective_research_id()
+ try:
+ gen = stream_fn(*args, **kwargs)
+ except Exception:
+ logger.debug(
+ "Sync stream creation failed; falling back to direct invoke",
+ exc_info=True,
+ )
+ return None
+ chunks = []
+ try:
+ for chunk in gen:
+ if research_id:
+ self._check_terminated(research_id)
+ # Structured-output runnables yield dicts/models: abort the
+ # streaming attempt and fall back to direct invoke rather
+ # than corrupting the contract.
+ if self._is_structured_chunk(chunk):
+ # NOTE: package logging is disabled by default
+ # (local_deep_research/__init__.py); this surfaces
+ # once the app enables it at startup.
+ logger.warning(
+ "Sync stream yielded structured chunk after "
+ f"{len(chunks)} message chunk(s); falling back "
+ "to direct invoke issues a second upstream "
+ "request for one logical call (token callbacks "
+ "fire twice)"
+ )
+ try:
+ close = getattr(gen, "close", None)
+ if close is not None:
+ close()
+ except Exception:
+ logger.debug(
+ "Sync stream generator close failed "
+ "(structured fallback, non-critical)"
+ )
+ return None
+ chunks.append(chunk)
+ except BaseException:
+ # On abort (or any mid-stream failure) release the HTTP
+ # response promptly. ``GeneratorExit`` from close() surfaces
+ # here for some providers — never mask the original raise.
+ try:
+ close = getattr(gen, "close", None)
+ if close is not None:
+ close()
+ except Exception:
+ logger.debug(
+ "Sync stream generator close failed on abort (non-critical)"
+ )
+ raise
+ else:
+ try:
+ close = getattr(gen, "close", None)
+ if close is not None:
+ close()
+ except Exception:
+ logger.debug(
+ "Sync stream generator close failed (non-critical)"
+ )
+ if not chunks:
+ # Only reachable with empty test-double generators; real
+ # LangChain models raise inside the generator on failure.
+ return None
+ combined = self._combine_stream_chunks(chunks)
+ if combined is None:
+ # Chunks were consumed but not reassemblable (structured or
+ # unknown shapes): the caller's direct-invoke fallback is a
+ # second upstream request — see the docstring above.
+ logger.warning(
+ "Sync stream produced "
+ f"{len(chunks)} non-reassemblable chunk(s); falling back "
+ "to direct invoke issues a second upstream request for "
+ "one logical call (token callbacks fire twice)"
+ )
+ return combined
+
+ async def _ainvoke_via_stream(self, *args: Any, **kwargs: Any):
+ """Async twin of :meth:`_invoke_via_stream` (via ``astream``).
+
+ Same fallback contract: zero chunks (test doubles only — real
+ models raise) and mid-stream structured shapes return ``None``;
+ a structured shape after pulled chunks means the direct-ainvoke
+ fallback is a second upstream request (warning logged).
+ """
+ if getattr(self, "_ldr_structured_output", False):
+ return None
+ astream_fn = getattr(self.base_llm, "astream", None)
+ if astream_fn is None:
+ return None
+ research_id = self._effective_research_id()
+ chunks = []
+ # ``astream`` is an async-generator function: calling it must not
+ # raise for a missing implementation (that is what the None check
+ # above covers); iteration errors propagate to the caller.
+ try:
+ agen = astream_fn(*args, **kwargs)
+ except Exception:
+ logger.debug(
+ "Async stream creation failed; falling back to direct ainvoke",
+ exc_info=True,
+ )
+ return None
+ try:
+ async for chunk in agen:
+ if research_id:
+ self._check_terminated(research_id)
+ if self._is_structured_chunk(chunk):
+ logger.warning(
+ "Async stream yielded structured chunk after "
+ f"{len(chunks)} message chunk(s); falling back "
+ "to direct ainvoke issues a second upstream "
+ "request for one logical call (token callbacks "
+ "fire twice)"
+ )
+ try:
+ aclose = getattr(agen, "aclose", None)
+ if aclose is not None:
+ await aclose()
+ except Exception:
+ logger.debug(
+ "Async stream generator close failed "
+ "(structured fallback, non-critical)"
+ )
+ return None
+ chunks.append(chunk)
+ except BaseException:
+ try:
+ aclose = getattr(agen, "aclose", None)
+ if aclose is not None:
+ await aclose()
+ else:
+ close = getattr(agen, "close", None)
+ if close is not None:
+ close()
+ except Exception:
+ logger.debug(
+ "Async stream generator close failed on abort (non-critical)"
+ )
+ raise
+ else:
+ try:
+ aclose = getattr(agen, "aclose", None)
+ if aclose is not None:
+ await aclose()
+ except Exception:
+ logger.debug(
+ "Async stream generator close failed (non-critical)"
+ )
+ if not chunks:
+ # Only reachable with empty test-double generators; real
+ # LangChain models raise inside the generator on failure.
+ return None
+ combined = self._combine_stream_chunks(chunks)
+ if combined is None:
+ logger.warning(
+ "Async stream produced "
+ f"{len(chunks)} non-reassemblable chunk(s); falling back "
+ "to direct ainvoke issues a second upstream request for "
+ "one logical call (token callbacks fire twice)"
+ )
+ return combined
+
def invoke(self, *args: Any, **kwargs: Any) -> Any:
+ # Fail fast if Stop arrived while queued (e.g. between
+ # check_termination checkpoints) — no new HTTP request.
+ self._check_terminated()
try:
+ # When a cancellation scope is known, stream under the hood
+ # so a Stop mid-generation aborts within one chunk instead
+ # of waiting for the full response (minutes on slow local
+ # models). Without a scope there is nothing to check
+ # between chunks, so keep the direct path. The streaming
+ # path is additionally gated by _stream_cancel_allowed():
+ # structured-output wrappers and usage-unsafe endpoints
+ # (openai_endpoint without stream_usage) stay on direct
+ # invoke so token/cost metrics and the dict/Pydantic contract
+ # survive — pre/post checks still abort promptly between calls.
+ if (
+ self._effective_research_id() is not None
+ and self._stream_cancel_allowed()
+ ):
+ streamed = self._invoke_via_stream(*args, **kwargs)
+ if streamed is not None:
+ self._check_terminated()
+ return self._normalize_response(streamed)
response = self.base_llm.invoke(*args, **kwargs)
except Exception as e:
self._log_llm_error(e)
raise
+ # Post-check: the flag may have been set while blocked. Raise
+ # so the worker aborts before the next pipeline step instead of
+ # continuing with a stale result.
+ self._check_terminated()
return self._normalize_response(response)
async def ainvoke(self, *args: Any, **kwargs: Any) -> Any:
# Async counterpart of invoke(); without this, ainvoke() would fall
# through __getattr__ to the base LLM and bypass think-tag stripping.
+ self._check_terminated()
try:
+ if (
+ self._effective_research_id() is not None
+ and self._stream_cancel_allowed()
+ ):
+ streamed = await self._ainvoke_via_stream(*args, **kwargs)
+ if streamed is not None:
+ self._check_terminated()
+ return self._normalize_response(streamed)
response = await self.base_llm.ainvoke(*args, **kwargs)
except Exception as e:
self._log_llm_error(e)
raise
+ self._check_terminated()
return self._normalize_response(response)
+ def stream(self, *args: Any, **kwargs: Any):
+ """Yield chunks with per-chunk termination checks.
+
+ Previously ``stream`` fell through ``__getattr__`` to the raw
+ model, bypassing both think-tag normalization and cancellation.
+ Now the generator checks the flag before yielding each chunk and
+ raises ``ResearchTerminatedException`` promptly on Stop. Chunks
+ are forwarded untouched (no per-chunk scrubbing — credentials
+ can straddle boundaries).
+ """
+ research_id = self._effective_research_id()
+ if research_id:
+ self._check_terminated(research_id)
+ gen = self.base_llm.stream(*args, **kwargs)
+ try:
+ for chunk in gen:
+ if research_id:
+ self._check_terminated(research_id)
+ yield chunk
+ finally:
+ try:
+ close = getattr(gen, "close", None)
+ if close is not None:
+ close()
+ except Exception:
+ logger.debug(
+ "Sync stream generator close failed in stream() (non-critical)"
+ )
+
+ async def astream(self, *args: Any, **kwargs: Any):
+ """Async generator twin of :meth:`stream` with the same checks."""
+ research_id = self._effective_research_id()
+ if research_id:
+ self._check_terminated(research_id)
+ agen = self.base_llm.astream(*args, **kwargs)
+ try:
+ async for chunk in agen:
+ if research_id:
+ self._check_terminated(research_id)
+ yield chunk
+ finally:
+ try:
+ aclose = getattr(agen, "aclose", None)
+ if aclose is not None:
+ await aclose()
+ except Exception:
+ logger.debug(
+ "Async stream generator close failed in astream() (non-critical)"
+ )
+
# Pass through any other attributes to the base LLM
def __getattr__(self, name):
return getattr(self.base_llm, name)
+ def batch(
+ self, inputs, config=None, *, return_exceptions=False, **kwargs: Any
+ ):
+ """Batch via :meth:`invoke` so per-item cancellation applies."""
+ results = []
+ # Resolve shared vs per-input configs like LangChain does.
+ if isinstance(config, list):
+ if len(config) != len(inputs):
+ raise ValueError(
+ f"configs must match the number of inputs ({len(config)} != {len(inputs)})"
+ )
+ configs = list(config)
+ else:
+ configs = [config] * len(inputs)
+ for single_input, single_config in zip(inputs, configs):
+ try:
+ if single_config is not None:
+ results.append(
+ self.invoke(single_input, single_config, **kwargs)
+ )
+ else:
+ results.append(self.invoke(single_input, **kwargs))
+ except Exception as e:
+ if return_exceptions:
+ results.append(e)
+ else:
+ raise
+ # ResearchTerminatedException (BaseException) propagates even with
+ # return_exceptions=True — a Stop must never be swallowed into a
+ # result list.
+ return results
+
+ async def abatch(
+ self, inputs, config=None, *, return_exceptions=False, **kwargs: Any
+ ):
+ """Async twin of :meth:`batch`."""
+ results = []
+ if isinstance(config, list):
+ if len(config) != len(inputs):
+ raise ValueError(
+ f"configs must match the number of inputs ({len(config)} != {len(inputs)})"
+ )
+ configs = list(config)
+ else:
+ configs = [config] * len(inputs)
+ for single_input, single_config in zip(inputs, configs):
+ try:
+ if single_config is not None:
+ results.append(
+ await self.ainvoke(
+ single_input, single_config, **kwargs
+ )
+ )
+ else:
+ results.append(await self.ainvoke(single_input, **kwargs))
+ except Exception as e:
+ if return_exceptions:
+ results.append(e)
+ else:
+ raise
+ return results
+
def close(self):
"""Release owned clients; registered shared instances remain caller-owned."""
if not self._owns_llm:
@@ -543,7 +1178,41 @@ class ProcessingLLMWrapper:
strip ``<think>`` tags.
"""
bound = self.base_llm.bind_tools(tools, **kwargs)
- return ProcessingLLMWrapper(bound, owns_llm=self._owns_llm)
+ return ProcessingLLMWrapper(
+ bound,
+ owns_llm=self._owns_llm,
+ research_id=self._effective_research_id(),
+ provider=getattr(self, "_provider", None),
+ settings_snapshot=getattr(self, "_settings_snapshot", None),
+ )
+
+ def with_structured_output(self, schema, **kwargs: Any) -> Any:
+ """Re-wrap like :meth:`bind_tools` so cancellation survives.
+
+ Structured-output runnables are used by several strategies for
+ JSON extraction; without re-wrapping, the bound runnable would
+ bypass the termination checks in ``invoke``. The re-wrapped
+ instance is marked ``structured_output`` so ``invoke``/``ainvoke``
+ use the direct path (pre/post checks) instead of stream+reassemble,
+ preserving the dict/Pydantic contract.
+ """
+ bound = self.base_llm.with_structured_output(schema, **kwargs)
+ try:
+ from ..llm.cancellation import bind_llm_to_research
+
+ bind_llm_to_research(bound, self._effective_research_id())
+ except Exception:
+ logger.debug(
+ "Structured-output scope propagation failed (non-critical)"
+ )
+ return ProcessingLLMWrapper(
+ bound,
+ owns_llm=self._owns_llm,
+ research_id=self._effective_research_id(),
+ provider=getattr(self, "_provider", None),
+ settings_snapshot=getattr(self, "_settings_snapshot", None),
+ structured_output=True,
+ )
def wrap_llm_without_think_tags(
@@ -613,4 +1282,22 @@ def wrap_llm_without_think_tags(
else:
llm.callbacks.extend(callbacks)
- return ProcessingLLMWrapper(llm, owns_llm=owns_llm)
+ wrapped = ProcessingLLMWrapper(
+ llm,
+ owns_llm=owns_llm,
+ research_id=research_id,
+ provider=provider,
+ settings_snapshot=settings_snapshot,
+ )
+ if research_id is not None:
+ # Propagate the scope to inner wrappers (rate-limiting layer)
+ # so direct uses of the inner instance also abort promptly.
+ try:
+ from ..llm.cancellation import bind_llm_to_research
+
+ bind_llm_to_research(wrapped, research_id)
+ except Exception:
+ logger.debug(
+ "Inner-wrapper scope propagation failed (non-critical)"
+ )
+ return wrapped
diff --git a/src/local_deep_research/llm/cancellation.py b/src/local_deep_research/llm/cancellation.py
new file mode 100644
index 0000000000..4fe34a9dda
--- /dev/null
+++ b/src/local_deep_research/llm/cancellation.py
@@ -0,0 +1,186 @@
+"""Cooperative cancellation for in-flight LLM calls.
+
+Research, chat and other long-running operations run on worker threads that
+block inside a synchronous LangChain ``llm.invoke()``. Setting the
+termination flag (``web.research_state.set_termination_flag``) only takes
+effect at the *next* ``check_termination`` checkpoint — i.e. after the
+current LLM HTTP request finishes, which can be minutes on a slow local
+model. The worker therefore keeps burning GPU/API budget after the user
+clicks Stop.
+
+This module is the single place that maps a ``research_id`` to "should this
+LLM call abort now?". Wrappers (``config.llm_config.ProcessingLLMWrapper``
+and the rate-limiting wrapper) resolve the effective research id from:
+
+1. an explicitly bound id (``bind_llm_to_research`` / ``research_id`` ctor
+ arg — survives thread-pool hops where the ContextVar is not copied), or
+2. the current thread's search context (``utilities.thread_context``), so
+ LLMs created without an explicit id inside a research worker are still
+ covered.
+
+When an id is known, wrappers prefer a streaming implementation of
+``invoke``: they consume ``base_llm.stream()`` chunk by chunk, check the
+flag between chunks, and close the generator on abort. Cancellation
+latency drops from "full response time" to "time to next token". Closing
+the generator releases the underlying HTTP response promptly instead of
+leaving it to GC.
+"""
+
+from typing import Any, Optional
+
+from loguru import logger
+
+
+def get_current_research_id() -> Optional[str]:
+ """Return the research id from the current thread's search context.
+
+ Returns ``None`` outside a research worker (request threads, CLI,
+ benchmarks without a context). Never raises — a missing/broken
+ context means "no cancellation scope", not an error.
+ """
+ try:
+ from ..utilities.thread_context import get_search_context
+
+ ctx = get_search_context()
+ if isinstance(ctx, dict):
+ rid = ctx.get("research_id")
+ if rid:
+ return str(rid)
+ except Exception:
+ logger.debug(
+ "get_current_research_id: failed to read search context",
+ exc_info=True,
+ )
+ return None
+
+
+def resolve_research_id(explicit: Optional[str] = None) -> Optional[str]:
+ """Return the explicit id, falling back to the thread's search context."""
+ if explicit:
+ return str(explicit)
+ return get_current_research_id()
+
+
+def is_termination_requested(research_id: Optional[str]) -> bool:
+ """Return True iff Stop was requested for *research_id*.
+
+ ``None`` (no cancellation scope) is never considered terminated.
+ Import is function-local so this module never creates an import cycle
+ with ``web.research_state``.
+ """
+ if not research_id:
+ return False
+ try:
+ from ..web.research_state import is_termination_requested as _check
+
+ return bool(_check(research_id))
+ except Exception:
+ logger.debug(
+ "is_termination_requested: flag lookup failed",
+ exc_info=True,
+ )
+ return False
+
+
+def raise_if_terminated(research_id: Optional[str]) -> None:
+ """Raise ``ResearchTerminatedException`` if Stop was requested.
+
+ No-op when *research_id* is falsy or no flag is set. The exception
+ inherits from ``BaseException`` so ``except Exception`` blocks in
+ strategy code let it propagate (same pattern as CancelledError).
+ """
+ if is_termination_requested(research_id):
+ from ..exceptions import ResearchTerminatedException
+
+ raise ResearchTerminatedException(
+ f"Research {research_id} was terminated by user during LLM call"
+ )
+
+
+def _try_bind(target: Any, rid: str) -> None:
+ """Best-effort ``_ldr_research_id`` setattr on one wrapper level.
+
+ Plain objects always accept it; exotic proxies or frozen test
+ doubles may refuse — that only loses the fast-path scope for that
+ level (the thread-context fallback still applies), so debug-log
+ and move on.
+ """
+ try:
+ setattr(target, "_ldr_research_id", rid)
+ except Exception:
+ logger.debug("bind_llm_to_research: setattr refused", exc_info=True)
+
+
+def bind_llm_to_research(llm: Any, research_id: Optional[str]) -> Any:
+ """Attach *research_id* to an LLM wrapper chain (in place, chain-safe).
+
+ Sets ``_ldr_research_id`` on *llm* and, when present, on its
+ ``base_llm`` (covers ``ProcessingLLMWrapper -> RateLimitedWrapper ->
+ raw ChatModel`` without unwrapping). Returns *llm* for chaining.
+ ``None`` clears nothing — a falsy id leaves existing bindings intact
+ so rebinding with an empty value cannot silently drop cancellation.
+
+ Invariant: a bound wrapper must not outlive its run. The binding is
+ resolved per call (explicit id > binding > thread context), so
+ re-binding for the next run takes effect without reconstructing the
+ LLM — but a wrapper bound to run A and reused for run B without
+ re-binding would fail-fast/post-check against A's flag. Callers must
+ re-bind (or construct with the new id) when crossing runs.
+ """
+ if not research_id:
+ return llm
+ rid = str(research_id)
+ _try_bind(llm, rid)
+ # Propagate one level down so inner wrappers that are invoked
+ # directly (e.g. via __getattr__ passthrough or shared instances)
+ # see the same scope. Depth is bounded: each level sets a plain
+ # attribute, never recursing.
+ try:
+ inner = getattr(llm, "base_llm", None)
+ except Exception:
+ logger.debug(
+ "bind_llm_to_research: base_llm lookup failed", exc_info=True
+ )
+ return llm
+ if inner is not None and getattr(inner, "_ldr_research_id", None) != rid:
+ _try_bind(inner, rid)
+ # One more level for the double-wrapped shape
+ # (Processing -> RateLimited -> ChatModel).
+ try:
+ inner_inner = getattr(inner, "base_llm", None)
+ except Exception:
+ logger.debug(
+ "bind_llm_to_research: nested base_llm lookup failed",
+ exc_info=True,
+ )
+ return llm
+ if (
+ inner_inner is not None
+ and getattr(inner_inner, "_ldr_research_id", None) != rid
+ ):
+ _try_bind(inner_inner, rid)
+ return llm
+
+
+def effective_research_id(
+ llm: Any, explicit: Optional[str] = None
+) -> Optional[str]:
+ """Resolve the cancellation scope for an LLM call.
+
+ Precedence: explicit ctor arg > ``_ldr_research_id`` binding >
+ current thread's search context. Used by wrappers on every call so
+ rebinding (or context propagation into pool threads) takes effect
+ without reconstructing the LLM.
+ """
+ if explicit:
+ return str(explicit)
+ try:
+ bound = getattr(llm, "_ldr_research_id", None)
+ except Exception:
+ logger.debug(
+ "effective_research_id: binding lookup failed", exc_info=True
+ )
+ return get_current_research_id()
+ if bound:
+ return str(bound)
+ return get_current_research_id()
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
index f9b92847da..7e0d45b197 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
@@ -69,6 +69,10 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
self.base_llm = llm
self.provider = provider_name
self.rate_limiter = None
+ # Cancellation scope (see llm/cancellation.py). Bound via
+ # ``bind_llm_to_research`` by the outer ProcessingLLMWrapper;
+ # falls back to the thread's search context per call.
+ self._ldr_research_id = getattr(llm, "_ldr_research_id", None)
# Only setup rate limiting if enabled
if self._should_rate_limit():
@@ -77,6 +81,27 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
f"Rate limiting enabled for LLM provider: {self._get_rate_limit_key()}"
)
+ def _effective_research_id(self):
+ """Resolve cancellation scope: binding > thread context."""
+ try:
+ from ....llm.cancellation import effective_research_id
+
+ return effective_research_id(self, self._ldr_research_id)
+ except Exception:
+ return getattr(self, "_ldr_research_id", None)
+
+ def _check_terminated(self, research_id=None):
+ """Raise ``ResearchTerminatedException`` if Stop was requested."""
+ from ....llm.cancellation import raise_if_terminated
+
+ rid = (
+ research_id
+ if research_id is not None
+ else self._effective_research_id()
+ )
+ if rid:
+ raise_if_terminated(rid)
+
def _should_rate_limit(self) -> bool:
"""Check if rate limiting should be applied to this LLM."""
# Rate limiting for LLMs is currently disabled by default
@@ -156,9 +181,12 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
def invoke(self, *args, **kwargs):
"""Invoke the LLM with rate limiting if enabled."""
- return self._call_rate_limited(
+ self._check_terminated()
+ result = self._call_rate_limited(
lambda: self.base_llm.invoke(*args, **kwargs)
)
+ self._check_terminated()
+ return result
async def ainvoke(self, *args, **kwargs):
"""Async invoke with the same rate limiting and scrub as invoke().
@@ -184,9 +212,12 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
``self.rate_limiter`` is always ``None``.
See #6232/#6246/#6249/#6268/#6347 for the history.
"""
- return await self._acall_rate_limited(
+ self._check_terminated()
+ result = await self._acall_rate_limited(
lambda: self.base_llm.ainvoke(*args, **kwargs)
)
+ self._check_terminated()
+ return result
def _scrub_or_raise(self, error):
"""Re-raise with scrubbing: provider 429 bodies can echo the
@@ -265,9 +296,13 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
except Exception as e:
self._scrub_or_raise(e)
+ research_id = self._effective_research_id()
+ if research_id:
+ self._check_terminated(research_id)
chunks = iter(self._call_rate_limited(_source))
try:
while True:
+ # Only the advance is guarded, and `yield` stays outside the
# Only the advance is guarded, and `yield` stays outside the
# inner `try`: a handler that encloses the yield also catches
# whatever the CONSUMER throws back in, which would scrub an
@@ -275,12 +310,17 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
# The outer handler only closes the upstream and
# re-raises the same object it caught, so a consumer
# `throw()` still propagates untouched to the caller.
+ # The termination check sits after next() and before yield:
+ # a Stop aborts without yielding the just-pulled chunk and
+ # without draining the rest of the stream.
try:
chunk = next(chunks)
except StopIteration:
break
except Exception as e:
self._scrub_or_raise(e)
+ if research_id:
+ self._check_terminated(research_id)
yield chunk
except BaseException as exc:
# Close the upstream generator on ANY exit — early consumer
@@ -383,6 +423,9 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
Chunks are forwarded untouched: a credential echoed in a 429 body
can straddle chunk boundaries, so per-chunk scrubbing is unsound.
"""
+ research_id = self._effective_research_id()
+ if research_id:
+ self._check_terminated(research_id)
try:
chunks = self.base_llm.astream(*args, **kwargs).__aiter__()
except Exception as e:
@@ -393,12 +436,16 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
# `yield` deliberately outside the inner `try`; see
# stream(). The outer handler re-raises the same object,
# so a consumer `throw()` still propagates untouched.
+ # Termination is checked after each advance so a Stop
+ # aborts without yielding the just-pulled chunk.
try:
chunk = await chunks.__anext__()
except StopAsyncIteration:
break
except Exception as e:
self._scrub_or_raise(e)
+ if research_id:
+ self._check_terminated(research_id)
yield chunk
except BaseException as exc:
# Async twin of stream()'s cleanup: close the upstream
@@ -468,7 +515,12 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
self, inputs, config=None, *, return_exceptions=False, **kwargs
):
"""Batch through invoke(), forwarding config (shared or
- per-input) so caller callbacks/tags/metadata survive."""
+ per-input) so caller callbacks/tags/metadata survive.
+
+ Only ``Exception`` is captured for ``return_exceptions=True`` —
+ ``ResearchTerminatedException`` (a ``BaseException``) always
+ propagates so a Stop is never swallowed into a result list.
+ """
configs = self._configs_for_inputs(config, inputs)
results = []
for msg, conf in zip(inputs, configs):
@@ -484,7 +536,7 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
async def abatch(
self, inputs, config=None, *, return_exceptions=False, **kwargs
):
- """Async counterpart of batch()."""
+ """Async counterpart of batch() (same BaseException guarantee)."""
configs = self._configs_for_inputs(config, inputs)
results = []
for msg, conf in zip(inputs, configs):
@@ -502,13 +554,39 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
limiting and scrubbing (same shape as
ProcessingLLMWrapper.bind_tools, #4804)."""
bound = self.base_llm.bind_tools(tools, **kwargs)
- return create_rate_limited_llm_wrapper(bound, self.provider)
+ wrapped = create_rate_limited_llm_wrapper(bound, self.provider)
+ try:
+ wrapped._ldr_research_id = self._effective_research_id()
+ inner = getattr(wrapped, "base_llm", None)
+ if inner is not None:
+ try:
+ setattr(
+ inner,
+ "_ldr_research_id",
+ wrapped._ldr_research_id,
+ )
+ except Exception:
+ logger.debug(
+ "bind_tools inner scope propagation failed (non-critical)"
+ )
+ except Exception:
+ logger.debug(
+ "bind_tools scope propagation failed (non-critical)"
+ )
+ return wrapped
def with_structured_output(self, schema, **kwargs):
"""Wrap the structured-output runnable the same way as
bind_tools."""
bound = self.base_llm.with_structured_output(schema, **kwargs)
- return create_rate_limited_llm_wrapper(bound, self.provider)
+ wrapped = create_rate_limited_llm_wrapper(bound, self.provider)
+ try:
+ wrapped._ldr_research_id = self._effective_research_id()
+ except Exception:
+ logger.debug(
+ "with_structured_output scope propagation failed (non-critical)"
+ )
+ return wrapped
# Pass through any other attributes to the base LLM
def __getattr__(self, name):
diff --git a/tests/llm/test_llm_cancellation.py b/tests/llm/test_llm_cancellation.py
new file mode 100644
index 0000000000..0f65dc9a19
--- /dev/null
+++ b/tests/llm/test_llm_cancellation.py
@@ -0,0 +1,804 @@
+"""Cooperative cancellation of in-flight LLM calls on Stop.
+
+Covers ``llm/cancellation.py`` and the termination-aware paths in
+``ProcessingLLMWrapper`` / the rate-limiting wrapper: a set termination
+flag must abort a running ``invoke`` mid-stream (not just between calls),
+block new calls outright, and propagate through ``bind_tools``. All
+fakes are synchronous and sleep-free (the mid-stream fake sets the flag
+from inside its own generator, simulating a Stop arriving between
+tokens).
+"""
+
+import asyncio
+import uuid
+
+from langchain_core.messages import AIMessage, AIMessageChunk
+
+
+def _rid():
+ return f"test-llm-cancel-{uuid.uuid4().hex[:12]}"
+
+
+class _FakeStreamingLLM:
+ """Minimal ChatModel double with controllable stream/invoke."""
+
+ def __init__(self, chunks=None):
+ self.chunks = list(chunks or [])
+ self.invoke_calls = 0
+ self.stream_calls = 0
+
+ def invoke(self, prompt, *args, **kwargs):
+ self.invoke_calls += 1
+ return AIMessage(content="direct-invoke-response")
+
+ def stream(self, prompt, *args, **kwargs):
+ self.stream_calls += 1
+
+ def _gen():
+ for chunk in self.chunks:
+ yield chunk
+
+ return _gen()
+
+ def bind_tools(self, tools, **kwargs):
+ return self
+
+ def with_structured_output(self, schema, **kwargs):
+ return self
+
+
+class TestPreTerminationBlocksNewCalls:
+ def test_invoke_raises_without_touching_base(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(chunks=[AIMessageChunk(content="hi")])
+ llm = ProcessingLLMWrapper(base, research_id=research_id)
+ set_termination_flag(research_id)
+ try:
+ try:
+ llm.invoke("hello")
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ assert base.stream_calls == 0
+ assert base.invoke_calls == 0
+ finally:
+ cleanup_research(research_id)
+
+
+class TestMidStreamAbort:
+ def test_invoke_aborts_when_flag_set_between_chunks(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+
+ research_id = _rid()
+
+ def _gen():
+ yield AIMessageChunk(content="tok0 ")
+ # Simulate the user clicking Stop mid-generation.
+ set_termination_flag(research_id)
+ yield AIMessageChunk(content="tok1 ")
+
+ class _MidStopLLM(_FakeStreamingLLM):
+ def stream(self, prompt, *args, **kwargs):
+ self.stream_calls += 1
+ return _gen()
+
+ llm = ProcessingLLMWrapper(_MidStopLLM(), research_id=research_id)
+ try:
+ try:
+ llm.invoke("hello")
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ finally:
+ cleanup_research(research_id)
+
+ def test_stream_generator_aborts_between_chunks(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+
+ research_id = _rid()
+
+ def _gen():
+ yield AIMessageChunk(content="a")
+ set_termination_flag(research_id)
+ yield AIMessageChunk(content="b")
+
+ class _MidStopLLM(_FakeStreamingLLM):
+ def stream(self, prompt, *args, **kwargs):
+ self.stream_calls += 1
+ return _gen()
+
+ llm = ProcessingLLMWrapper(_MidStopLLM(), research_id=research_id)
+ try:
+ seen = []
+ try:
+ for chunk in llm.stream("hello"):
+ seen.append(chunk)
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ assert len(seen) == 1
+ finally:
+ cleanup_research(research_id)
+
+
+class TestNoFlagCompletesViaStream:
+ def test_invoke_streams_and_combines_when_not_terminated(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(
+ chunks=[
+ AIMessageChunk(content="tok0 "),
+ AIMessageChunk(content="tok1"),
+ ]
+ )
+ llm = ProcessingLLMWrapper(base, research_id=research_id)
+ try:
+ response = llm.invoke("hello")
+ assert getattr(response, "content", "") == "tok0 tok1"
+ assert base.stream_calls == 1
+ assert base.invoke_calls == 0
+ finally:
+ cleanup_research(research_id)
+
+ def test_tool_calls_survive_stream_reassembly(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(
+ chunks=[
+ AIMessageChunk(
+ content="",
+ tool_calls=[
+ {
+ "name": "search",
+ "args": {"q": "x"},
+ "id": "call-1",
+ "type": "tool_call",
+ }
+ ],
+ )
+ ]
+ )
+ llm = ProcessingLLMWrapper(base, research_id=research_id)
+ try:
+ response = llm.invoke("hello")
+ assert getattr(response, "tool_calls", None)
+ finally:
+ cleanup_research(research_id)
+
+
+class TestThreadContextFallback:
+ def test_invoke_without_explicit_id_uses_search_context(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ set_search_context,
+ )
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(chunks=[AIMessageChunk(content="hi")])
+ llm = ProcessingLLMWrapper(base)
+ set_search_context({"research_id": research_id, "username": "u"})
+ set_termination_flag(research_id)
+ try:
+ try:
+ llm.invoke("hello")
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ finally:
+ clear_search_context()
+ cleanup_research(research_id)
+
+
+class TestScopePropagation:
+ def test_bind_tools_keeps_research_id(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ llm = ProcessingLLMWrapper(_FakeStreamingLLM(), research_id=research_id)
+ try:
+ bound = llm.bind_tools([])
+ assert getattr(bound, "_ldr_research_id", None) == research_id
+ finally:
+ cleanup_research(research_id)
+
+ def test_bind_llm_to_research_reaches_inner_wrapper(self):
+ from local_deep_research.llm.cancellation import bind_llm_to_research
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ outer = _FakeStreamingLLM()
+ outer.base_llm = _FakeStreamingLLM()
+ try:
+ bind_llm_to_research(outer, research_id)
+ assert outer._ldr_research_id == research_id
+ assert outer.base_llm._ldr_research_id == research_id
+ finally:
+ cleanup_research(research_id)
+
+
+class TestRateLimitedWrapper:
+ def test_rate_limited_invoke_precheck_raises(self):
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (
+ create_rate_limited_llm_wrapper,
+ )
+
+ research_id = _rid()
+ wrapped = create_rate_limited_llm_wrapper(_FakeStreamingLLM(), "openai")
+ wrapped._ldr_research_id = research_id
+ set_termination_flag(research_id)
+ try:
+ try:
+ wrapped.invoke("hello")
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ finally:
+ cleanup_research(research_id)
+
+
+class TestAsyncAbort:
+ def test_ainvoke_aborts_mid_astream(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+
+ research_id = _rid()
+
+ class _AsyncMidStopLLM(_FakeStreamingLLM):
+ def astream(self, prompt, *args, **kwargs):
+ async def _gen():
+ yield AIMessageChunk(content="a")
+ set_termination_flag(research_id)
+ yield AIMessageChunk(content="b")
+
+ return _gen()
+
+ async def _run():
+ llm = ProcessingLLMWrapper(
+ _AsyncMidStopLLM(), research_id=research_id
+ )
+ await llm.ainvoke("hello")
+
+ try:
+ try:
+ asyncio.run(_run())
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ finally:
+ cleanup_research(research_id)
+
+
+class TestAbortDoesNotDrainStream:
+ """Pin that an abort stops consuming the stream (no drain-then-raise)."""
+
+ def test_invoke_aborts_without_draining_stream(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+
+ research_id = _rid()
+ pulled = []
+
+ def _gen():
+ for i in range(6):
+ pulled.append(i)
+ yield AIMessageChunk(content=f"tok{i} ")
+ if i == 0:
+ # Simulate Stop arriving between tokens: the flag is set
+ # while the wrapper holds chunk 0, so the very next pull
+ # (chunk 1) must abort without touching chunks 2-5.
+ set_termination_flag(research_id)
+
+ class _CountingLLM(_FakeStreamingLLM):
+ def stream(self, prompt, *args, **kwargs):
+ self.stream_calls += 1
+ return _gen()
+
+ llm = ProcessingLLMWrapper(_CountingLLM(), research_id=research_id)
+ try:
+ try:
+ llm.invoke("hello")
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ # Genuinely stops at 2/6: chunks 0 and 1 pulled, the rest never
+ # consumed (a drain-then-raise implementation would show 6).
+ assert pulled == [0, 1], f"drained stream: {pulled}"
+ finally:
+ cleanup_research(research_id)
+
+ def test_rate_limited_stream_aborts_without_draining(self):
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (
+ create_rate_limited_llm_wrapper,
+ )
+
+ research_id = _rid()
+ pulled = []
+
+ def _gen():
+ for i in range(6):
+ pulled.append(i)
+ yield AIMessageChunk(content=f"tok{i} ")
+ if i == 0:
+ set_termination_flag(research_id)
+
+ class _CountingLLM(_FakeStreamingLLM):
+ def stream(self, prompt, *args, **kwargs):
+ self.stream_calls += 1
+ return _gen()
+
+ wrapped = create_rate_limited_llm_wrapper(_CountingLLM(), "openai")
+ wrapped._ldr_research_id = research_id
+ try:
+ seen = []
+ try:
+ for chunk in wrapped.stream("hello"):
+ seen.append(chunk)
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ assert pulled == [0, 1], f"drained stream: {pulled}"
+ assert len(seen) == 1
+ finally:
+ cleanup_research(research_id)
+
+
+class TestBatchCancellation:
+ def test_batch_returns_results_when_not_terminated(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(
+ chunks=[AIMessageChunk(content="hi")],
+ )
+ llm = ProcessingLLMWrapper(base, research_id=research_id)
+ try:
+ out = llm.batch(["a", "b"])
+ assert len(out) == 2
+ assert all(getattr(m, "content", "") == "hi" for m in out)
+ finally:
+ cleanup_research(research_id)
+
+ def test_batch_propagates_termination_even_with_return_exceptions(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+
+ research_id = _rid()
+ llm = ProcessingLLMWrapper(
+ _FakeStreamingLLM(chunks=[AIMessageChunk(content="hi")]),
+ research_id=research_id,
+ )
+ set_termination_flag(research_id)
+ try:
+ try:
+ llm.batch(["a", "b"], return_exceptions=True)
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError(
+ "ResearchTerminatedException must not be embedded "
+ "in result list under return_exceptions=True"
+ )
+ finally:
+ cleanup_research(research_id)
+
+ def test_abatch_propagates_termination_even_with_return_exceptions(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+
+ research_id = _rid()
+
+ async def _run():
+ llm = ProcessingLLMWrapper(
+ _FakeStreamingLLM(chunks=[AIMessageChunk(content="hi")]),
+ research_id=research_id,
+ )
+ await llm.abatch(["a", "b"], return_exceptions=True)
+
+ set_termination_flag(research_id)
+ try:
+ try:
+ asyncio.run(_run())
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError(
+ "ResearchTerminatedException must not be embedded "
+ "in abatch result list under return_exceptions=True"
+ )
+ finally:
+ cleanup_research(research_id)
+
+ def test_rate_limited_batch_propagates_termination(self):
+ from local_deep_research.exceptions import ResearchTerminatedException
+ from local_deep_research.web.research_state import (
+ cleanup_research,
+ set_termination_flag,
+ )
+ from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (
+ create_rate_limited_llm_wrapper,
+ )
+
+ research_id = _rid()
+ wrapped = create_rate_limited_llm_wrapper(_FakeStreamingLLM(), "openai")
+ wrapped._ldr_research_id = research_id
+ set_termination_flag(research_id)
+ try:
+ try:
+ wrapped.batch(["a"], return_exceptions=True)
+ except ResearchTerminatedException:
+ pass
+ else:
+ raise AssertionError("expected ResearchTerminatedException")
+ finally:
+ cleanup_research(research_id)
+
+
+class TestStructuredOutputPreserved:
+ """with_structured_output() must keep the dict/Pydantic contract."""
+
+ def test_invoke_preserves_dict_output(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+
+ class _DictRunnable:
+ def invoke(self, prompt, *args, **kwargs):
+ return {"answer": "x", "score": 1}
+
+ def stream(self, prompt, *args, **kwargs):
+ def _gen():
+ yield {"answer": "x"}
+
+ return _gen()
+
+ def with_structured_output(self, schema, **kwargs):
+ return self
+
+ base = _FakeStreamingLLM()
+ base.with_structured_output = lambda schema, **kw: _DictRunnable()
+ llm = ProcessingLLMWrapper(base, research_id=research_id)
+ try:
+ structured = llm.with_structured_output(dict)
+ out = structured.invoke("hello")
+ assert out == {"answer": "x", "score": 1}, f"corrupted: {out!r}"
+ assert not hasattr(out, "content")
+ finally:
+ cleanup_research(research_id)
+
+ def test_ainvoke_preserves_dict_output(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+
+ class _AsyncDictRunnable:
+ async def ainvoke(self, prompt, *args, **kwargs):
+ return {"answer": "y"}
+
+ def invoke(self, prompt, *args, **kwargs):
+ return {"answer": "y"}
+
+ async def astream(self, prompt, *args, **kwargs):
+ async def _gen():
+ yield {"answer": "y"}
+
+ return _gen()
+
+ def stream(self, prompt, *args, **kwargs):
+ def _gen():
+ yield {"answer": "y"}
+
+ return _gen()
+
+ class _Base(_FakeStreamingLLM):
+ def with_structured_output(self, schema, **kwargs):
+ return _AsyncDictRunnable()
+
+ async def ainvoke(self, prompt, *args, **kwargs):
+ return {"answer": "y"}
+
+ async def _run():
+ llm = ProcessingLLMWrapper(_Base(), research_id=research_id)
+ structured = llm.with_structured_output(dict)
+ return await structured.ainvoke("hello")
+
+ try:
+ out = asyncio.run(_run())
+ assert out == {"answer": "y"}, f"corrupted: {out!r}"
+ finally:
+ cleanup_research(research_id)
+
+ def test_invoke_preserves_pydantic_output(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+ from pydantic import BaseModel
+
+ class _Answer(BaseModel):
+ answer: str
+
+ research_id = _rid()
+
+ class _ModelRunnable:
+ def invoke(self, prompt, *args, **kwargs):
+ return _Answer(answer="z")
+
+ def stream(self, prompt, *args, **kwargs):
+ def _gen():
+ yield _Answer(answer="z")
+
+ return _gen()
+
+ class _Base(_FakeStreamingLLM):
+ def with_structured_output(self, schema, **kwargs):
+ return _ModelRunnable()
+
+ llm = ProcessingLLMWrapper(_Base(), research_id=research_id)
+ try:
+ structured = llm.with_structured_output(_Answer)
+ out = structured.invoke("hello")
+ assert isinstance(out, _Answer), f"corrupted: {out!r}"
+ assert out.answer == "z"
+ finally:
+ cleanup_research(research_id)
+
+
+class TestStreamUsageGate:
+ """Scoped invoke must not silently become streaming when that would
+ zero out token/cost metrics (openai_endpoint without stream_usage)."""
+
+ def test_openai_endpoint_without_usage_stays_on_direct_invoke(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(chunks=[AIMessageChunk(content="hi")])
+ llm = ProcessingLLMWrapper(
+ base, research_id=research_id, provider="openai_endpoint"
+ )
+ try:
+ out = llm.invoke("hello")
+ assert getattr(out, "content", "") == "direct-invoke-response"
+ assert base.invoke_calls == 1
+ assert base.stream_calls == 0
+ finally:
+ cleanup_research(research_id)
+
+ def test_openai_endpoint_with_model_opt_in_streams(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(chunks=[AIMessageChunk(content="hi")])
+ base.stream_usage = True
+ llm = ProcessingLLMWrapper(
+ base, research_id=research_id, provider="openai_endpoint"
+ )
+ try:
+ out = llm.invoke("hello")
+ assert getattr(out, "content", "") == "hi"
+ assert base.stream_calls == 1
+ assert base.invoke_calls == 0
+ finally:
+ cleanup_research(research_id)
+
+ def test_other_providers_keep_streaming(self):
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(chunks=[AIMessageChunk(content="hi")])
+ llm = ProcessingLLMWrapper(
+ base, research_id=research_id, provider="ollama"
+ )
+ try:
+ out = llm.invoke("hello")
+ assert getattr(out, "content", "") == "hi"
+ assert base.stream_calls == 1
+ finally:
+ cleanup_research(research_id)
+
+
+class TestMidStreamStructuredFallbackDoubleRequest:
+ """Pin the defense-in-depth fallback: a structured chunk mid-stream
+ falls back to direct invoke, which is a *second* upstream request for
+ one logical call (token callbacks fire twice). No in-app path produces
+ such mixed shapes (structured wrappers are excluded up front), so the
+ implementation logs a warning instead of silently double-firing.
+
+ NOTE: the package disables its own loguru namespace by default
+ (``local_deep_research/__init__.py`` — the app re-enables it at
+ startup), so these tests explicitly ``logger.enable`` around the
+ invoke and restore the disabled default afterwards.
+ """
+
+ def test_sync_structured_after_message_chunk_warns_and_retries_once(
+ self,
+ ):
+ from loguru import logger
+
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+
+ class _MixedLLM(_FakeStreamingLLM):
+ def invoke(self, prompt, *args, **kwargs):
+ self.invoke_calls += 1
+ return {"answer": "fallback"}
+
+ def stream(self, prompt, *args, **kwargs):
+ self.stream_calls += 1
+
+ def _gen():
+ yield AIMessageChunk(content="partial ")
+ yield {"answer": "fallback"}
+
+ return _gen()
+
+ base = _MixedLLM()
+ llm = ProcessingLLMWrapper(base, research_id=research_id)
+ records = []
+ sink = lambda msg: records.append(msg) # noqa: E731
+ handler = logger.add(sink, format="{message}", level="WARNING")
+ logger.enable("local_deep_research")
+ try:
+ out = llm.invoke("hello")
+ assert out == {"answer": "fallback"}
+ # Exactly one stream attempt + one direct retry: no more, no less.
+ assert base.stream_calls == 1
+ assert base.invoke_calls == 1
+ assert any("second upstream request" in str(r) for r in records), (
+ f"missing double-request warning: {records!r}"
+ )
+ finally:
+ logger.disable("local_deep_research")
+ logger.remove(handler)
+ cleanup_research(research_id)
+
+ def test_async_structured_after_message_chunk_warns_and_retries_once(
+ self,
+ ):
+ import asyncio
+
+ from loguru import logger
+
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+
+ class _MixedAsyncLLM(_FakeStreamingLLM):
+ def __init__(self):
+ super().__init__()
+ self.ainvoke_calls = 0
+ self.astream_calls = 0
+
+ async def ainvoke(self, prompt, *args, **kwargs):
+ self.ainvoke_calls += 1
+ return {"answer": "fallback"}
+
+ def astream(self, prompt, *args, **kwargs):
+ self.astream_calls += 1
+
+ async def _gen():
+ yield AIMessageChunk(content="partial ")
+ yield {"answer": "fallback"}
+
+ return _gen()
+
+ async def _run():
+ base = _MixedAsyncLLM()
+ llm = ProcessingLLMWrapper(base, research_id=research_id)
+ records = []
+ sink = lambda msg: records.append(msg) # noqa: E731
+ handler = logger.add(sink, format="{message}", level="WARNING")
+ logger.enable("local_deep_research")
+ try:
+ out = await llm.ainvoke("hello")
+ assert out == {"answer": "fallback"}
+ assert base.astream_calls == 1
+ assert base.ainvoke_calls == 1
+ assert any(
+ "second upstream request" in str(r) for r in records
+ ), f"missing double-request warning: {records!r}"
+ finally:
+ logger.disable("local_deep_research")
+ logger.remove(handler)
+ return True
+
+ try:
+ assert asyncio.run(_run())
+ finally:
+ cleanup_research(research_id)
+
+ def test_empty_stream_falls_back_without_warning(self):
+ """Zero chunks (test doubles only — real LangChain models raise
+ inside the generator) fall back silently to one direct invoke."""
+ from loguru import logger
+
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.web.research_state import cleanup_research
+
+ research_id = _rid()
+ base = _FakeStreamingLLM(chunks=[])
+ llm = ProcessingLLMWrapper(base, research_id=research_id)
+ records = []
+ sink = lambda msg: records.append(msg) # noqa: E731
+ handler = logger.add(sink, format="{message}", level="WARNING")
+ logger.enable("local_deep_research")
+ try:
+ out = llm.invoke("hello")
+ assert getattr(out, "content", "") == "direct-invoke-response"
+ assert base.stream_calls == 1
+ assert base.invoke_calls == 1
+ assert not any(
+ "second upstream request" in str(r) for r in records
+ ), f"unexpected double-request warning: {records!r}"
+ finally:
+ logger.disable("local_deep_research")
+ logger.remove(handler)
+ cleanup_research(research_id)