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.

docs(async): align async-twin comments with ADR-0013 (#6469)

LearningCircuit26631132d32d
diff --git a/changelog.d/6277.misc.md b/changelog.d/6277.misc.md
index 3b77341ccd..47b8c2d83b 100644
--- a/changelog.d/6277.misc.md
+++ b/changelog.d/6277.misc.md
@@ -1 +1 @@
-The research pipeline's question generators, result filters, candidate explorers, follow-up context manager, evidence evaluator, findings synthesizer, summarization and constraint analysis, agent fetch tool and the news/LangGraph strategies now make their model calls through one shared `invoke_llm_sync` helper. The helper keeps the synchronous client and raw response; token-usage attribution skips this dispatch frame, so the pipeline caller is retained for injected raw models while wrapped models keep their existing `config/llm_config.py` attribution, with the filter's visible effect being on the recorded call stack. An `ainvoke_llm` helper and `RateLimitedLLMWrapper.ainvoke` are added for future async callers, with regression coverage for credential scrubbing and exception-chain suppression. Pipeline callers remain synchronous. Fifth tranche of #5854.
+The research pipeline's question generators, result filters, candidate explorers, follow-up context manager, evidence evaluator, findings synthesizer, summarization and constraint analysis, agent fetch tool and the news/LangGraph strategies now make their model calls through one shared `invoke_llm_sync` helper. The helper keeps the synchronous client and raw response; token-usage attribution skips this dispatch frame, so the pipeline caller is retained for injected raw models while wrapped models keep their existing `config/llm_config.py` attribution, with the filter's visible effect being on the recorded call stack. An `ainvoke_llm` helper is added for future async callers, and the existing `RateLimitedLLMWrapper.ainvoke` gains regression coverage for credential scrubbing and exception-chain suppression. Pipeline callers remain synchronous. Fifth tranche of #5854.
diff --git a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
index 55a4546493..d6ce824d27 100644
--- a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
@@ -163,23 +163,41 @@ class TopicOrganizationStrategy(BaseSearchStrategy):
be normalized by ``ProcessingLLMWrapper``; retaining this helper
also preserves behavior for injected or unwrapped models.
- This method runs synchronously in its caller's thread. It must not
- create a temporary event loop to drive the async twin: cached async
- HTTP clients can retain connections bound to an earlier loop
- (#6293). An async runner must manage that client and loop lifetime
- before switching production callers to :meth:`_ainvoke_model`.
+ This method runs synchronously in its caller's thread. That is the
+ research run's dedicated daemon thread for web UI and queue-started
+ runs (ADR-0013, docs/decisions/0013-research-runs-keep-daemon-thread.md);
+ REST v1 (on a pooled executor thread) and scheduled runs (on an
+ APScheduler worker) run it inline instead (#6862); the web
+ benchmark runner calls it on its own daemon thread outside
+ ``start_research_process``, and library callers on their own
+ thread. It must not create a temporary event loop to drive the
+ async twin: cached async HTTP clients can retain connections
+ bound to an earlier loop (#6293). Nothing fans out from here yet;
+ if fan-out onto :meth:`_ainvoke_model` is wired (#6467), it goes
+ through the process's one shared event loop.
"""
return get_llm_response_text(self.model.invoke(prompt))
async def _ainvoke_model(self, prompt: str) -> str:
"""Async counterpart of :meth:`_invoke_model`.
- Additive: no production caller awaits it yet. It exists for the
- research-runner tranche of #5854, which will drive the strategy from
- a single long-lived event loop; only then does the async LangChain
- API become safe here (#6293), and the token-usage callback needs to
- become async-aware first or the usage row loses its call-site
- attribution and can be dropped entirely (#6294).
+ Additive: no production caller awaits it yet. It is intended to be
+ submitted to the process's one shared event loop via
+ ``asyncio.run_coroutine_threadsafe`` (ADR-0013,
+ docs/decisions/0013-research-runs-keep-daemon-thread.md); which
+ thread hosts that loop is not decided yet (#6467).
+ :meth:`_invoke_model` remains the canonical production path on the
+ research thread, and this must never go through ``asyncio.run`` or
+ a per-thread loop (#6293).
+
+ Not loop-safe yet, for three reasons: ``TokenCountingCallback``
+ writes call-usage rows to the user's encrypted database from the
+ loop's default executor rather than the daemon thread (rule 5;
+ #6294 is related); the egress audit context is thread-local and
+ must be passed in and re-armed on the loop side; and the submit
+ helper must run the coroutine in an explicit minimal context so it
+ does not inherit the daemon thread's ambient search context,
+ including the password (rule 4).
Every LLM object the strategy is constructed with in production
exposes ``ainvoke`` — ``get_llm`` returns a processing wrapper
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 90a0edc8e4..08645364f2 100644
--- a/src/local_deep_research/citation_handlers/base_citation_handler.py
+++ b/src/local_deep_research/citation_handlers/base_citation_handler.py
@@ -242,13 +242,26 @@ class BaseCitationHandler(ABC):
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.
+ Additive: no production caller awaits it yet. It is intended to be
+ submitted to the process's one shared event loop via
+ ``asyncio.run_coroutine_threadsafe`` (ADR-0013,
+ docs/decisions/0013-research-runs-keep-daemon-thread.md); which
+ thread hosts that loop is not decided yet (#6467).
+ :meth:`_invoke_with_streaming` remains the canonical production
+ path on the research thread, and this must never go through
+ ``asyncio.run`` or a per-thread loop (#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.
+
+ Not loop-safe yet, for three reasons: ``TokenCountingCallback``
+ writes call-usage rows to the user's encrypted database from the
+ loop's default executor rather than the daemon thread (rule 5;
+ #6294 is related); the egress audit context is thread-local and
+ must be passed in and re-armed on the loop side; and the submit
+ helper must run the coroutine in an explicit minimal context so it
+ does not inherit the daemon thread's ambient search context,
+ including the password (rule 4).
"""
if self.stream_callback and hasattr(self.llm, "astream"):
chunks: List[str] = []
diff --git a/src/local_deep_research/research_library/notes/services/note_ai_service.py b/src/local_deep_research/research_library/notes/services/note_ai_service.py
index 9c9d1eb7f2..723dc0737a 100644
--- a/src/local_deep_research/research_library/notes/services/note_ai_service.py
+++ b/src/local_deep_research/research_library/notes/services/note_ai_service.py
@@ -782,12 +782,19 @@ Changes summary:"""
) -> str:
"""Generate a summary of changes between two versions.
- Async core, for callers that already run on the process's
- long-lived event loop. Callers with no loop of their own must use
- ``summarize_changes_sync`` instead of bridging to this one. It
- currently has no production caller — the change-summary worker
- uses ``summarize_changes_sync`` — and is kept for the single-loop
- tranche of #5854.
+ Async core for callers already running on an event loop, such as
+ the notes AI routes converted to ``async def`` under #6232 (none
+ of which calls this one today) — not a fan-out interface a
+ research daemon submits to the shared loop (ADR-0013,
+ docs/decisions/0013-research-runs-keep-daemon-thread.md): it
+ builds its LLM from a per-user settings snapshot read fresh from
+ the database on every call (``_get_llm_async`` -> ``_get_llm`` ->
+ ``_build_settings_snapshot``), which rules 4 and 5 forbid for
+ anything submitted to that loop. Callers with no event loop of
+ their own use ``summarize_changes_sync`` instead of bridging to
+ this coroutine. It has no production caller:
+ ``note_service.py``'s change-summary ``ThreadPoolExecutor``
+ worker calls ``summarize_changes_sync`` instead.
"""
try:
shortcut = self._change_summary_shortcut(old_content, new_content)
diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.py
index 8f476c1c8c..b00275862b 100644
--- a/src/local_deep_research/utilities/llm_utils.py
+++ b/src/local_deep_research/utilities/llm_utils.py
@@ -33,10 +33,13 @@ def invoke_llm_sync(llm: Any, prompt: Any) -> Any:
event loop: langchain's cached ``httpx.AsyncClient`` is bound to the
loop that first used it, so bridging a sync caller onto ``ainvoke``
with a throwaway loop double-sends or hard-fails from the second call
- onward (see #6293). The helper exists to give the research pipeline's
- question generators, filters, explorers, context managers and
- evaluators one call site to change once a single-loop runner makes
- the async path safe.
+ onward (see #6293). The helper is the research pipeline's one
+ synchronous dispatch seam — question generators, filters, explorers,
+ context managers and evaluators call through it (exception below) —
+ and it is the canonical production path. If I/O-bound fan-out is wired, it means
+ callers submit :func:`ainvoke_llm` coroutines to the process's single
+ shared event loop, not routing this helper through that loop; this
+ helper itself never opens or uses a per-call loop.
Returns the RAW response object, so each caller's existing parsing
(``get_llm_response_text`` / ``.content`` / ``extract_json``) is
@@ -51,12 +54,21 @@ def invoke_llm_sync(llm: Any, prompt: Any) -> Any:
async def ainvoke_llm(llm: Any, prompt: Any) -> Any:
"""Async core matching :func:`invoke_llm_sync` (#5854).
- Additive: nothing in production awaits this yet. It becomes usable
- once the process has a single long-lived event loop for the LLM
- clients (#6293) and ``TokenCountingCallback`` records call-site
- attribution on the async dispatch path (#6294); ``ainvoke`` coverage
- on ``RateLimitedLLMWrapper`` (#6232) is in place, with the wrapper's
- remaining surfaces tracked in #6296.
+ Additive: nothing in production awaits this yet. Before it is usable,
+ the process needs a single long-lived event loop for the LLM clients
+ (#6293), and three ADR-0013 preconditions
+ (docs/decisions/0013-research-runs-keep-daemon-thread.md) must hold:
+ ``TokenCountingCallback`` needs to stop writing its call-usage row to
+ the user's encrypted database from the loop's default executor (rule
+ 5; #6294 tracks the related attribution gap); the egress audit
+ context is thread-local and must be passed in and re-armed on the
+ loop side; and the submit helper must run the coroutine in an
+ explicit minimal context so it does not inherit the daemon thread's
+ ambient search context, including the password (rule 4).
+ ``RateLimitedLLMWrapper.ainvoke`` already awaits the wrapped
+ provider's own async client and was hardened in #6347; that is the
+ correct shape for a fan-out interface and the pattern this helper
+ follows.
Every production model is a ``ProcessingLLMWrapper``, which defines
``ainvoke``; a wrapped object without it is a configuration error and
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.py
index ed4db35704..c8b9f33da0 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
@@ -187,10 +187,23 @@ class FullSearchResults:
) -> 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).
+ Additive: no production caller awaits it yet. It is intended to be
+ submitted to the process's one shared event loop via
+ ``asyncio.run_coroutine_threadsafe`` (ADR-0013,
+ docs/decisions/0013-research-runs-keep-daemon-thread.md); which
+ thread hosts that loop is not decided yet (#6467).
+ :meth:`check_urls` remains the canonical production path on the
+ research thread, and this must never go through ``asyncio.run`` or
+ a per-thread loop (#6293).
+
+ Not loop-safe yet, for three reasons: ``TokenCountingCallback``
+ writes call-usage rows to the user's encrypted database from the
+ loop's default executor rather than the daemon thread (rule 5;
+ #6294 is related); the egress audit context is thread-local and
+ must be passed in and re-armed on the loop side; and the submit
+ helper must run the coroutine in an explicit minimal context so it
+ does not inherit the daemon thread's ambient search context,
+ including the password (rule 4).
"""
if not results:
return results
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 4d7799c6f7..cbdd6b7783 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
@@ -164,15 +164,24 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
Without this, ``ainvoke`` falls through ``__getattr__`` to the
base LLM and silently skips the adaptive wait/retry loop and
- the RateLimitError wrapping — a behavioural hole once async
- callers become the primary path (#5854). The ``@retry``
- decorator detects the coroutine and sleeps between attempts
+ the RateLimitError wrapping — a behavioural hole for any caller
+ that reaches this async twin, including the fan-out path daemon
+ code submits to the process's one shared event loop (ADR-0013,
+ docs/decisions/0013-research-runs-keep-daemon-thread.md); the
+ sync ``invoke`` stays the canonical production path on the
+ research thread. The ``@retry`` decorator detects the coroutine
+ and sleeps between attempts
with ``asyncio.sleep`` (tenacity AsyncRetrying), so the sleep
itself does not block the loop. The wait STRATEGY that
computes that sleep still runs synchronously on the loop —
- see the note on ``_should_rate_limit``; today that is moot
- because ``self.rate_limiter`` is always ``None``.
- See #6232/#6246/#6249/#6268 for the history.
+ see the note on ``_should_rate_limit``. ``_acall_rate_limited``
+ also calls ``tracker.record_outcome`` (and from it
+ ``_update_estimate``) synchronously on the loop after each
+ successful call and each rate-limit failure; those can read
+ the settings context and the search context and persist
+ through the metrics database. Both are moot today because
+ ``self.rate_limiter`` is always ``None``.
+ See #6232/#6246/#6249/#6268/#6347 for the history.
"""
return await self._acall_rate_limited(
lambda: self.base_llm.ainvoke(*args, **kwargs)