diff --git a/sentry_sdk/integrations/__init__.py b/sentry_sdk/integrations/__init__.py index 84d1ca49b2..60071fdd24 100644 --- a/sentry_sdk/integrations/__init__.py +++ b/sentry_sdk/integrations/__init__.py @@ -45,11 +45,22 @@ def __call__( # Set of all integration identifiers we have actually installed _installed_integrations: "Set[str]" = set() -# Trigger module -> import string of the deferred integration waiting for the -# application to import the trigger module -_pending_deferred_integrations: "Dict[str, str]" = {} +# Import strings of the deferred integrations waiting for the application to +# import one of their trigger modules +_pending_deferred_integrations: "Set[str]" = set() -_deferred_setup_finder_guard = local() + +class _DeferredSetupState(local): + def __init__(self) -> None: + # Guards the finder against recursion + self.finding = False + # Trigger imports and setups in progress + self.import_depth = 0 + # Set up once the outermost trigger import completes + self.completed_triggers: "List[str]" = [] + + +_deferred_setup_state = _DeferredSetupState() def _generate_default_integrations_iterator( @@ -141,15 +152,45 @@ def iter_default_integrations( ] # With the `deferred_auto_enabling_integrations` experiment on, these auto-enabling -# integrations are only set up once the application imports the trigger module. +# integrations are only set up once the application imports one of their trigger +# modules, and the outermost trigger import in progress completes. The first trigger +# decides whether the library is installed. When an integration imports from several +# packages, each of them is a trigger, so none is half-initialised when the setup runs. # This can't live on the integration class, since loading the class imports the library. _DEFERRED_INTEGRATION_TRIGGERS = { - "sentry_sdk.integrations.anthropic.AnthropicIntegration": "anthropic", - "sentry_sdk.integrations.google_genai.GoogleGenAIIntegration": "google.genai", - "sentry_sdk.integrations.huggingface_hub.HuggingfaceHubIntegration": "huggingface_hub.inference._client", - "sentry_sdk.integrations.openai.OpenAIIntegration": "openai", - "sentry_sdk.integrations.openai_agents.OpenAIAgentsIntegration": "agents", - "sentry_sdk.integrations.pydantic_ai.PydanticAIIntegration": "pydantic_ai", + "sentry_sdk.integrations.anthropic.AnthropicIntegration": ("anthropic",), + "sentry_sdk.integrations.google_genai.GoogleGenAIIntegration": ("google.genai",), + "sentry_sdk.integrations.huggingface_hub.HuggingfaceHubIntegration": ( + "huggingface_hub.inference._client", + ), + "sentry_sdk.integrations.langchain.LangchainIntegration": ( + "langchain_core", + "langchain", + "langchain_classic", + "langchain_openai", + "langchain_google_vertexai", + "langchain_aws", + "langchain_cohere", + "langchain_mistralai", + "langchain_huggingface", + "langchain_ollama", + ), + # `langgraph` is a namespace package, so it can't be a trigger + "sentry_sdk.integrations.langgraph.LanggraphIntegration": ( + "langgraph.graph", + "langgraph.func", + "langgraph.pregel", + ), + "sentry_sdk.integrations.mcp.MCPIntegration": ("mcp", "fastmcp"), + "sentry_sdk.integrations.openai.OpenAIIntegration": ("openai",), + "sentry_sdk.integrations.openai_agents.OpenAIAgentsIntegration": ("agents",), + "sentry_sdk.integrations.pydantic_ai.PydanticAIIntegration": ("pydantic_ai",), +} + +_DEFERRED_INTEGRATION_BY_TRIGGER = { + trigger: import_string + for import_string, triggers in _DEFERRED_INTEGRATION_TRIGGERS.items() + for trigger in triggers } iter_default_integrations = _generate_default_integrations_iterator( @@ -264,9 +305,10 @@ def setup_integrations( and options is not None and options["_experiments"].get("deferred_auto_enabling_integrations") ): - for import_string, trigger in _DEFERRED_INTEGRATION_TRIGGERS.items(): - if trigger in sys.modules: + for import_string, triggers in _DEFERRED_INTEGRATION_TRIGGERS.items(): + if any(trigger in sys.modules for trigger in triggers): continue + trigger = triggers[0] try: spec = importlib.util.find_spec(trigger) except Exception: @@ -355,19 +397,18 @@ def setup_integrations( ): continue - trigger = _DEFERRED_INTEGRATION_TRIGGERS[import_string] with _installer_lock: if identifier in _processed_integrations: continue _processed_integrations.add(identifier) - _pending_deferred_integrations[trigger] = import_string + _pending_deferred_integrations.add(import_string) if _deferred_setup_finder not in sys.meta_path: sys.meta_path.insert(0, _deferred_setup_finder) logger.debug( - "Deferring setup of integration %s until %s is imported", + "Deferring setup of integration %s until one of %s is imported", identifier, - trigger, + ", ".join(_DEFERRED_INTEGRATION_TRIGGERS[import_string]), ) integrations = { @@ -383,8 +424,10 @@ def setup_integrations( def _set_up_deferred_integration(trigger: str) -> None: - import_string = _pending_deferred_integrations.pop(trigger, None) - if import_string is None: + import_string = _DEFERRED_INTEGRATION_BY_TRIGGER[trigger] + try: + _pending_deferred_integrations.remove(import_string) + except KeyError: return with capture_internal_exceptions(): @@ -412,21 +455,39 @@ def create_module(self, spec: "ModuleSpec") -> "Optional[ModuleType]": return self._loader.create_module(spec) def exec_module(self, module: "ModuleType") -> None: - self._loader.exec_module(module) - module.__loader__ = self._loader - if module.__spec__ is not None: - module.__spec__.loader = self._loader - - # Setup may access the trigger as an attribute of its parent package - # before the import system binds it there - with capture_internal_exceptions(): - parent, _, child = self._trigger.rpartition(".") - if parent: - setattr( - sys.modules[parent], child, sys.modules.get(self._trigger, module) - ) + state = _deferred_setup_state + state.import_depth += 1 + try: + self._loader.exec_module(module) + module.__loader__ = self._loader + if module.__spec__ is not None: + module.__spec__.loader = self._loader + + # Setup may access the trigger as an attribute of its parent package + # before the import system binds it there + with capture_internal_exceptions(): + parent, _, child = self._trigger.rpartition(".") + if parent: + setattr( + sys.modules[parent], + child, + sys.modules.get(self._trigger, module), + ) - _set_up_deferred_integration(self._trigger) + state.completed_triggers.append(self._trigger) + finally: + state.import_depth -= 1 + + if state.import_depth > 0: + return + + # Trigger imports during a setup are queued rather than set up halfway through it + state.import_depth += 1 + try: + while state.completed_triggers: + _set_up_deferred_integration(state.completed_triggers.pop(0)) + finally: + state.import_depth -= 1 def __getattr__(self, name: str) -> "Any": return getattr(self._loader, name) @@ -439,12 +500,15 @@ def find_spec( path: "Optional[Sequence[str]]" = None, target: "Optional[ModuleType]" = None, ) -> "Optional[ModuleSpec]": - if fullname not in _pending_deferred_integrations or getattr( - _deferred_setup_finder_guard, "active", False + state = _deferred_setup_state + if ( + _DEFERRED_INTEGRATION_BY_TRIGGER.get(fullname) + not in _pending_deferred_integrations + or state.finding ): return None - _deferred_setup_finder_guard.active = True + state.finding = True try: for finder in sys.meta_path: if finder is self or not hasattr(finder, "find_spec"): @@ -455,12 +519,14 @@ def find_spec( else: return None finally: - _deferred_setup_finder_guard.active = False + state.finding = False if hasattr(spec.loader, "exec_module"): spec.loader = _DeferredSetupLoader(spec.loader, fullname) else: - _pending_deferred_integrations.pop(fullname, None) + _pending_deferred_integrations.discard( + _DEFERRED_INTEGRATION_BY_TRIGGER[fullname] + ) logger.debug( "Not setting up deferred integration for %s: its loader has no exec_module", fullname, diff --git a/sentry_sdk/integrations/langgraph.py b/sentry_sdk/integrations/langgraph.py index af287b0fd4..29a8dbda20 100644 --- a/sentry_sdk/integrations/langgraph.py +++ b/sentry_sdk/integrations/langgraph.py @@ -10,9 +10,6 @@ ) from sentry_sdk.consts import OP, SPANDATA from sentry_sdk.integrations import DidNotEnable, Integration - -# This is fine because langgraph depends on langchain-base, and LangchainIntegration only imports from langchain-base. -from sentry_sdk.integrations.langchain import LangchainIntegration from sentry_sdk.scope import should_send_default_pii from sentry_sdk.traces import StreamedSpan from sentry_sdk.tracing_utils import ( @@ -28,6 +25,10 @@ except ImportError: raise DidNotEnable("langgraph not installed") +# Imported after the langgraph check, so langchain_core is only loaded when langgraph +# is installed. langgraph depends on langchain-core, which is all LangchainIntegration needs. +from sentry_sdk.integrations.langchain import LangchainIntegration + class LanggraphIntegration(Integration): identifier = "langgraph" diff --git a/tests/integrations/fastmcp/test_fastmcp.py b/tests/integrations/fastmcp/test_fastmcp.py index e0211bb22d..09d570cd4d 100644 --- a/tests/integrations/fastmcp/test_fastmcp.py +++ b/tests/integrations/fastmcp/test_fastmcp.py @@ -41,6 +41,7 @@ async def __call__(self, *args, **kwargs): from sentry_sdk import start_transaction from sentry_sdk.consts import OP, SPANDATA from sentry_sdk.integrations.mcp import MCPIntegration +from tests.integrations.utils import run_deferred_setup_app try: from fastmcp.prompts import Message @@ -1473,3 +1474,24 @@ async def async_multiply(x: int, y: int) -> int: assert len(mcp_spans) == 2 assert mcp_spans[0]["data"][SPANDATA.MCP_TOOL_NAME] == "sync_add" assert mcp_spans[1]["data"][SPANDATA.MCP_TOOL_NAME] == "async_multiply" + + +@pytest.mark.parametrize("method", ["_get_prompt_mcp", "_read_resource_mcp"]) +def test_deferred_setup_on_import(tmp_path, method): + if not hasattr(StandaloneFastMCP, method): + pytest.skip(f"Requires standalone fastmcp with FastMCP.{method}") + + result = run_deferred_setup_app( + tmp_path, + identifier="mcp", + trigger="mcp", + app_imports="from fastmcp import FastMCP", + patched=f"FastMCP.{method}", + ) + + assert result == { + "imported_during_init": False, + "integration_enabled": True, + "patched": True, + "reported_in_event": True, + } diff --git a/tests/integrations/langchain/test_langchain.py b/tests/integrations/langchain/test_langchain.py index 150889973e..f7838eb5e2 100644 --- a/tests/integrations/langchain/test_langchain.py +++ b/tests/integrations/langchain/test_langchain.py @@ -1,4 +1,5 @@ import json +from textwrap import dedent from typing import Any, Iterator, List, Optional from unittest import mock from unittest.mock import Mock, patch @@ -7358,3 +7359,68 @@ def test_deferred_setup_skips_deactivated_integration(tmp_path): "patched": False, "reported_in_event": False, } + + +@pytest.mark.parametrize( + "app_imports, patched", + [ + pytest.param( + "from langchain_openai import OpenAIEmbeddings", + "OpenAIEmbeddings.embed_documents", + id="langchain_openai_first", + ), + pytest.param( + "from langchain_classic.agents import AgentExecutor", + "AgentExecutor.invoke", + id="langchain_classic_agents_first", + marks=pytest.mark.skipif( + package_version("langchain-classic") is None, + reason="Requires langchain-classic", + ), + ), + ], +) +def test_deferred_setup_on_import(tmp_path, app_imports, patched): + result = run_deferred_setup_app( + tmp_path, + identifier="langchain", + trigger="langchain_core", + app_imports=app_imports, + patched=patched, + ) + + assert result == { + "imported_during_init": False, + "integration_enabled": True, + "patched": True, + "reported_in_event": True, + } + + +def test_deferred_setup_of_langgraph_imported_by_langchain_agents(tmp_path): + pytest.importorskip("langchain.agents.factory") + + result = run_deferred_setup_app( + tmp_path, + identifier="langgraph", + trigger="langchain_core", + app_imports="import langchain.agents\nfrom langgraph.pregel import Pregel", + patched="Pregel.invoke", + before_init=dedent( + """ + class HideLangchainClassic: + def find_spec(self, fullname, path=None, target=None): + if fullname == "langchain_classic": + raise ImportError(fullname) + + sys.meta_path.insert(0, HideLangchainClassic()) + """ + ), + ) + + assert result == { + "imported_during_init": False, + "integration_enabled": True, + "patched": True, + "reported_in_event": True, + } diff --git a/tests/integrations/langgraph/test_langgraph.py b/tests/integrations/langgraph/test_langgraph.py index 9b92149aca..cd40d89054 100644 --- a/tests/integrations/langgraph/test_langgraph.py +++ b/tests/integrations/langgraph/test_langgraph.py @@ -12,6 +12,7 @@ import sentry_sdk from sentry_sdk import start_transaction from sentry_sdk.consts import OP, SPANDATA +from tests.integrations.utils import run_deferred_setup_app def mock_langgraph_imports(): @@ -2655,3 +2656,35 @@ def original_compile(self, *args, **kwargs): assert SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS not in data assert data[SPANDATA.GEN_AI_AGENT_NAME] == "test_graph" + + +@pytest.mark.parametrize( + "app_imports, patched", + [ + pytest.param( + "from langgraph.graph import StateGraph", + "StateGraph.compile", + id="langgraph_graph", + ), + pytest.param( + "from langgraph.func import entrypoint\nfrom langgraph.pregel import Pregel", + "Pregel.invoke", + id="langgraph_func_only", + ), + ], +) +def test_deferred_setup_on_import(tmp_path, app_imports, patched): + result = run_deferred_setup_app( + tmp_path, + identifier="langgraph", + trigger="langchain_core", + app_imports=app_imports, + patched=patched, + ) + + assert result == { + "imported_during_init": False, + "integration_enabled": True, + "patched": True, + "reported_in_event": True, + } diff --git a/tests/integrations/mcp/test_mcp.py b/tests/integrations/mcp/test_mcp.py index ef6c04bbdb..54fe249f1a 100644 --- a/tests/integrations/mcp/test_mcp.py +++ b/tests/integrations/mcp/test_mcp.py @@ -76,6 +76,7 @@ async def __call__(self, *args, **kwargs): from sentry_sdk import start_transaction from sentry_sdk.consts import OP, SPANDATA from sentry_sdk.integrations.mcp import MCPIntegration +from tests.integrations.utils import run_deferred_setup_app def _get_response(session_message): @@ -2611,3 +2612,20 @@ async def test_tool(tool_name, arguments): assert data[SPANDATA.MCP_TOOL_RESULT_CONTENT] == json.dumps({"value": 42}) assert data[SPANDATA.MCP_TOOL_RESULT_CONTENT_COUNT] == 1 + + +def test_deferred_setup_on_import(tmp_path): + result = run_deferred_setup_app( + tmp_path, + identifier="mcp", + trigger="mcp", + app_imports="from mcp.server.streamable_http import StreamableHTTPServerTransport", + patched="StreamableHTTPServerTransport.handle_request", + ) + + assert result == { + "imported_during_init": False, + "integration_enabled": True, + "patched": True, + "reported_in_event": True, + }