~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: restore egress context after raw worker calls (#7166)
LearningCircuit6c3175a38a64
diff --git a/changelog.d/+research-worker-test-context.misc.md b/changelog.d/+research-worker-test-context.misc.mdnew file mode 100644index 0000000000..8149961653--- /dev/null+++ b/changelog.d/+research-worker-test-context.misc.md@@ -0,0 +1 @@+Restore the caller's egress context after raw research-worker test helpers, preventing mocked runs from contaminating later policy checks.diff --git a/tests/web/services/helpers.py b/tests/web/services/helpers.pyindex 0d8bab1ca9..f69e2721f4 100644--- a/tests/web/services/helpers.py+++ b/tests/web/services/helpers.py@@ -9,6 +9,7 @@ longer disappear when a test module is retired."""from contextlib import contextmanager, ExitStack+from functools import wrapsfrom unittest.mock import MagicMock, create_autospec, patchfrom local_deep_research.web.services import research_service@@ -45,13 +46,36 @@ def _make_mock_research(status=None, research_meta=None):def _get_raw_run_research_process():- """Get the unwrapped (no decorators) run_research_process function."""+ """Run the unwrapped worker while restoring the caller's egress context.++ These tests intentionally skip thread_cleanup, which normally clears+ the worker's active context. Preserve any enclosing context and prevent+ a mocked run from contaminating policy checks later in the same process.+ """+ from local_deep_research.security.egress.audit_hook import (+ clear_active_context,+ get_active_context,+ set_active_context,+ )from local_deep_research.web.services.research_service import (run_research_process,)# @log_for_research and @thread_cleanup, outermost first.- return run_research_process.__wrapped__.__wrapped__+ raw_worker = run_research_process.__wrapped__.__wrapped__++ @wraps(raw_worker)+ def isolated_worker(*args, **kwargs):+ previous = get_active_context()+ try:+ return raw_worker(*args, **kwargs)+ finally:+ if previous is None:+ clear_active_context()+ else:+ set_active_context(previous)++ return isolated_workerdef _base_run_patches(mock_session=None):diff --git a/tests/web/services/test_research_service_coverage_main_port.py b/tests/web/services/test_research_service_coverage_main_port.pyindex e40528c1b7..9deaf22b43 100644--- a/tests/web/services/test_research_service_coverage_main_port.py+++ b/tests/web/services/test_research_service_coverage_main_port.py@@ -61,13 +61,12 @@ def _fake_session_ctx(session):def _get_raw_run_research_process():- """The unwrapped (no decorators) run_research_process function."""- from local_deep_research.web.services.research_service import (- run_research_process,+ """Use the shared raw-worker wrapper that restores egress context."""+ from tests.web.services.helpers import (+ _get_raw_run_research_process as get_isolated_raw_worker,)- # @log_for_research and @thread_cleanup, outermost first.- return run_research_process.__wrapped__.__wrapped__+ return get_isolated_raw_worker()def _make_research_mock(diff --git a/tests/web/services/test_research_worker_harness_context.py b/tests/web/services/test_research_worker_harness_context.pynew file mode 100644index 0000000000..5bc054c7c6--- /dev/null+++ b/tests/web/services/test_research_worker_harness_context.py@@ -0,0 +1,144 @@+"""Raw worker test helpers must restore the caller's egress context."""++from unittest.mock import patch++import pytest++from local_deep_research.security.egress.audit_hook import (+ clear_active_context,+ get_active_context,+ set_active_context,+)+from local_deep_research.security.egress.policy import (+ EgressContext,+ EgressScope,+ evaluate_url,+)+from tests.web.services import helpers+++def _private_context():+ return EgressContext(+ scope=EgressScope.PRIVATE_ONLY,+ primary_engine="library",+ require_local_llm=False,+ require_local_embeddings=False,+ )++[email protected]("harness", ["analyze-result", "search-error"])[email protected]("has_outer_context", [False, True])[email protected]("worker_raises", [False, True])+def test_worker_harness_restores_context(+ harness, has_outer_context, worker_raises+):+ previous = get_active_context()+ expected = _private_context() if has_outer_context else None+ if expected is None:+ clear_active_context()+ else:+ set_active_context(expected)++ def call_harness():+ if harness == "analyze-result":+ return helpers.run_quick_mode_with_analyze_result(+ {+ "findings": [],+ "formatted_findings": "Public answer",+ "iterations": 1,+ }+ )+ return helpers.run_quick_mode_with_search_error("Synthetic timeout")++ try:+ if worker_raises:++ class WorkerInterrupted(BaseException):+ pass++ def interrupted_activation(*args, **kwargs):+ set_active_context(_private_context())+ raise WorkerInterrupted("Synthetic worker interruption")++ with (+ patch(+ "local_deep_research.security.set_active_context",+ side_effect=interrupted_activation,+ ),+ pytest.raises(+ WorkerInterrupted, match="Synthetic worker interruption"+ ),+ ):+ call_harness()+ else:+ result = call_harness()+ if harness == "analyze-result":+ assert result == {"clean_markdown": "Public answer"}+ else:+ assert isinstance(result, str) and result++ assert get_active_context() is expected+ context = expected or _private_context()+ assert evaluate_url("http://127.0.0.1/v1", context).allowed+ decision = evaluate_url("http://169.254.169.254/latest", context)+ assert not decision.allowed+ assert decision.reason == "blocked_metadata_ip"+ finally:+ if previous is None:+ clear_active_context()+ else:+ set_active_context(previous)++[email protected]("has_outer_context", [False, True])[email protected]("worker_raises", [False, True])+def test_coverage_port_raw_worker_restores_context(+ has_outer_context, worker_raises+):+ """The coverage-port module has its own raw-worker entry point."""+ from local_deep_research.web.services import research_service+ from tests.web.services.test_research_service_coverage_main_port import (+ _get_raw_run_research_process,+ )++ class WorkerInterrupted(BaseException):+ pass++ def raw_worker():+ set_active_context(_private_context())+ if worker_raises:+ raise WorkerInterrupted()+ return "finished"++ def inner_wrapper():+ raise AssertionError("decorators should be skipped")++ def outer_wrapper():+ raise AssertionError("decorators should be skipped")++ inner_wrapper.__wrapped__ = raw_worker+ outer_wrapper.__wrapped__ = inner_wrapper++ previous = get_active_context()+ expected = _private_context() if has_outer_context else None+ if expected is None:+ clear_active_context()+ else:+ set_active_context(expected)++ try:+ with patch.object(+ research_service, "run_research_process", outer_wrapper+ ):+ isolated_worker = _get_raw_run_research_process()+ if worker_raises:+ with pytest.raises(WorkerInterrupted):+ isolated_worker()+ else:+ assert isolated_worker() == "finished"+ assert get_active_context() is expected+ finally:+ if previous is None:+ clear_active_context()+ else:+ set_active_context(previous)