:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(warehouse-sources): isolate source module imports so one broken source can't take down the rest (#75766)
Daniel RCe99de5756f5b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/__init__.pyindex 0d257b64fb52..2aef428efd3d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/__init__.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/__init__.py@@ -1,9 +1,17 @@+import importlib+from pathlib import Pathfrom typing import Any+import structlog++from posthog.exceptions_capture import capture_exception+from .common.registry import SourceRegistry__all__ = ["SourceRegistry", "load_all_sources"]+logger = structlog.get_logger(__name__)+def load_all_sources() -> None:"""Import every source module so each registers itself with ``SourceRegistry``.@@ -12,16 +20,51 @@ def load_all_sources() -> None:doesn't drag every vendor SDK at app startup. Importing ``_load_all`` runs eachsource module's ``@SourceRegistry.register`` decorator. Idempotent — re-imports arecheap dict lookups in ``sys.modules``.++ Best-effort: a source module that can't be imported is reported and skipped, leaving the+ rest of the catalog usable."""+ try:+ _bulk_load()+ except Exception:+ # `_load_all` is one flat import list, so a single unimportable source module aborts it+ # and leaves every later source unregistered — failing every sync and the whole sources+ # UI rather than just the offending source. Import the rest individually so one broken+ # vendor module costs only its own source.+ logger.exception("load_all_sources: bulk import failed, falling back to per-source import")+ for module_path in _source_module_paths():+ _load_source(module_path)+++def _bulk_load() -> None:from . import _load_all # noqa: F401, PLC0415+def _source_module_paths() -> list[str]:+ """Every source module `_load_all` imports, derived from the directory layout.++ A test asserts this stays in step with `_load_all`'s import list.+ """+ package_dir = Path(__path__[0])+ return sorted(f"{__name__}.{source.parent.name}.source" for source in package_dir.glob("*/source.py"))+++def _load_source(module_path: str) -> None:+ try:+ importlib.import_module(module_path)+ except Exception as e:+ logger.exception("load_all_sources: source module failed to import", module=module_path)+ capture_exception(e)++def __getattr__(name: str) -> Any:# Back-compat: source classes used to be re-exported here. Resolve them lazily so# `from ...sources import StripeSource` keeps working without eager-loading every SDK.# Guard private/dunder names (including `_load_all` itself) to avoid recursing through- # the very import we use to populate the namespace.- if name.startswith("_"):+ # the very import we use to populate the namespace. Every re-exported class is a+ # `*Source`, so anything else is an attribute probe (pytest looking for `pytest_plugins`,+ # a `hasattr` check) that must not drag in 1200-odd vendor modules to answer.+ if name.startswith("_") or not name.endswith("Source"):raise AttributeError(f"module {__name__!r} has no attribute {name!r}")from . import _load_all # noqa: PLC0415diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/registry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/registry.pyindex 7b315b6ca395..771db586b851 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/registry.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/registry.py@@ -20,8 +20,10 @@ class SourceRegistry:# on first registry use rather than at package import, so a process that never# touches the registry (most of them) doesn't pay for every vendor SDK at startup.# Double-checked lock: concurrent first-callers in a web worker must not observe a- # half-populated registry, and `_loaded` flips only after the import succeeds — so a- # failed load (e.g. a broken optional dependency) is retried rather than cached.+ # half-populated registry, and `_loaded` flips only after the load returns — so a load+ # that raises outright is retried rather than cached. A single source module that can't+ # be imported is skipped by `load_all_sources`, leaving it absent here (and reported as+ # an unknown type by `get_source`) rather than taking every other source down with it.if cls._loaded:returnwith cls._load_lock:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_loading.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_loading.pynew file mode 100644index 000000000000..8e359c97c725--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_loading.py@@ -0,0 +1,37 @@+import ast+from pathlib import Path++from unittest.mock import patch++from products.warehouse_sources.backend.temporal.data_imports.sources import _source_module_paths, load_all_sources+from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCES = "products.warehouse_sources.backend.temporal.data_imports.sources"+++def test_broken_source_module_does_not_block_the_rest_of_the_catalog():+ with (+ patch(f"{_SOURCES}._bulk_load", side_effect=ModuleNotFoundError("No module named 'gone'")),+ patch(+ f"{_SOURCES}._source_module_paths",+ return_value=[f"{_SOURCES}.gone.source", f"{_SOURCES}.pypi.source"],+ ),+ patch(f"{_SOURCES}.capture_exception") as capture_exception,+ ):+ load_all_sources()++ # Reads `_sources` rather than `get_all_sources()` so the assertion can't be satisfied by+ # the real full load that `_ensure_loaded` would kick off.+ assert ExternalDataSourceType.PYPI in SourceRegistry._sources+ capture_exception.assert_called_once()+++def test_per_source_fallback_covers_every_source_the_bulk_import_loads():+ bulk_import_list = ast.parse((Path(__file__).parent.parent / "_load_all.py").read_text())++ assert set(_source_module_paths()) == {+ f"{_SOURCES}.{node.module}"+ for node in ast.walk(bulk_import_list)+ if isinstance(node, ast.ImportFrom) and node.module+ }