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(security): close the LangChain surface escapes in RateLimitedLLMWrapper (#6347)

Huang-404-Q26900c60b810
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 ecb3d24f3c..1033a13206 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
@@ -145,65 +145,208 @@ 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."""
- if self.rate_limiter:
- rate_limit_key = self._get_rate_limit_key()
-
- # Define retry logic
- @retry(
- wait=AdaptiveLLMWait(self.rate_limiter, rate_limit_key),
- stop=stop_after_attempt(3),
- retry=retry_if_exception(is_llm_rate_limit_error),
- )
- def _invoke_with_retry():
- return self._do_invoke(*args, **kwargs)
-
+ return self._call_rate_limited(
+ lambda: self.base_llm.invoke(*args, **kwargs)
+ )
+
+ async def ainvoke(self, *args, **kwargs):
+ """Async invoke; see #6232/#6246/#6249/#6268 for the history."""
+ return await self._acall_rate_limited(
+ lambda: self.base_llm.ainvoke(*args, **kwargs)
+ )
+
+ def _scrub_or_raise(self, error):
+ """Re-raise with scrubbing: provider 429 bodies can echo the
+ Authorization header, so the body must not reach logs or
+ exception chains unscrubbed. Non-rate-limit errors pass
+ through unchanged."""
+ if is_llm_rate_limit_error(error):
+ logger.warning("LLM rate limit error detected")
+ safe_msg = scrub_error(error)
+ raise RateLimitError(f"LLM rate limit: {safe_msg}") from None
+ raise error
+
+ def _call_rate_limited(self, call):
+ """Run one base-LLM call with retries and tracker bookkeeping
+ when rate limiting is enabled; scrub rate-limit errors either
+ way."""
+ if not self.rate_limiter:
+ try:
+ return call()
+ except Exception as e:
+ self._scrub_or_raise(e)
+
+ rate_limit_key = self._get_rate_limit_key()
+ tracker = self.rate_limiter
+ if tracker is None: # defensive: narrowed above in this branch
+ return call()
+
+ @retry(
+ wait=AdaptiveLLMWait(tracker, rate_limit_key),
+ stop=stop_after_attempt(3),
+ retry=retry_if_exception(is_llm_rate_limit_error),
+ )
+ def _with_retry():
try:
- result = _invoke_with_retry()
+ return call()
+ except Exception as e:
+ self._scrub_or_raise(e)
- # Record successful attempt
- self.rate_limiter.record_outcome(
+ try:
+ result = _with_retry()
+ tracker.record_outcome(
+ engine_type=rate_limit_key,
+ wait_time=0,
+ success=True,
+ retry_count=0,
+ )
+ return result
+ except Exception as e:
+ if is_llm_rate_limit_error(e):
+ tracker.record_outcome(
engine_type=rate_limit_key,
- wait_time=0, # First attempt had no wait
- success=True,
+ wait_time=0,
+ success=False,
retry_count=0,
)
+ raise
- return result
+ def stream(self, *args, **kwargs):
+ """Stream through the base LLM with scrub on stream-start errors.
+ Chunks are forwarded untouched: a credential echoed in a 429
+ body can straddle chunk boundaries, so scrubbing individual
+ chunks is unsound. Rate-limit failures surface at stream start
+ (the common case for 429s) and go through the same wrap as
+ invoke().
+ """
+
+ def _source():
+ try:
+ return self.base_llm.stream(*args, **kwargs)
except Exception as e:
- # Only record rate limit failures, not general failures
- if is_llm_rate_limit_error(e):
- self.rate_limiter.record_outcome(
- engine_type=rate_limit_key,
- wait_time=0,
- success=False,
- retry_count=0,
- )
- raise
- else:
- # No rate limiting, just invoke directly
- return self._do_invoke(*args, **kwargs)
-
- def _do_invoke(self, *args, **kwargs):
- """Actually invoke the LLM."""
+ self._scrub_or_raise(e)
+
+ return self._call_rate_limited(_source)
+
+ async def _astream(self, *args, **kwargs):
+ """Async generator implementing LangChain's astream contract:
+ ``async for chunk in model.astream(...)``. Getting the underlying
+ stream goes through the rate-limited wrap (scrub/retry on stream
+ start); chunks themselves are forwarded untouched — a credential
+ echoed in a 429 body can straddle chunk boundaries, so per-chunk
+ scrubbing is unsound — while failures raised during iteration go
+ through the scrub."""
try:
- return self.base_llm.invoke(*args, **kwargs)
+ source = self.base_llm.astream(*args, **kwargs)
+ except Exception as e:
+ self._scrub_or_raise(e)
+
+ async for chunk in source:
+ yield chunk
+
+ async def _acall_rate_limited(self, call):
+ """Async variant of _call_rate_limited."""
+ if not self.rate_limiter:
+ try:
+ return await call()
+ except Exception as e:
+ self._scrub_or_raise(e)
+
+ rate_limit_key = self._get_rate_limit_key()
+ tracker = self.rate_limiter
+ if tracker is None: # defensive: narrowed above in this branch
+ return call()
+
+ @retry(
+ wait=AdaptiveLLMWait(tracker, rate_limit_key),
+ stop=stop_after_attempt(3),
+ retry=retry_if_exception(is_llm_rate_limit_error),
+ )
+ async def _with_retry():
+ try:
+ return await call()
+ except Exception as e:
+ self._scrub_or_raise(e)
+
+ try:
+ result = await _with_retry()
+ tracker.record_outcome(
+ engine_type=rate_limit_key,
+ wait_time=0,
+ success=True,
+ retry_count=0,
+ )
+ return result
except Exception as e:
- # Check if it's a rate limit error and wrap it
if is_llm_rate_limit_error(e):
- logger.warning("LLM rate limit error detected")
- # Scrub before wrapping: LLM providers can echo the
- # Authorization header back in a 429 body. The scrub
- # keeps non-credential text (e.g. "retry after 20
- # seconds") intact for extract_retry_after(). `from
- # None` suppresses the __context__ chain, which still
- # carries the raw message.
- safe_msg = scrub_error(e)
- raise RateLimitError(
- f"LLM rate limit: {safe_msg}"
- ) from None
+ tracker.record_outcome(
+ engine_type=rate_limit_key,
+ wait_time=0,
+ success=False,
+ retry_count=0,
+ )
raise
+ @staticmethod
+ def _configs_for_inputs(config, inputs):
+ """Resolve per-item configs from a shared config or a list of
+ per-input configs (LangChain Runnable.batch takes either)."""
+ if isinstance(config, list):
+ if len(config) != len(inputs):
+ raise ValueError(
+ "configs must match the number of inputs "
+ f"({len(config)} != {len(inputs)})"
+ )
+ return list(config)
+ return [config] * len(inputs)
+
+ def batch(
+ self, inputs, config=None, *, return_exceptions=False, **kwargs
+ ):
+ """Batch through invoke(), forwarding config (shared or
+ per-input) so caller callbacks/tags/metadata survive."""
+ configs = self._configs_for_inputs(config, inputs)
+ results = []
+ for msg, conf in zip(inputs, configs):
+ try:
+ results.append(self.invoke(msg, conf, **kwargs))
+ except Exception as e:
+ if return_exceptions:
+ results.append(e)
+ else:
+ raise
+ return results
+
+ async def abatch(
+ self, inputs, config=None, *, return_exceptions=False, **kwargs
+ ):
+ """Async counterpart of batch()."""
+ configs = self._configs_for_inputs(config, inputs)
+ results = []
+ for msg, conf in zip(inputs, configs):
+ try:
+ results.append(await self.ainvoke(msg, conf, **kwargs))
+ except Exception as e:
+ if return_exceptions:
+ results.append(e)
+ else:
+ raise
+ return results
+
+ def bind_tools(self, tools, **kwargs):
+ """Bind tools and re-wrap so the bound runnable keeps rate
+ 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)
+
+ 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)
+
# Pass through any other attributes to the base LLM
def __getattr__(self, name):
return getattr(self.base_llm, name)
diff --git a/tests/rate_limiting/test_llm_wrapper_extended.py b/tests/rate_limiting/test_llm_wrapper_extended.py
index cdaf131091..5ac3c6efe1 100644
--- a/tests/rate_limiting/test_llm_wrapper_extended.py
+++ b/tests/rate_limiting/test_llm_wrapper_extended.py
@@ -8,7 +8,7 @@ These tests exercise the actual rate-limiting code paths.
Tests cover:
- AdaptiveLLMWait.__call__: tracker wait, retry-after merging, error recording
- RateLimitedLLMWrapper._check_if_local_model: provider + URL detection
-- RateLimitedLLMWrapper._do_invoke: error wrapping
+- RateLimitedLLMWrapper.invoke: error wrapping
- RateLimitedLLMWrapper.invoke with rate limiting active
- __str__ and __repr__
"""
@@ -191,12 +191,12 @@ class TestCheckIfLocalModel:
# ---------------------------------------------------------------------------
-# RateLimitedLLMWrapper._do_invoke
+# RateLimitedLLMWrapper.invoke
# ---------------------------------------------------------------------------
class TestDoInvoke:
- """Tests for _do_invoke."""
+ """Tests for invoke."""
def test_rate_limit_error_wrapped_into_rate_limit_error(self):
"""Rate limit errors are wrapped into RateLimitError."""
@@ -214,7 +214,7 @@ class TestDoInvoke:
wrapper = create_rate_limited_llm_wrapper(base_llm)
with pytest.raises(RateLimitError, match="LLM rate limit"):
- wrapper._do_invoke("test prompt")
+ wrapper.invoke("test prompt")
def test_rate_limit_error_message_is_scrubbed(self):
"""Wrapped RateLimitError must not carry raw exception secrets.
@@ -242,7 +242,7 @@ class TestDoInvoke:
wrapper = create_rate_limited_llm_wrapper(base_llm)
with pytest.raises(RateLimitError) as exc_info:
- wrapper._do_invoke("test prompt")
+ wrapper.invoke("test prompt")
msg = str(exc_info.value)
assert "sk-llmleaked1234567890" not in msg
@@ -261,7 +261,7 @@ class TestDoInvoke:
wrapper = create_rate_limited_llm_wrapper(base_llm)
with pytest.raises(ValueError, match="Invalid input format"):
- wrapper._do_invoke("test prompt")
+ wrapper.invoke("test prompt")
def test_successful_invoke_returns_result(self):
"""Successful invoke returns result."""
@@ -273,7 +273,7 @@ class TestDoInvoke:
base_llm.invoke.return_value = "LLM response"
wrapper = create_rate_limited_llm_wrapper(base_llm)
- result = wrapper._do_invoke("test prompt")
+ result = wrapper.invoke("test prompt")
assert result == "LLM response"
@@ -313,7 +313,7 @@ class TestInvokeWithRateLimiting:
)
def test_invoke_without_rate_limiter_delegates_directly(self):
- """Without rate limiter, invoke delegates to _do_invoke."""
+ """Without rate limiter, invoke delegates straight to the base LLM."""
from local_deep_research.web_search_engines.rate_limiting.llm.wrapper import (
create_rate_limited_llm_wrapper,
)
diff --git a/tests/rate_limiting/test_rate_limiting_behavior.py b/tests/rate_limiting/test_rate_limiting_behavior.py
index 50ad7cf603..d13f3c49cb 100644
--- a/tests/rate_limiting/test_rate_limiting_behavior.py
+++ b/tests/rate_limiting/test_rate_limiting_behavior.py
@@ -4,7 +4,7 @@ Behavioral tests for the rate limiting subsystem.
Covers untested logic in:
- detection.py: provider-specific detection paths, extract_retry_after edge cases
- wrapper.py: _check_if_local_model URL detection, _get_rate_limit_key edge cases,
- _do_invoke rate limit wrapping, string representations
+ invoke rate limit wrapping, string representations
- exceptions.py: exception hierarchy
"""
@@ -504,12 +504,12 @@ class TestWrapperStringRepresentations:
# ---------------------------------------------------------------------------
-# wrapper.py — _do_invoke rate limit error wrapping
+# wrapper.py — invoke rate limit error wrapping
# ---------------------------------------------------------------------------
class TestDoInvokeRateLimitWrapping:
- """Tests for _do_invoke wrapping rate limit errors as RateLimitError."""
+ """Tests for invoke wrapping rate limit errors as RateLimitError."""
def test_rate_limit_error_wrapped(self):
"""Rate limit error from base LLM → wrapped as RateLimitError."""
@@ -526,7 +526,7 @@ class TestDoInvokeRateLimitWrapping:
wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")
with pytest.raises(RateLimitError, match="LLM rate limit"):
- wrapper._do_invoke("test prompt")
+ wrapper.invoke("test prompt")
def test_non_rate_limit_error_not_wrapped(self):
"""Non-rate-limit error from base LLM → re-raised as-is."""
@@ -540,7 +540,7 @@ class TestDoInvokeRateLimitWrapping:
wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")
with pytest.raises(ValueError, match="Invalid input format"):
- wrapper._do_invoke("test prompt")
+ wrapper.invoke("test prompt")
def test_successful_invoke_returns_result(self):
"""Successful invoke returns the base LLM result."""
@@ -553,7 +553,7 @@ class TestDoInvokeRateLimitWrapping:
mock_llm.invoke.return_value = "response text"
wrapper = create_rate_limited_llm_wrapper(mock_llm, provider="openai")
- result = wrapper._do_invoke("test prompt")
+ result = wrapper.invoke("test prompt")
assert result == "response text"
diff --git a/tests/test_llm_rate_limiting.py b/tests/test_llm_rate_limiting.py
index 747936a7a8..bec09dbad6 100644
--- a/tests/test_llm_rate_limiting.py
+++ b/tests/test_llm_rate_limiting.py
@@ -173,3 +173,227 @@ class TestIntegrationWithTracker:
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+
+
+class TestRateLimitedWrapperLangChainSurface:
+ """Issue #6296: every public LangChain entry point must be handled by the
+ wrapper itself — not resolved through __getattr__ to the raw model, which
+ skips scrubbing and rate-limit bookkeeping."""
+
+ LANGCHAIN_ENTRY_POINTS = [
+ "invoke",
+ "ainvoke",
+ "stream",
+ "astream",
+ "batch",
+ "abatch",
+ "generate",
+ "agenerate",
+ "bind_tools",
+ "with_structured_output",
+ ]
+
+ @pytest.fixture
+ def mock_llm(self):
+ llm = Mock()
+ llm.model_name = "test-model"
+ llm.base_url = "https://api.example.com"
+ llm.invoke = Mock(return_value=AIMessage(content="ok"))
+ return llm
+
+ def _wrapper(self, mock_llm):
+ return create_rate_limited_llm_wrapper(mock_llm, provider="openai")
+
+ def test_rate_limit_error_is_scrubbed_on_stream(self, mock_llm):
+ """A 429 raised when the stream starts must not leak the body."""
+ fake_key = "sk-" + "a1b2c3d4e5f6g7h8i9j0" # 20+ chars: real key shape
+ err = Exception(f"Error: 429 quota exceeded, key {fake_key}")
+ mock_llm.stream = Mock(side_effect=err)
+ wrapper = self._wrapper(mock_llm)
+
+ with pytest.raises(Exception) as exc_info:
+ list(wrapper.stream("prompt"))
+
+ assert fake_key not in str(exc_info.value)
+
+ def test_stream_forwards_chunks(self, mock_llm):
+ mock_llm.stream = Mock(return_value=iter(["a", "b"]))
+ wrapper = self._wrapper(mock_llm)
+
+ chunks = list(wrapper.stream("prompt"))
+
+ assert chunks == ["a", "b"]
+ mock_llm.stream.assert_called_once_with("prompt")
+
+ def test_bind_tools_rewraps_bound_model(self, mock_llm):
+ """bind_tools must return a wrapper, not the raw bound model."""
+ bound = Mock()
+ mock_llm.bind_tools = Mock(return_value=bound)
+ wrapper = self._wrapper(mock_llm)
+
+ result = wrapper.bind_tools([])
+
+ mock_llm.bind_tools.assert_called_once_with([])
+ assert result.base_llm is bound
+
+ def test_with_structured_output_rewraps(self, mock_llm):
+ bound = Mock()
+ mock_llm.with_structured_output = Mock(return_value=bound)
+ wrapper = self._wrapper(mock_llm)
+
+ result = wrapper.with_structured_output({"type": "object"})
+
+ mock_llm.with_structured_output.assert_called_once_with(
+ {"type": "object"}
+ )
+ assert result.base_llm is bound
+
+ def test_batch_preserves_order_and_results(self, mock_llm):
+ wrapper = self._wrapper(mock_llm)
+ calls = []
+ mock_llm.invoke = Mock(
+ side_effect=lambda m, cfg=None, **kw: (
+ calls.append(m) or AIMessage(content=f"r-{m}")
+ )
+ )
+
+ results = wrapper.batch(["m1", "m2"])
+
+ assert [r.content for r in results] == ["r-m1", "r-m2"]
+
+ def test_batch_return_exceptions_collects_failures(self, mock_llm):
+ wrapper = self._wrapper(mock_llm)
+ mock_llm.invoke = Mock(
+ side_effect=[AIMessage(content="ok"), Exception("boom")]
+ )
+
+ results = wrapper.batch(["m1", "m2"], return_exceptions=True)
+
+ assert results[0].content == "ok"
+ assert isinstance(results[1], Exception)
+
+ def test_batch_raises_without_return_exceptions(self, mock_llm):
+ wrapper = self._wrapper(mock_llm)
+ mock_llm.invoke = Mock(side_effect=Exception("boom"))
+
+ with pytest.raises(Exception, match="boom"):
+ wrapper.batch(["m1"])
+
+ def test_rate_limit_error_wrapped_in_batch(self, mock_llm):
+ """Batch through invoke() inherits the 429 scrub: the provider body
+ must not surface raw."""
+ wrapper = self._wrapper(mock_llm)
+ fake_key = "sk-" + "z9y8x7w6v5u4t3s2r1q0"
+ mock_llm.invoke = Mock(
+ side_effect=Exception(f"429 quota, auth Bearer {fake_key}")
+ )
+
+ results = wrapper.batch(["m1"], return_exceptions=True)
+
+ assert fake_key not in str(results[0])
+
+ def test_scrub_applies_even_with_rate_limiter_disabled(self, mock_llm):
+ """Rate limiting is off by default; the credential scrub must not be
+ gated on it."""
+ wrapper = self._wrapper(mock_llm)
+ fake_key = "sk-" + "m1n2o3p4q5r6s7t8u9v0"
+ mock_llm.invoke = Mock(
+ side_effect=Exception(f"429 quota, auth Bearer {fake_key}")
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ wrapper.invoke("prompt")
+
+ assert fake_key not in str(exc_info.value)
+
+
+class TestRateLimitedWrapperReviewFixes:
+ """Regression coverage for the maintainer CHANGES_REQUESTED on #6347."""
+
+ @pytest.fixture
+ def mock_llm(self):
+ llm = Mock()
+ llm.model_name = "test-model"
+ llm.base_url = "https://api.example.com"
+ llm.invoke = Mock(return_value=AIMessage(content="ok"))
+ return llm
+
+ def _wrapper(self, mock_llm):
+ return create_rate_limited_llm_wrapper(mock_llm, provider="openai")
+
+ def test_astream_is_async_iterable(self, mock_llm):
+ """`async for chunk in wrapper.astream(...)` must work without
+ awaiting astream first (LangChain contract)."""
+ import asyncio
+
+ async def fake_astream(*args, **kwargs):
+ for chunk in ["c1", "c2"]:
+ yield chunk
+
+ mock_llm.astream = fake_astream
+ wrapper = self._wrapper(mock_llm)
+
+ async def consume():
+ return [chunk async for chunk in wrapper.astream("prompt")]
+
+ chunks = asyncio.run(consume())
+ assert chunks == ["c1", "c2"]
+
+ def test_batch_forwards_shared_config(self, mock_llm):
+ """A shared config must reach the underlying invoke."""
+ wrapper = self._wrapper(mock_llm)
+ captured = []
+ mock_llm.invoke = Mock(
+ side_effect=lambda msg, cfg=None, **kw: (
+ captured.append(cfg) or AIMessage(content="ok")
+ )
+ )
+
+ wrapper.batch(["m1", "m2"], {"tags": ["t1"]})
+
+ assert captured == [{"tags": ["t1"]}, {"tags": ["t1"]}]
+
+ def test_batch_forwards_per_input_configs(self, mock_llm):
+ wrapper = self._wrapper(mock_llm)
+ captured = []
+ mock_llm.invoke = Mock(
+ side_effect=lambda msg, cfg=None, **kw: (
+ captured.append(cfg) or AIMessage(content="ok")
+ )
+ )
+
+ per_input = [{"metadata": 1}, {"metadata": 2}]
+ wrapper.batch(["m1", "m2"], per_input)
+
+ assert captured == per_input
+
+ def test_batch_config_mismatch_raises(self, mock_llm):
+ wrapper = self._wrapper(mock_llm)
+
+ with pytest.raises(ValueError, match="configs must match"):
+ wrapper.batch(["m1", "m2"], [{"only": "one"}])
+
+ def test_abatch_forwards_shared_and_per_input_configs(self, mock_llm):
+ """Async batches must forward shared and per-input configs too
+ (review parity for the sync batch cases)."""
+ import asyncio
+
+ wrapper = self._wrapper(mock_llm)
+ captured = []
+
+ async def fake_ainvoke(msg, cfg=None, **kw):
+ captured.append(cfg)
+ return AIMessage(content=f"r-{msg}")
+
+ mock_llm.ainvoke = fake_ainvoke
+
+ async def run():
+ await wrapper.abatch(["m1"], {"tags": ["shared"]})
+ await wrapper.abatch(
+ ["m1", "m2"], [{"metadata": 1}, {"metadata": 2}]
+ )
+
+ asyncio.run(run())
+
+ assert captured[:1] == [{"tags": ["shared"]}]
+ assert captured[1:] == [{"metadata": 1}, {"metadata": 2}]
diff --git a/tests/web_search_engines/rate_limiting/test_llm_wrapper_high_value.py b/tests/web_search_engines/rate_limiting/test_llm_wrapper_high_value.py
index 6aef0439b4..3c1042d3a3 100644
--- a/tests/web_search_engines/rate_limiting/test_llm_wrapper_high_value.py
+++ b/tests/web_search_engines/rate_limiting/test_llm_wrapper_high_value.py
@@ -6,7 +6,7 @@ Complements test_llm_wrapper_pure_logic.py by covering:
- RateLimitedLLMWrapper.invoke: direct passthrough without rate limiting
- __getattr__ passthrough to base LLM
- __str__ and __repr__ formatting
-- _do_invoke: exception wrapping for rate limit errors
+- invoke: exception wrapping for rate limit errors
"""
import types