Skip to content

: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.

fix(data-warehouse): load one source module per registry lookup (#93259)

Jovan Sakovic8b3005e6bc01
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/__init__.py
index 2aef428efd3d..69d5f73ea090 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/__init__.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/__init__.py
@@ -1,3 +1,4 @@
+import functools
import importlib
from pathlib import Path
from typing import Any
@@ -6,9 +7,11 @@ import structlog
from posthog.exceptions_capture import capture_exception
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
from .common.registry import SourceRegistry
-__all__ = ["SourceRegistry", "load_all_sources"]
+__all__ = ["SourceRegistry", "load_all_sources", "load_source", "source_module_path"]
logger = structlog.get_logger(__name__)
@@ -40,6 +43,32 @@ def _bulk_load() -> None:
from . import _load_all # noqa: F401, PLC0415
+def source_module_path(source_type: ExternalDataSourceType) -> str | None:
+ """The source module that registers ``source_type``, or None when no directory matches.
+
+ A source directory is the enum member's name in lowercase with underscores added
+ (``BINGADS`` -> ``bing_ads``), so the lookup strips underscores from the directory names.
+ A test asserts every registered source resolves this way.
+ """
+ return _source_modules_by_squashed_name().get(source_type.name.lower())
+
+
+def load_source(source_type: ExternalDataSourceType) -> None:
+ """Import only the module that registers ``source_type``.
+
+ Request paths ask the registry for a handful of source types, and importing every
+ source module costs seconds per process, so they import just the modules they need.
+ """
+ module_path = source_module_path(source_type)
+ if module_path is not None:
+ _load_source(module_path)
+
+
+def _source_modules_by_squashed_name() -> dict[str, str]:
+ return {path.rsplit(".", 2)[1].replace("_", ""): path for path in _source_module_paths()}
+
+
def _source_module_paths() -> list[str]:
"""Every source module `_load_all` imports, derived from the directory layout.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/registry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/registry.py
index 771db586b851..00626cf9383a 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
@@ -46,11 +46,34 @@ class SourceRegistry:
return source_class
+ @classmethod
+ def _load_one(cls, source_type: ExternalDataSourceType) -> None:
+ # Importing every source module costs seconds per process, and a request typically
+ # needs a handful of types. Import only the module for this type; `get_source` falls
+ # back to the full load when that leaves the type unregistered.
+ if cls._loaded or source_type in cls._sources:
+ return
+ from products.warehouse_sources.backend.temporal.data_imports.sources import load_source # noqa: PLC0415
+
+ load_source(source_type)
+
@classmethod
def get_source(cls, source_type: ExternalDataSourceType) -> "AnySource":
"""Get a source instance by type"""
- cls._ensure_loaded()
+ # Callers may hand us the raw string value (e.g. an `oauth_accounts` query param). The
+ # str-mixin enum compares equal to its value, so the `in cls._sources` checks below still
+ # work, but the lazy single-module load reads `source_type.name`, which a plain str lacks.
+ # Coerce to a real enum member first so both the lazy and full-load paths resolve, and so
+ # an unknown value surfaces as ValueError rather than AttributeError.
+ try:
+ source_type = ExternalDataSourceType(source_type)
+ except ValueError:
+ raise ValueError(f"Unknown source type: {source_type}")
+
+ cls._load_one(source_type)
+ if source_type not in cls._sources:
+ cls._ensure_loaded()
if source_type not in cls._sources:
raise ValueError(f"Unknown source type: {source_type}")
return cls._sources[source_type]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_all_sources_import.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_all_sources_import.py
index 2e9b1b25af7e..009d94b2ecf3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_all_sources_import.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_all_sources_import.py
@@ -1,7 +1,14 @@
-from products.warehouse_sources.backend.temporal.data_imports.sources import load_all_sources
+from products.warehouse_sources.backend.temporal.data_imports.sources import load_all_sources, source_module_path
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
def test_load_all_sources_imports_every_source_module():
# A stale import in any single source module breaks the whole registry load — every
# source self-registers on import, so one bad path takes down imports for all sources.
load_all_sources()
+
+ # `SourceRegistry.get_source` imports one module per type, derived from the directory
+ # name. A source registered from a differently named directory would silently fall back
+ # to the full load on every request.
+ for source_type, source in SourceRegistry.get_all_sources().items():
+ assert type(source).__module__ == source_module_path(source_type)
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.py
index 8e359c97c725..58924505d857 100644
--- 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.py
@@ -1,9 +1,16 @@
import ast
from pathlib import Path
+from typing import cast
+import pytest
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 import (
+ _source_module_paths,
+ load_all_sources,
+ source_module_path,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import AnySource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -35,3 +42,75 @@ def test_per_source_fallback_covers_every_source_the_bulk_import_loads():
for node in ast.walk(bulk_import_list)
if isinstance(node, ast.ImportFrom) and node.module
}
+
+
+class _FakePypiSource:
+ @property
+ def source_type(self) -> ExternalDataSourceType:
+ return ExternalDataSourceType.PYPI
+
+
+def _register_fake_pypi_source(*_args) -> None:
+ SourceRegistry.register(cast(type[AnySource], _FakePypiSource))
+
+
+def empty_registry():
+ saved_sources, saved_loaded = dict(SourceRegistry._sources), SourceRegistry._loaded
+ SourceRegistry._sources.clear()
+ SourceRegistry._loaded = False
+ try:
+ yield
+ finally:
+ SourceRegistry._sources.clear()
+ SourceRegistry._sources.update(saved_sources)
+ SourceRegistry._loaded = saved_loaded
+
+
+def test_get_source_imports_only_the_requested_source(empty_registry):
+ with (
+ patch(f"{_SOURCES}.load_source", side_effect=_register_fake_pypi_source) as load_source,
+ patch(f"{_SOURCES}.load_all_sources", side_effect=AssertionError("the full catalog load must not run")),
+ ):
+ source = SourceRegistry.get_source(ExternalDataSourceType.PYPI)
+
+ assert isinstance(source, _FakePypiSource)
+ load_source.assert_called_once_with(ExternalDataSourceType.PYPI)
+ assert SourceRegistry._loaded is False
+
+
+def test_get_source_falls_back_to_the_full_load_when_the_single_import_registers_nothing(empty_registry):
+ with (
+ patch(f"{_SOURCES}.load_source"),
+ patch(f"{_SOURCES}.load_all_sources", side_effect=_register_fake_pypi_source),
+ ):
+ source = SourceRegistry.get_source(ExternalDataSourceType.PYPI)
+
+ assert isinstance(source, _FakePypiSource)
+ assert SourceRegistry._loaded is True
+
+
+def test_get_source_resolves_a_raw_string_value_through_the_lazy_path(empty_registry):
+ # Reproduces the cold-worker `oauth_accounts` call: a raw query-param string reaches
+ # `get_source`, whose lazy load reads `source_type.name`. `_load_source` is stubbed so the
+ # real `source_module_path` runs without importing a vendor module.
+ with (
+ patch(f"{_SOURCES}._load_source", side_effect=_register_fake_pypi_source),
+ patch(f"{_SOURCES}.load_all_sources", side_effect=AssertionError("the full catalog load must not run")),
+ ):
+ source = SourceRegistry.get_source(cast(ExternalDataSourceType, ExternalDataSourceType.PYPI.value))
+
+ assert isinstance(source, _FakePypiSource)
+
+
+def test_get_source_raises_valueerror_for_an_unknown_string_value(empty_registry):
+ # The endpoint turns ValueError into a 400. An unknown string must not read `.name` off a str.
+ with patch(f"{_SOURCES}.load_all_sources", side_effect=AssertionError("the full catalog load must not run")):
+ with pytest.raises(ValueError):
+ SourceRegistry.get_source(cast(ExternalDataSourceType, "NotARealSource"))
+
+
+def test_source_module_path_resolves_every_source_type_without_importing_it():
+ module_paths = set(_source_module_paths())
+
+ assert {source_module_path(source_type) for source_type in ExternalDataSourceType} <= module_paths