: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
chore(devex): cut heavy SDK imports off Django startup path (#60635)
Julian Bezc7fcc60c05e8
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex abb4e071df37..11e57663af7a 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -10,9 +10,7 @@ from django.http import HttpResponsefrom django.shortcuts import redirectfrom django.utils import timezone-import stripeimport structlog-from anthropic import APIConnectionError, APIStatusError, AuthenticationError, PermissionDeniedErrorfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema, extend_schema_serializerfrom rest_framework import mixins, serializers, viewsets@@ -105,6 +103,9 @@ def _verify_stripe_install_signature(state: str, user_id: str, account_id: str,"""if not install_signature or not settings.STRIPE_SIGNING_SECRET:return False++ import stripe # noqa: PLC0415+payload = json.dumps({"state": state, "user_id": user_id, "account_id": account_id},separators=(",", ":"),@@ -933,6 +934,13 @@ class IntegrationViewSet(return self._anthropic_managed_list_response(request, resource="vaults")def _anthropic_managed_list_response(self, request: Request, *, resource: str) -> Response:+ from anthropic import ( # noqa: PLC0415+ APIConnectionError,+ APIStatusError,+ AuthenticationError,+ PermissionDeniedError,+ )+instance = self._get_anthropic_integration_or_400()try:diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex e0c5bb4a7b63..ea01ff01ba98 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -2057,7 +2057,7 @@ class TestStripeIntegrationOAuthTokens:assert OAuthAccessToken.objects.filter(pk=access_token.pk).exists()assert OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()- @patch("posthog.models.integration.StripeClient")+ @patch("stripe.StripeClient")@patch("posthog.models.integration.settings")def test_write_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id@@ -2086,7 +2086,7 @@ class TestStripeIntegrationOAuthTokens:assert secret_payloads["posthog_project_id"] == str(self.team.pk)assert secret_payloads["posthog_oauth_client_id"] == self.oauth_app.client_id- @patch("posthog.models.integration.StripeClient")+ @patch("stripe.StripeClient")@patch("posthog.models.integration.settings")def test_clear_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"@@ -2118,7 +2118,7 @@ class TestStripeIntegrationOAuthTokens:("write_uses_live_when_flag_missing", "write_posthog_secrets", {}, "sk_live"),])- @patch("posthog.models.integration.StripeClient")+ @patch("stripe.StripeClient")@patch("posthog.models.integration.settings")def test_stripe_client_secret_selection(self, _name, method_name, config, expected_key, mock_settings, MockStripeClient@@ -2145,7 +2145,7 @@ class TestStripeIntegrationOAuthTokens:MockStripeClient.assert_called_once_with(expected_key)@patch("posthog.models.integration.capture_exception")- @patch("posthog.models.integration.StripeClient")+ @patch("stripe.StripeClient")@patch("posthog.models.integration.settings")def test_write_posthog_secrets_skips_when_sandbox_keys_missing(self, mock_settings, MockStripeClient, mock_capture):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id@@ -2172,7 +2172,7 @@ class TestStripeIntegrationOAuthTokens:assert isinstance(captured_exc, NotImplementedError)@patch("posthog.models.integration.capture_exception")- @patch("posthog.models.integration.StripeClient")+ @patch("stripe.StripeClient")@patch("posthog.models.integration.settings")def test_clear_posthog_secrets_skips_and_revokes_tokens_when_sandbox_keys_missing(self, mock_settings, MockStripeClient, mock_capture@@ -2870,7 +2870,7 @@ class TestAnthropicIntegration:mock_client.get.return_value = {"data": []}return mock_client- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_create_with_valid_key(self, mock_anthropic_class, client: HttpClient):self._mock_anthropic_validate_key(mock_anthropic_class)@@ -2900,7 +2900,7 @@ class TestAnthropicIntegration:assert get_call.args[0] == "/v1/agents"assert get_call.kwargs["options"]["headers"]["anthropic-beta"] == "managed-agents-2026-04-01"- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_create_strips_whitespace_from_api_key(self, mock_anthropic_class, client: HttpClient):self._mock_anthropic_validate_key(mock_anthropic_class)@@ -2915,7 +2915,7 @@ class TestAnthropicIntegration:integration = Integration.objects.get(id=response.json()["id"])assert integration.sensitive_config == {"api_key": "sk-ant-test"}- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_create_without_workspace_label_uses_default_id(self, mock_anthropic_class, client: HttpClient):self._mock_anthropic_validate_key(mock_anthropic_class)@@ -2931,7 +2931,7 @@ class TestAnthropicIntegration:assert integration.config == {}assert integration.integration_id == f"workspace-{self.team.pk}"- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_create_rejects_existing_workspace_without_force(self, mock_anthropic_class, client: HttpClient):self._mock_anthropic_validate_key(mock_anthropic_class)@@ -2956,7 +2956,7 @@ class TestAnthropicIntegration:integration = Integration.objects.get(id=first_id)assert integration.sensitive_config == {"api_key": "sk-ant-first"}- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_create_overwrites_with_force_flag(self, mock_anthropic_class, client: HttpClient):self._mock_anthropic_validate_key(mock_anthropic_class)@@ -2995,7 +2995,7 @@ class TestAnthropicIntegration:({"api_key": "sk-ant-test", "workspace_label": 42}, "Workspace label must be a string"),],)- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_create_rejects_invalid_payload(self,mock_anthropic_class,@@ -3024,7 +3024,7 @@ class TestAnthropicIntegration:("APIConnectionError", "Could not reach Anthropic"),],)- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_create_rejects_anthropic_failures(self,mock_anthropic_class,@@ -3067,7 +3067,7 @@ class TestAnthropicIntegration:created_by=self.user,)- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_anthropic_managed_agents_action(self, mock_anthropic_class, client: HttpClient):from django.core.cache import cache@@ -3101,7 +3101,7 @@ class TestAnthropicIntegration:assert path_arg == "/v1/agents"assert headers["anthropic-beta"] == "managed-agents-2026-04-01"- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_anthropic_managed_agents_action_caches_default_page(self, mock_anthropic_class, client: HttpClient):from django.core.cache import cache@@ -3121,7 +3121,7 @@ class TestAnthropicIntegration:# Second hit served from cache → SDK called only once.assert mock_client.get.call_count == 1- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_anthropic_managed_agents_action_translates_auth_error(self, mock_anthropic_class, client: HttpClient):from django.core.cache import cache@@ -3144,7 +3144,7 @@ class TestAnthropicIntegration:integration.refresh_from_db()assert integration.errors == ERROR_TOKEN_REFRESH_FAILED- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_anthropic_managed_agents_action_rejects_wrong_kind(self, mock_anthropic_class, client: HttpClient):slack_integration = Integration.objects.create(team=self.team,@@ -3164,7 +3164,7 @@ class TestAnthropicIntegration:assert "is not an Anthropic integration" in str(response.json())mock_anthropic_class.assert_not_called()- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_anthropic_managed_agent_environments_action(self, mock_anthropic_class, client: HttpClient):from django.core.cache import cache@@ -3185,7 +3185,7 @@ class TestAnthropicIntegration:assert body["next_cursor"] == "abc"assert body["has_more"] is True- @patch("posthog.models.integration.Anthropic")+ @patch("anthropic.Anthropic")def test_anthropic_managed_agent_vaults_action(self, mock_anthropic_class, client: HttpClient):from django.core.cache import cachediff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 36492034f4b1..f137e0f8f30d 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -14,6 +14,8 @@ from products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDSif TYPE_CHECKING:import aiohttp+ from anthropic import Anthropic+ from stripe import StripeClientfrom django.conf import settingsfrom django.db import models, transaction@@ -22,7 +24,6 @@ from django.utils import timezoneimport requestsimport structlog-from anthropic import Anthropic, APIConnectionError, APIStatusError, AuthenticationError, PermissionDeniedErrorfrom disposable_email_domains import blocklist as disposable_email_domains_listfrom free_email_domains import whitelist as free_email_domains_listfrom google.auth.transport.requests import Request as GoogleRequest@@ -35,7 +36,6 @@ from rest_framework.request import Requestfrom slack_sdk import WebClientfrom slack_sdk.errors import SlackApiErrorfrom slack_sdk.web.async_client import AsyncWebClient-from stripe import StripeClientfrom posthog.cache_utils import cache_forfrom posthog.exceptions_capture import capture_exception@@ -919,6 +919,8 @@ class OauthIntegration:# Stripe OAuth returns stripe_user_id but no account name — fetch it from the Accounts APIif kind == "stripe" and integration_id:try:+ from stripe import StripeClient # noqa: PLC0415+stripe_client = StripeClient(oauth_config.client_secret)account = stripe_client.accounts.retrieve(str(integration_id))business_profile = getattr(account, "business_profile", None)@@ -2970,15 +2972,17 @@ class AnthropicIntegrationError(Exception):"""Raised when the AnthropicIntegration is constructed with an invalid Integration row."""-def _build_anthropic_client(api_key: str) -> Anthropic:+def _build_anthropic_client(api_key: str) -> "Anthropic":# Tight timeouts and no SDK-side retries: we don't want a slow upstream to# multiply request time by 3 (default `max_retries=2`) inside a Django worker.+ from anthropic import Anthropic # noqa: PLC0415+return Anthropic(api_key=api_key, timeout=ANTHROPIC_CLIENT_TIMEOUT_SECONDS, max_retries=0)class AnthropicIntegration:integration: Integration- _client: Anthropic+ _client: "Anthropic"def __init__(self, integration: Integration) -> None:if integration.kind != Integration.IntegrationKind.ANTHROPIC.value:@@ -2996,6 +3000,13 @@ class AnthropicIntegration:def validate_key(api_key: str) -> None:# Validate by hitting the actual managed-agents surface so a key without# beta access fails at create time instead of silently failing later.+ from anthropic import ( # noqa: PLC0415+ APIConnectionError,+ APIStatusError,+ AuthenticationError,+ PermissionDeniedError,+ )+try:client = _build_anthropic_client(api_key)client.get(@@ -3335,11 +3346,13 @@ class StripeIntegration:def is_sandbox(self) -> bool:return _stripe_integration_is_sandbox(self.integration)- def _stripe_client(self) -> StripeClient | None:+ def _stripe_client(self) -> "StripeClient | None":# Sandbox accounts are issued by a separate Stripe app (live vs sandbox), so the# Apps Secret Store and account-scoped API calls must authenticate with the matching# developer secret. Returns None when the required env vars are missing so callers# can skip Stripe API calls without raising past their per-secret error handling.+ from stripe import StripeClient # noqa: PLC0415+try:oauth_config = OauthIntegration.oauth_config_for_kind("stripe", is_sandbox=self.is_sandbox)except NotImplementedError as e:diff --git a/posthog/temporal/ai/anomaly_investigation/charts.py b/posthog/temporal/ai/anomaly_investigation/charts.pyindex 5e823ad03a9f..e77e9efd7232 100644--- a/posthog/temporal/ai/anomaly_investigation/charts.py+++ b/posthog/temporal/ai/anomaly_investigation/charts.py@@ -20,11 +20,10 @@ from typing import Any# is Agg. Set MPLBACKEND via env var before the first matplotlib import so we# pick the backend the canonical way and avoid post-import `matplotlib.use(...)`# mutations to library-global state. `setdefault` leaves an explicit override-# from the environment intact.+# from the environment intact. Set at module load so it's in place before the+# deferred import inside render_series_chart runs.os.environ.setdefault("MPLBACKEND", "Agg")-import matplotlib.pyplot as plt # noqa: E402-logger = logging.getLogger(__name__)CHART_WIDTH_IN = 8.0@@ -50,6 +49,10 @@ def render_series_chart(if not dates or not values or len(dates) != len(values):return None+ # Deferred import: matplotlib is heavy (~0.35s) and only the temporal worker+ # rendering a chart needs it — not every process that imports this module.+ import matplotlib.pyplot as plt+try:fig, ax = plt.subplots(figsize=(CHART_WIDTH_IN, CHART_HEIGHT_IN), dpi=CHART_DPI)x = list(range(len(values)))diff --git a/posthog/temporal/data_imports/sources/__init__.py b/posthog/temporal/data_imports/sources/__init__.pyindex e6ace2644a3d..0d257b64fb52 100644--- a/posthog/temporal/data_imports/sources/__init__.py+++ b/posthog/temporal/data_imports/sources/__init__.py@@ -1,297 +1,32 @@-from .active_campaign.source import ActiveCampaignSource-from .adjust.source import AdjustSource-from .aircall.source import AircallSource-from .airtable.source import AirtableSource-from .amazon_ads.source import AmazonAdsSource-from .amplitude.source import AmplitudeSource-from .apple_search_ads.source import AppleSearchAdsSource-from .appsflyer.source import AppsFlyerSource-from .asana.source import AsanaSource-from .ashby.source import AshbySource-from .attio.source import AttioSource-from .auth0.source import Auth0Source-from .azure_blob.source import AzureBlobSource-from .bamboohr.source import BambooHRSource-from .bigcommerce.source import BigCommerceSource-from .bigquery.source import BigQuerySource-from .bing_ads.source import BingAdsSource-from .box.source import BoxSource-from .braintree.source import BraintreeSource-from .braze.source import BrazeSource-from .brevo.source import BrevoSource-from .buildbetter.source import BuildBetterSource-from .calendly.source import CalendlySource-from .campaign_monitor.source import CampaignMonitorSource-from .chargebee.source import ChargebeeSource-from .chartmogul.source import ChartMogulSource-from .circleci.source import CircleCISource-from .clerk.source import ClerkSource-from .clickhouse.source import ClickHouseSource-from .clickup.source import ClickUpSource-from .close.source import CloseSource-from .cockroachdb.source import CockroachDBSource+from typing import Any+from .common.registry import SourceRegistry-from .confluence.source import ConfluenceSource-from .convertkit.source import ConvertKitSource-from .convex.source import ConvexSource-from .copper.source import CopperSource-from .custom.source import CustomSource-from .customer_io.source import CustomerIOSource-from .datadog.source import DatadogSource-from .doit.source import DoItSource-from .drip.source import DripSource-from .dynamodb.source import DynamoDBSource-from .elasticsearch.source import ElasticsearchSource-from .eventbrite.source import EventbriteSource-from .facebook_pages.source import FacebookPagesSource-from .firebase.source import FirebaseSource-from .freshdesk.source import FreshdeskSource-from .freshsales.source import FreshsalesSource-from .front.source import FrontSource-from .fullstory.source import FullStorySource-from .github.source import GithubSource-from .gitlab.source import GitLabSource-from .gong.source import GongSource-from .google_ads.source import GoogleAdsSource-from .google_analytics.source import GoogleAnalyticsSource-from .google_drive.source import GoogleDriveSource-from .google_sheets.source import GoogleSheetsSource-from .gorgias.source import GorgiasSource-from .granola.source import GranolaSource-from .greenhouse.source import GreenhouseSource-from .helpscout.source import HelpScoutSource-from .hubspot.source import HubspotSource-from .instagram.source import InstagramSource-from .intercom.source import IntercomSource-from .iterable.source import IterableSource-from .jira.source import JiraSource-from .kafka.source import KafkaSource-from .klaviyo.source import KlaviyoSource-from .launchdarkly.source import LaunchDarklySource-from .lever.source import LeverSource-from .linear.source import LinearSource-from .linkedin_ads.source import LinkedInAdsSource-from .mailchimp.source import MailchimpSource-from .mailerlite.source import MailerLiteSource-from .mailjet.source import MailJetSource-from .marketo.source import MarketoSource-from .meta_ads.source import MetaAdsSource-from .microsoft_teams.source import MicrosoftTeamsSource-from .mixpanel.source import MixpanelSource-from .monday.source import MondaySource-from .mongodb.source import MongoDBSource-from .mssql.source import MSSQLSource-from .mysql.source import MySQLSource-from .netsuite.source import NetSuiteSource-from .notion.source import NotionSource-from .okta.source import OktaSource-from .omnisend.source import OmnisendSource-from .onedrive.source import OneDriveSource-from .oracle.source import OracleSource-from .outreach.source import OutreachSource-from .paddle.source import PaddleSource-from .pagerduty.source import PagerDutySource-from .pardot.source import PardotSource-from .paypal.source import PayPalSource-from .pendo.source import PendoSource-from .pganalyze.source import PgAnalyzeSource-from .pinterest_ads.source import PinterestAdsSource-from .pipedrive.source import PipedriveSource-from .plaid.source import PlaidSource-from .plain.source import PlainSource-from .polar.source import PolarSource-from .postgres.source import PostgresSource-from .postmark.source import PostmarkSource-from .productboard.source import ProductboardSource-from .quickbooks.source import QuickBooksSource-from .recharge.source import RechargeSource-from .recurly.source import RecurlySource-from .reddit_ads.source import RedditAdsSource-from .redshift.source import RedshiftSource-from .resend.source import ResendSource-from .revenuecat.source import RevenueCatSource-from .ringcentral.source import RingCentralSource-from .salesforce.source import SalesforceSource-from .salesloft.source import SalesLoftSource-from .sendgrid.source import SendGridSource-from .sentry.source import SentrySource-from .servicenow.source import ServiceNowSource-from .sftp.source import SFTPSource-from .sharepoint.source import SharePointSource-from .shopify.source import ShopifySource-from .shortcut.source import ShortcutSource-from .slack.source import SlackSource-from .smartsheet.source import SmartsheetSource-from .snapchat_ads.source import SnapchatAdsSource-from .snowflake.source import SnowflakeSource-from .square.source import SquareSource-from .stripe.source import StripeSource-from .supabase.source import SupabaseSource-from .surveymonkey.source import SurveyMonkeySource-from .temporalio.source import TemporalIOSource-from .tiktok_ads.source import TikTokAdsSource-from .trello.source import TrelloSource-from .twilio.source import TwilioSource-from .twitter_ads.source import TwitterAdsSource-from .typeform.source import TypeformSource-from .vitally.source import VitallySource-from .webflow.source import WebflowSource-from .woocommerce.source import WooCommerceSource-from .workday.source import WorkdaySource-from .wrike.source import WrikeSource-from .xero.source import XeroSource-from .youtube_analytics.source import YouTubeAnalyticsSource-from .zendesk.source import ZendeskSource-from .zoho_crm.source import ZohoCRMSource-from .zoom.source import ZoomSource-from .zuora.source import ZuoraSource-__all__ = [- "ActiveCampaignSource",- "AdjustSource",- "AircallSource",- "AirtableSource",- "AmazonAdsSource",- "AmplitudeSource",- "AppleSearchAdsSource",- "AppsFlyerSource",- "AsanaSource",- "AshbySource",- "AttioSource",- "Auth0Source",- "AzureBlobSource",- "BambooHRSource",- "BigCommerceSource",- "BigQuerySource",- "BingAdsSource",- "BoxSource",- "BraintreeSource",- "BrazeSource",- "BrevoSource",- "BuildBetterSource",- "CalendlySource",- "CampaignMonitorSource",- "ChargebeeSource",- "ChartMogulSource",- "CircleCISource",- "ClerkSource",- "ClickHouseSource",- "ClickUpSource",- "CloseSource",- "CockroachDBSource",- "ConfluenceSource",- "ConvertKitSource",- "ConvexSource",- "CopperSource",- "CustomSource",- "CustomerIOSource",- "DatadogSource",- "DoItSource",- "DripSource",- "DynamoDBSource",- "ElasticsearchSource",- "EventbriteSource",- "FacebookPagesSource",- "FirebaseSource",- "FreshdeskSource",- "FreshsalesSource",- "FrontSource",- "FullStorySource",- "GithubSource",- "GitLabSource",- "GongSource",- "GoogleAdsSource",- "GoogleAnalyticsSource",- "GoogleDriveSource",- "GoogleSheetsSource",- "GorgiasSource",- "GranolaSource",- "GreenhouseSource",- "HelpScoutSource",- "HubspotSource",- "InstagramSource",- "IntercomSource",- "IterableSource",- "JiraSource",- "KafkaSource",- "KlaviyoSource",- "LaunchDarklySource",- "LeverSource",- "LinearSource",- "LinkedInAdsSource",- "MailchimpSource",- "MailerLiteSource",- "MailJetSource",- "MarketoSource",- "MetaAdsSource",- "MicrosoftTeamsSource",- "MixpanelSource",- "MondaySource",- "MongoDBSource",- "MSSQLSource",- "MySQLSource",- "NetSuiteSource",- "NotionSource",- "OktaSource",- "OmnisendSource",- "OneDriveSource",- "OracleSource",- "OutreachSource",- "PaddleSource",- "PagerDutySource",- "PardotSource",- "PayPalSource",- "PendoSource",- "PgAnalyzeSource",- "PinterestAdsSource",- "PipedriveSource",- "PlaidSource",- "PlainSource",- "PolarSource",- "PostmarkSource",- "PostgresSource",- "ProductboardSource",- "QuickBooksSource",- "RechargeSource",- "RecurlySource",- "RedditAdsSource",- "RedshiftSource",- "ResendSource",- "RevenueCatSource",- "RingCentralSource",- "SalesforceSource",- "SalesLoftSource",- "SendGridSource",- "SentrySource",- "ServiceNowSource",- "SFTPSource",- "SharePointSource",- "ShopifySource",- "ShortcutSource",- "SlackSource",- "SmartsheetSource",- "SnapchatAdsSource",- "SnowflakeSource",- "SourceRegistry",- "SquareSource",- "StripeSource",- "SupabaseSource",- "SurveyMonkeySource",- "TemporalIOSource",- "TikTokAdsSource",- "TrelloSource",- "TwilioSource",- "TwitterAdsSource",- "TypeformSource",- "VitallySource",- "WebflowSource",- "WooCommerceSource",- "WorkdaySource",- "WrikeSource",- "XeroSource",- "YouTubeAnalyticsSource",- "ZendeskSource",- "ZohoCRMSource",- "ZoomSource",- "ZuoraSource",-]+__all__ = ["SourceRegistry", "load_all_sources"]+++def load_all_sources() -> None:+ """Import every source module so each registers itself with ``SourceRegistry``.++ Deferred out of module scope so importing a leaf (e.g. ``sources.stripe.constants``)+ doesn't drag every vendor SDK at app startup. Importing ``_load_all`` runs each+ source module's ``@SourceRegistry.register`` decorator. Idempotent — re-imports are+ cheap dict lookups in ``sys.modules``.+ """+ from . import _load_all # noqa: F401, PLC0415+++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("_"):+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")++ from . import _load_all # noqa: PLC0415++ try:+ return getattr(_load_all, name)+ except AttributeError:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from Nonediff --git a/posthog/temporal/data_imports/sources/_load_all.py b/posthog/temporal/data_imports/sources/_load_all.pynew file mode 100644index 000000000000..0d58b0d820da--- /dev/null+++ b/posthog/temporal/data_imports/sources/_load_all.py@@ -0,0 +1,155 @@+# ruff: noqa: F401+"""Import every source module so each registers itself with ``SourceRegistry``.++Kept out of ``sources/__init__.py`` so that importing a leaf (e.g.+``sources.stripe.constants``) does not drag every vendor SDK at app startup.+``SourceRegistry`` imports this module lazily on first use — see+``common/registry.py``.+"""++from .active_campaign.source import ActiveCampaignSource+from .adjust.source import AdjustSource+from .aircall.source import AircallSource+from .airtable.source import AirtableSource+from .amazon_ads.source import AmazonAdsSource+from .amplitude.source import AmplitudeSource+from .apple_search_ads.source import AppleSearchAdsSource+from .appsflyer.source import AppsFlyerSource+from .asana.source import AsanaSource+from .ashby.source import AshbySource+from .attio.source import AttioSource+from .auth0.source import Auth0Source+from .azure_blob.source import AzureBlobSource+from .bamboohr.source import BambooHRSource+from .bigcommerce.source import BigCommerceSource+from .bigquery.source import BigQuerySource+from .bing_ads.source import BingAdsSource+from .box.source import BoxSource+from .braintree.source import BraintreeSource+from .braze.source import BrazeSource+from .brevo.source import BrevoSource+from .buildbetter.source import BuildBetterSource+from .calendly.source import CalendlySource+from .campaign_monitor.source import CampaignMonitorSource+from .chargebee.source import ChargebeeSource+from .chartmogul.source import ChartMogulSource+from .circleci.source import CircleCISource+from .clerk.source import ClerkSource+from .clickhouse.source import ClickHouseSource+from .clickup.source import ClickUpSource+from .close.source import CloseSource+from .cockroachdb.source import CockroachDBSource+from .confluence.source import ConfluenceSource+from .convertkit.source import ConvertKitSource+from .convex.source import ConvexSource+from .copper.source import CopperSource+from .custom.source import CustomSource+from .customer_io.source import CustomerIOSource+from .datadog.source import DatadogSource+from .doit.source import DoItSource+from .drip.source import DripSource+from .dynamodb.source import DynamoDBSource+from .elasticsearch.source import ElasticsearchSource+from .eventbrite.source import EventbriteSource+from .facebook_pages.source import FacebookPagesSource+from .firebase.source import FirebaseSource+from .freshdesk.source import FreshdeskSource+from .freshsales.source import FreshsalesSource+from .front.source import FrontSource+from .fullstory.source import FullStorySource+from .github.source import GithubSource+from .gitlab.source import GitLabSource+from .gong.source import GongSource+from .google_ads.source import GoogleAdsSource+from .google_analytics.source import GoogleAnalyticsSource+from .google_drive.source import GoogleDriveSource+from .google_sheets.source import GoogleSheetsSource+from .gorgias.source import GorgiasSource+from .granola.source import GranolaSource+from .greenhouse.source import GreenhouseSource+from .helpscout.source import HelpScoutSource+from .hubspot.source import HubspotSource+from .instagram.source import InstagramSource+from .intercom.source import IntercomSource+from .iterable.source import IterableSource+from .jira.source import JiraSource+from .kafka.source import KafkaSource+from .klaviyo.source import KlaviyoSource+from .launchdarkly.source import LaunchDarklySource+from .lever.source import LeverSource+from .linear.source import LinearSource+from .linkedin_ads.source import LinkedInAdsSource+from .mailchimp.source import MailchimpSource+from .mailerlite.source import MailerLiteSource+from .mailjet.source import MailJetSource+from .marketo.source import MarketoSource+from .meta_ads.source import MetaAdsSource+from .microsoft_teams.source import MicrosoftTeamsSource+from .mixpanel.source import MixpanelSource+from .monday.source import MondaySource+from .mongodb.source import MongoDBSource+from .mssql.source import MSSQLSource+from .mysql.source import MySQLSource+from .netsuite.source import NetSuiteSource+from .notion.source import NotionSource+from .okta.source import OktaSource+from .omnisend.source import OmnisendSource+from .onedrive.source import OneDriveSource+from .oracle.source import OracleSource+from .outreach.source import OutreachSource+from .paddle.source import PaddleSource+from .pagerduty.source import PagerDutySource+from .pardot.source import PardotSource+from .paypal.source import PayPalSource+from .pendo.source import PendoSource+from .pganalyze.source import PgAnalyzeSource+from .pinterest_ads.source import PinterestAdsSource+from .pipedrive.source import PipedriveSource+from .plaid.source import PlaidSource+from .plain.source import PlainSource+from .polar.source import PolarSource+from .postgres.source import PostgresSource+from .postmark.source import PostmarkSource+from .productboard.source import ProductboardSource+from .quickbooks.source import QuickBooksSource+from .recharge.source import RechargeSource+from .recurly.source import RecurlySource+from .reddit_ads.source import RedditAdsSource+from .redshift.source import RedshiftSource+from .resend.source import ResendSource+from .revenuecat.source import RevenueCatSource+from .ringcentral.source import RingCentralSource+from .salesforce.source import SalesforceSource+from .salesloft.source import SalesLoftSource+from .sendgrid.source import SendGridSource+from .sentry.source import SentrySource+from .servicenow.source import ServiceNowSource+from .sftp.source import SFTPSource+from .sharepoint.source import SharePointSource+from .shopify.source import ShopifySource+from .shortcut.source import ShortcutSource+from .slack.source import SlackSource+from .smartsheet.source import SmartsheetSource+from .snapchat_ads.source import SnapchatAdsSource+from .snowflake.source import SnowflakeSource+from .square.source import SquareSource+from .stripe.source import StripeSource+from .supabase.source import SupabaseSource+from .surveymonkey.source import SurveyMonkeySource+from .temporalio.source import TemporalIOSource+from .tiktok_ads.source import TikTokAdsSource+from .trello.source import TrelloSource+from .twilio.source import TwilioSource+from .twitter_ads.source import TwitterAdsSource+from .typeform.source import TypeformSource+from .vitally.source import VitallySource+from .webflow.source import WebflowSource+from .woocommerce.source import WooCommerceSource+from .workday.source import WorkdaySource+from .wrike.source import WrikeSource+from .xero.source import XeroSource+from .youtube_analytics.source import YouTubeAnalyticsSource+from .zendesk.source import ZendeskSource+from .zoho_crm.source import ZohoCRMSource+from .zoom.source import ZoomSource+from .zuora.source import ZuoraSourcediff --git a/posthog/temporal/data_imports/sources/common/registry.py b/posthog/temporal/data_imports/sources/common/registry.pyindex 42476aea2d04..7605830d1630 100644--- a/posthog/temporal/data_imports/sources/common/registry.py+++ b/posthog/temporal/data_imports/sources/common/registry.py@@ -1,3 +1,4 @@+import threadingfrom typing import TYPE_CHECKINGfrom products.data_warehouse.backend.types import ExternalDataSourceType@@ -10,6 +11,27 @@ class SourceRegistry:"""Registry for all available data warehouse sources"""_sources: dict[ExternalDataSourceType, "AnySource"] = {}+ _loaded: bool = False+ _load_lock = threading.Lock()++ @classmethod+ def _ensure_loaded(cls) -> None:+ # Sources self-register via @SourceRegistry.register on import. We import them+ # 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.+ if cls._loaded:+ return+ with cls._load_lock:+ # another thread may have loaded while we waited for the lock; mypy can't model that+ if cls._loaded:+ return # type: ignore[unreachable]+ from posthog.temporal.data_imports.sources import load_all_sources # noqa: PLC0415++ load_all_sources()+ cls._loaded = True@classmethoddef register(cls, source_class: type["AnySource"]):@@ -24,6 +46,7 @@ class SourceRegistry:def get_source(cls, source_type: ExternalDataSourceType) -> "AnySource":"""Get a source instance by type"""+ cls._ensure_loaded()if source_type not in cls._sources:raise ValueError(f"Unknown source type: {source_type}")return cls._sources[source_type]@@ -32,16 +55,19 @@ class SourceRegistry:def get_all_sources(cls) -> dict[ExternalDataSourceType, "AnySource"]:"""Get all registered sources"""+ cls._ensure_loaded()return cls._sources@classmethoddef is_registered(cls, source_type: ExternalDataSourceType) -> bool:"""Check if a source type is registered"""+ cls._ensure_loaded()return source_type in cls._sources@classmethoddef get_registered_types(cls) -> list[ExternalDataSourceType]:"""Get all registered source types"""+ cls._ensure_loaded()return list(cls._sources.keys())diff --git a/products/batch_exports/backend/api/destination_tests/__init__.py b/products/batch_exports/backend/api/destination_tests/__init__.pyindex 332cebba30f8..daed4ea90b11 100644--- a/products/batch_exports/backend/api/destination_tests/__init__.py+++ b/products/batch_exports/backend/api/destination_tests/__init__.py@@ -1,24 +1,42 @@-from products.batch_exports.backend.api.destination_tests.azure_blob import AzureBlobDestinationTestfrom products.batch_exports.backend.api.destination_tests.base import DestinationTest-from products.batch_exports.backend.api.destination_tests.bigquery import BigQueryDestinationTest-from products.batch_exports.backend.api.destination_tests.databricks import DatabricksDestinationTest-from products.batch_exports.backend.api.destination_tests.s3 import S3DestinationTest-from products.batch_exports.backend.api.destination_tests.snowflake import SnowflakeDestinationTestdef get_destination_test(destination: str,) -> DestinationTest:- """Resolve a destination to its corresponding `DestinationTest` implementation."""+ """Resolve a destination to its corresponding `DestinationTest` implementation.++ Per-branch deferred imports: each destination test module pulls a heavy vendor SDK+ (databricks, google-cloud-bigquery, snowflake, etc.). Importing them lazily keeps the+ SDKs off the API import path — only the requested destination's SDK loads.+ """if destination == "S3":+ from products.batch_exports.backend.api.destination_tests.s3 import S3DestinationTest # noqa: PLC0415+return S3DestinationTest()elif destination == "BigQuery":+ from products.batch_exports.backend.api.destination_tests.bigquery import ( # noqa: PLC0415+ BigQueryDestinationTest,+ )+return BigQueryDestinationTest()elif destination == "Snowflake":+ from products.batch_exports.backend.api.destination_tests.snowflake import ( # noqa: PLC0415+ SnowflakeDestinationTest,+ )+return SnowflakeDestinationTest()elif destination == "Databricks":+ from products.batch_exports.backend.api.destination_tests.databricks import ( # noqa: PLC0415+ DatabricksDestinationTest,+ )+return DatabricksDestinationTest()elif destination == "AzureBlob":+ from products.batch_exports.backend.api.destination_tests.azure_blob import ( # noqa: PLC0415+ AzureBlobDestinationTest,+ )+return AzureBlobDestinationTest()else:raise ValueError(f"Unsupported destination: {destination}")diff --git a/products/business_knowledge/backend/html_parse.py b/products/business_knowledge/backend/html_parse.pyindex a1bdc6a5a160..a4aa2e044fa5 100644--- a/products/business_knowledge/backend/html_parse.py+++ b/products/business_knowledge/backend/html_parse.py@@ -12,7 +12,6 @@ Only `logic.py` is allowed to import this module.from __future__ import annotationsimport structlog-import trafilaturafrom bs4 import BeautifulSouplogger = structlog.get_logger(__name__)@@ -53,6 +52,10 @@ def parse_html(body: bytes, url: str) -> tuple[str, str]:should treat that as a soft failure and store an error on the source."""+ # Deferred import: trafilatura (and its dateparser/htmldate deps) is slow to import+ # and only needed when actually parsing a page, not at API/module load.+ import trafilatura+html = _decode(body)# trafilatura.extract returns the main-content text only. We ask fordiff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.pyindex 4b3eecf8d917..e6678e5ae444 100644--- a/products/user_interviews/backend/presentation/views.py+++ b/products/user_interviews/backend/presentation/views.py@@ -1,7 +1,7 @@import reimport json-from functools import cached_property-from typing import Any, cast+from functools import cache, cached_property+from typing import TYPE_CHECKING, Any, castfrom uuid import uuid4from django.conf import settings@@ -18,7 +18,6 @@ import posthoganalytics.ai.openaifrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiResponse, extend_schema-from elevenlabs import ElevenLabsfrom posthoganalytics.ai.openai import OpenAIfrom rest_framework import filters, response, serializers, status, viewsetsfrom rest_framework.decorators import action@@ -51,7 +50,17 @@ from ..models import EmailWithDisplayNameValidator, IntervieweeContext, UserIntelogger = structlog.get_logger(__name__)-elevenlabs_client = ElevenLabs()+if TYPE_CHECKING:+ from elevenlabs import ElevenLabs+++@cache+def _get_elevenlabs_client() -> "ElevenLabs":+ # Deferred import + cached instance: the elevenlabs SDK is slow to import and+ # only the audio transcription path needs it, not every process that loads this module.+ from elevenlabs import ElevenLabs++ return ElevenLabs()class _InterviewLinksCSVRenderer(csvrenderers.CSVRenderer):@@ -89,7 +98,7 @@ class UserInterviewSerializer(serializers.ModelSerializer):return super().create(validated_data)def _transcribe_audio(self, audio: File, interviewee_emails: list[str]) -> str:- transcript = elevenlabs_client.speech_to_text.convert(+ transcript = _get_elevenlabs_client().speech_to_text.convert(model_id="scribe_v1",file=audio,num_speakers=10, # Maximum number of speakers, not expected onediff --git a/pyproject.toml b/pyproject.tomlindex 9ecc4dd0a7dc..be04d226bac6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -342,6 +342,7 @@ select = ["RUF019","T100","T2",+ "TID253","TRY201","TRY400","UP",@@ -371,6 +372,13 @@ select = ["services/stripe-mock/**" = ["PLC0415"]"tools/**" = ["PLC0415"]+[tool.ruff.lint.flake8-tidy-imports]+# Heavy SDKs that noticeably slow startup. They must be imported lazily (inside the+# function that uses them), not at module top, so they stay off the Django app-load path.+# Only modules with a single, already-lazy call site are listed — vendor source/destination+# leaf modules legitimately import their own SDK at module level and are loaded on demand.+banned-module-level-imports = ["elevenlabs", "matplotlib", "trafilatura"]+[tool.ruff.lint.mccabe]max-complexity = 10