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(metrics): propagate research context across LangGraph tool threads (#3631)

LearningCircuitd077054f3266
diff --git a/src/local_deep_research/utilities/thread_context.py b/src/local_deep_research/utilities/thread_context.py
index 65d5074592..5b3dc5520d 100644
--- a/src/local_deep_research/utilities/thread_context.py
+++ b/src/local_deep_research/utilities/thread_context.py
@@ -1,60 +1,60 @@
"""
-Utility functions for handling thread-local context propagation.
-
-This module provides helpers for propagating research context across thread boundaries,
-which is necessary when strategies use ThreadPoolExecutor for parallel searches.
+Utility functions for handling research context propagation.
+
+This module provides helpers for propagating research context across thread
+and asyncio boundaries. Built on ``contextvars.ContextVar`` so the context
+is correctly inherited by frameworks that copy the context to worker
+threads (e.g. langchain's ``ContextThreadPoolExecutor`` used by LangGraph
+for parallel tool execution). For stdlib ``ThreadPoolExecutor`` — which
+does not copy context — use ``preserve_research_context`` below.
"""
import functools
from contextlib import contextmanager
-from threading import local
-from typing import Any, Callable, Dict, Generator
+from contextvars import ContextVar
+from typing import Any, Callable, Dict, Generator, Optional
from loguru import logger
-_g_thread_data = local()
-"""
-Thread-local storage for research context data.
-"""
+_search_context_var: ContextVar[Optional[Dict[str, Any]]] = ContextVar(
+ "ldr_search_context", default=None
+)
def set_search_context(context: Dict[str, Any]) -> None:
"""
- Sets the research context for this entire thread.
+ Sets the research context for the current execution context.
Args:
context: The context to set.
"""
- global _g_thread_data
- if hasattr(_g_thread_data, "context"):
+ if _search_context_var.get() is not None:
logger.debug(
"Context already set for this thread. It will be overwritten."
)
- _g_thread_data.context = context.copy()
+ _search_context_var.set(context.copy())
def clear_search_context() -> None:
"""
- Clears the research context for this thread.
+ Clears the research context for the current execution context.
Should be called in a finally block after set_search_context() to prevent
context from leaking to subsequent tasks when threads are reused in a pool.
"""
- global _g_thread_data
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ _search_context_var.set(None)
def get_search_context() -> Dict[str, Any] | None:
"""
- Gets the current research context for this thread.
+ Gets the current research context.
Returns:
The context dictionary, or None if no context is set.
"""
- context = getattr(_g_thread_data, "context", None)
+ context = _search_context_var.get()
if context is not None:
context = context.copy()
return context
diff --git a/tests/utilities/test_thread_context.py b/tests/utilities/test_thread_context.py
index 723c10e39c..ef8ce15c48 100644
--- a/tests/utilities/test_thread_context.py
+++ b/tests/utilities/test_thread_context.py
@@ -2,13 +2,13 @@
import threading
from concurrent.futures import ThreadPoolExecutor
+from contextvars import copy_context
from unittest.mock import patch
import pytest
from local_deep_research.utilities.thread_context import (
- _g_thread_data,
clear_search_context,
get_search_context,
preserve_research_context,
@@ -21,29 +21,27 @@ class TestSetSearchContext:
"""Tests for set_search_context function."""
def setup_method(self):
- """Clear thread-local data before each test."""
- if hasattr(_g_thread_data, "context"):
- delattr(_g_thread_data, "context")
+ """Clear context before each test."""
+ clear_search_context()
def test_sets_context(self):
- """Should set context in thread-local storage."""
+ """Should set context."""
context = {"research_id": "123", "user": "test"}
set_search_context(context)
- assert hasattr(_g_thread_data, "context")
- assert _g_thread_data.context == context
+ assert get_search_context() == context
def test_copies_context(self):
"""Should copy context to avoid mutations."""
context = {"research_id": "123"}
set_search_context(context)
context["new_key"] = "value"
- assert "new_key" not in _g_thread_data.context
+ assert "new_key" not in get_search_context()
def test_overwrites_existing_context(self):
"""Should overwrite existing context."""
set_search_context({"old": "context"})
set_search_context({"new": "context"})
- assert _g_thread_data.context == {"new": "context"}
+ assert get_search_context() == {"new": "context"}
def test_logs_debug_on_overwrite(self):
"""Should log debug message when overwriting existing context."""
@@ -57,22 +55,20 @@ class TestSetSearchContext:
def test_handles_empty_context(self):
"""Should handle empty context dictionary."""
set_search_context({})
- assert _g_thread_data.context == {}
+ assert get_search_context() == {}
class TestClearSearchContext:
"""Tests for clear_search_context function."""
def setup_method(self):
- """Clear thread-local data before each test."""
- if hasattr(_g_thread_data, "context"):
- delattr(_g_thread_data, "context")
+ """Clear context before each test."""
+ clear_search_context()
def test_clears_existing_context(self):
"""Should clear context when set."""
set_search_context({"research_id": "123"})
clear_search_context()
- assert not hasattr(_g_thread_data, "context")
assert get_search_context() is None
def test_noop_when_no_context(self):
@@ -91,9 +87,8 @@ class TestGetSearchContext:
"""Tests for get_search_context function."""
def setup_method(self):
- """Clear thread-local data before each test."""
- if hasattr(_g_thread_data, "context"):
- delattr(_g_thread_data, "context")
+ """Clear context before each test."""
+ clear_search_context()
def test_returns_none_when_not_set(self):
"""Should return None when no context is set."""
@@ -114,7 +109,7 @@ class TestGetSearchContext:
result = get_search_context()
result["mutated"] = True
# Original should not be mutated
- assert "mutated" not in _g_thread_data.context
+ assert "mutated" not in get_search_context()
def test_multiple_calls_return_same_data(self):
"""Multiple calls should return same data."""
@@ -129,9 +124,8 @@ class TestThreadIsolation:
"""Tests for thread isolation of context."""
def setup_method(self):
- """Clear thread-local data before each test."""
- if hasattr(_g_thread_data, "context"):
- delattr(_g_thread_data, "context")
+ """Clear context before each test."""
+ clear_search_context()
def test_context_isolated_between_threads(self):
"""Context should be isolated between threads."""
@@ -181,9 +175,8 @@ class TestPreserveResearchContext:
"""Tests for preserve_research_context decorator."""
def setup_method(self):
- """Clear thread-local data before each test."""
- if hasattr(_g_thread_data, "context"):
- delattr(_g_thread_data, "context")
+ """Clear context before each test."""
+ clear_search_context()
def test_preserves_context_in_thread_pool(self):
"""Should preserve context when function runs in thread pool."""
@@ -334,9 +327,8 @@ class TestEdgeCases:
"""Edge case tests for thread_context module."""
def setup_method(self):
- """Clear thread-local data before each test."""
- if hasattr(_g_thread_data, "context"):
- delattr(_g_thread_data, "context")
+ """Clear context before each test."""
+ clear_search_context()
def test_context_with_nested_dict(self):
"""Should handle nested dictionaries in context."""
@@ -374,9 +366,8 @@ class TestSearchContextManager:
"""Tests for search_context context manager."""
def setup_method(self):
- """Clear thread-local data before each test."""
- if hasattr(_g_thread_data, "context"):
- delattr(_g_thread_data, "context")
+ """Clear context before each test."""
+ clear_search_context()
def test_sets_and_clears_context(self):
"""Context should be set inside and cleared after the block."""
@@ -427,3 +418,47 @@ class TestSearchContextManager:
assert get_search_context()["research_id"] == "inner"
# Inner exited — context is cleared
assert get_search_context() is None
+
+
+class TestContextVarsPropagation:
+ """Regression: context must propagate through frameworks that copy
+ contextvars to worker threads (e.g. langchain's ContextThreadPoolExecutor
+ used by LangGraph for tool execution)."""
+
+ def setup_method(self):
+ clear_search_context()
+
+ def test_copy_context_run_propagates_to_worker(self):
+ """copy_context().run(fn) — the mechanism used by langchain's
+ ContextThreadPoolExecutor — must carry our context across threads."""
+ set_search_context({"research_id": "ctx-propagation"})
+
+ observed = {}
+
+ def worker():
+ observed["ctx"] = get_search_context()
+
+ # Capture the parent context, then run the worker inside that copy
+ # on a new thread (matches what ContextThreadPoolExecutor.submit does).
+ ctx = copy_context()
+ t = threading.Thread(target=ctx.run, args=(worker,))
+ t.start()
+ t.join()
+
+ assert observed["ctx"] == {"research_id": "ctx-propagation"}
+
+ def test_worker_mutation_does_not_leak_to_caller(self):
+ """A copied context is isolated — set_search_context inside the
+ worker must not affect the caller's context."""
+ set_search_context({"research_id": "caller"})
+
+ def worker():
+ set_search_context({"research_id": "worker"})
+
+ ctx = copy_context()
+ t = threading.Thread(target=ctx.run, args=(worker,))
+ t.start()
+ t.join()
+
+ # Caller still sees its own value
+ assert get_search_context() == {"research_id": "caller"}
diff --git a/tests/utilities/test_thread_context_coverage.py b/tests/utilities/test_thread_context_coverage.py
index 7d73df4755..92b5fd1de7 100644
--- a/tests/utilities/test_thread_context_coverage.py
+++ b/tests/utilities/test_thread_context_coverage.py
@@ -12,7 +12,6 @@ from unittest.mock import MagicMock, patch
import pytest
from local_deep_research.utilities.thread_context import (
- _g_thread_data,
clear_search_context,
get_search_context,
preserve_research_context,
@@ -22,8 +21,7 @@ from local_deep_research.utilities.thread_context import (
def _cleanup():
"""Remove any leftover context on the current thread."""
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
# ---------------------------------------------------------------------------
diff --git a/tests/utilities/test_thread_context_extended.py b/tests/utilities/test_thread_context_extended.py
index 8244e9008f..820229d214 100644
--- a/tests/utilities/test_thread_context_extended.py
+++ b/tests/utilities/test_thread_context_extended.py
@@ -10,7 +10,6 @@ from unittest.mock import patch
import pytest
from local_deep_research.utilities.thread_context import (
- _g_thread_data,
clear_search_context,
get_search_context,
preserve_research_context,
@@ -26,8 +25,7 @@ from local_deep_research.utilities.thread_context import (
def _cleanup():
"""Remove any leftover context on the current thread."""
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
# ---------------------------------------------------------------------------
@@ -45,10 +43,10 @@ class TestSetSearchContextExtended:
_cleanup()
def test_sets_context_in_thread_local_storage(self):
- """Setting context stores it on the thread-local object."""
+ """Setting context stores it for retrieval via get_search_context."""
ctx = {"research_id": "abc", "query": "test query"}
set_search_context(ctx)
- stored = getattr(_g_thread_data, "context", None)
+ stored = get_search_context()
assert stored is not None
assert stored == {"research_id": "abc", "query": "test query"}
@@ -62,7 +60,7 @@ class TestSetSearchContextExtended:
original["key"] = "mutated"
original["extra"] = "added"
- stored = _g_thread_data.context
+ stored = get_search_context()
assert stored["key"] == "original_value"
assert "extra" not in stored
@@ -81,7 +79,7 @@ class TestSetSearchContextExtended:
or "already set" in mock_logger.debug.call_args[0][0].lower()
)
- assert _g_thread_data.context == {"round": 2}
+ assert get_search_context() == {"round": 2}
# ---------------------------------------------------------------------------
@@ -99,18 +97,18 @@ class TestClearSearchContextExtended:
_cleanup()
def test_removes_context_from_thread_local_storage(self):
- """After clearing, hasattr reports no context attribute."""
+ """After clearing, get_search_context returns None."""
set_search_context({"id": "will-be-cleared"})
- assert hasattr(_g_thread_data, "context")
+ assert get_search_context() is not None
clear_search_context()
- assert not hasattr(_g_thread_data, "context")
+ assert get_search_context() is None
def test_noop_when_no_context_set(self):
"""Calling clear when there is nothing stored must not raise."""
- assert not hasattr(_g_thread_data, "context")
+ assert get_search_context() is None
clear_search_context() # should not raise
- assert not hasattr(_g_thread_data, "context")
+ assert get_search_context() is None
# ---------------------------------------------------------------------------
@@ -140,8 +138,9 @@ class TestGetSearchContextExtended:
returned["injected"] = True
# The stored context must remain untouched
- assert _g_thread_data.context["research_id"] == "immutable-check"
- assert "injected" not in _g_thread_data.context
+ stored = get_search_context()
+ assert stored["research_id"] == "immutable-check"
+ assert "injected" not in stored
def test_returns_correct_context_values(self):
"""The returned dict contains exactly the same key-value pairs that
@@ -428,8 +427,8 @@ class TestEdgeCasesExtended:
retrieved = get_search_context()
# Top-level key mutation does NOT leak back
retrieved["top_new"] = "added"
- assert "top_new" not in _g_thread_data.context
+ assert "top_new" not in get_search_context()
# Nested mutation DOES leak back (shallow copy)
retrieved["nested"]["inner_key"] = "mutated"
- assert _g_thread_data.context["nested"]["inner_key"] == "mutated"
+ assert get_search_context()["nested"]["inner_key"] == "mutated"
diff --git a/tests/utilities/test_url_thread_coverage.py b/tests/utilities/test_url_thread_coverage.py
index d8c82ee7f7..2ff2c12fbf 100644
--- a/tests/utilities/test_url_thread_coverage.py
+++ b/tests/utilities/test_url_thread_coverage.py
@@ -16,7 +16,6 @@ import pytest
from local_deep_research.utilities.url_utils import normalize_url
from local_deep_research.utilities.thread_context import (
- _g_thread_data,
clear_search_context,
get_search_context,
preserve_research_context,
@@ -266,48 +265,44 @@ class TestSetSearchContext:
"""set_search_context sets context and overwrites previous."""
def setup_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def teardown_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def test_sets_context(self):
set_search_context({"research_id": "abc"})
- assert _g_thread_data.context == {"research_id": "abc"}
+ assert get_search_context() == {"research_id": "abc"}
def test_overwrites_previous(self):
set_search_context({"first": 1})
set_search_context({"second": 2})
- assert _g_thread_data.context == {"second": 2}
+ assert get_search_context() == {"second": 2}
def test_makes_defensive_copy(self):
original = {"key": "value"}
set_search_context(original)
original["key"] = "mutated"
- assert _g_thread_data.context["key"] == "value"
+ assert get_search_context()["key"] == "value"
def test_empty_dict_accepted(self):
set_search_context({})
- assert _g_thread_data.context == {}
+ assert get_search_context() == {}
class TestClearSearchContext:
"""clear_search_context removes the context attribute entirely."""
def setup_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def teardown_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def test_clears_existing(self):
set_search_context({"x": 1})
clear_search_context()
- assert not hasattr(_g_thread_data, "context")
+ assert get_search_context() is None
def test_noop_when_nothing_set(self):
clear_search_context() # must not raise
@@ -323,12 +318,10 @@ class TestGetSearchContext:
"""get_search_context returns a copy, or None when unset."""
def setup_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def teardown_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def test_returns_none_when_not_set(self):
assert get_search_context() is None
@@ -337,7 +330,7 @@ class TestGetSearchContext:
set_search_context({"key": "value"})
result = get_search_context()
result["key"] = "mutated"
- assert _g_thread_data.context["key"] == "value"
+ assert get_search_context()["key"] == "value"
def test_two_gets_are_independent_copies(self):
set_search_context({"k": "v"})
@@ -357,12 +350,10 @@ class TestSearchContextManager:
"""search_context context manager sets on entry and clears on exit."""
def setup_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def teardown_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def test_sets_inside_block(self):
with search_context({"research_id": "cm"}):
@@ -398,15 +389,13 @@ class TestPreserveResearchContext:
"""preserve_research_context decorator captures and restores context."""
def setup_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
sys.modules.pop(
"local_deep_research.database.thread_local_session", None
)
def teardown_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
sys.modules.pop(
"local_deep_research.database.thread_local_session", None
)
@@ -596,12 +585,10 @@ class TestThreadIsolation:
"""Context is truly thread-local: other threads cannot see it."""
def setup_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def teardown_method(self):
- if hasattr(_g_thread_data, "context"):
- del _g_thread_data.context
+ clear_search_context()
def test_other_thread_sees_none(self):
set_search_context({"main": True})