: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(startup): defer heavy imports off the django.setup() path (#105006)
Frank Hamandb27912bc4a83
diff --git a/Dockerfile b/Dockerfileindex c43efb212fc8..1732b0069ce3 100644--- a/Dockerfile+++ b/Dockerfile@@ -436,6 +436,14 @@ RUN test -f products/stamphog/packages/pr-approval-agent/review_local.py && test# services/ is a Node build (Dockerfile.node) and deliberately stays out of this image.COPY --chown=posthog:posthog services/mcp/schema services/mcp/schema/+# Pre-compile first-party bytecode. Site-packages are already compiled (UV_COMPILE_BYTECODE=1), but+# the app runs as `nobody` (bin/docker-server), which cannot write __pycache__ under the posthog-owned+# /code, so without this every process compiled ~1300 first-party modules in memory at every start.+# Test modules are skipped to keep the layer small. Default (timestamp) validation: one stat per+# module, and a later COPY of edited .py files still takes effect. See docs/internal/django-startup-time.md.+RUN /python-runtime/bin/python -m compileall -q -j 0 -x '/tests?/' \+ manage.py posthog ee common/hogvm common/migration_utils products packages/owners-yaml+# Validate the Playwright client library (used to drive the remote browserless service over CDP —# no browser binary ships in this image).RUN /python-runtime/bin/python -c "import playwright; print('Playwright package imported successfully')"diff --git a/docs/internal/django-startup-time.md b/docs/internal/django-startup-time.mdindex 1fee94146e80..5d025079085e 100644--- a/docs/internal/django-startup-time.md+++ b/docs/internal/django-startup-time.md@@ -163,6 +163,41 @@ When the floor has crept, the lever is the same as it ever was — find the heavSometimes you cannot just defer a heavy import because it is load-bearing in a circular import — deferring one edge only relocates the cycle.`grimp`'s `nominate_cycle_breakers` ranks which edge to cut, so the real work becomes untangling the owning package's cycle before the heavy import can come off the startup path.+## Where the floor is now, and what is left++Re-profiled September 2026 (`TEST=1 DEBUG=1`, warm page cache, GC disabled): a bare `django.setup()` went from ~1.95s to ~1.5s and `manage.py shell -c '1'` from ~1.9s to ~1.6s wall, by removing ~460 modules from the setup path.+Every removal was a `ready()` chain or a model file dragging a subsystem in at module scope — the same shape as before, one level further down the tail:++- `products/signals/backend/receivers.py` imported `scout_harness.suggestions` → `prompt` → `products.tasks.backend.facade.api` → `facade.contracts` (61 pydantic dataclasses) to wire one `post_delete` receiver. Deferred to the receiver body.+- `ee` `ready()` imported all of `ee/vercel/integration.py` to wire four receivers. That module imports `ee.api.authentication`, which holds `@api_view` functions, and DRF's decorator resolves `DEFAULT_SCHEMA_CLASS` at decoration time → `posthog.api.documentation` → `drf_spectacular.plumbing` → `rest_framework.test` → `django.test` → `jinja2`. The receivers now live in `ee/vercel/receivers.py` (a light module, as the skill asks) and import the integration when they fire.+- `posthog/helpers/impersonation.py` (reached from the activity-log signal handlers) imported `posthog.auth`, which pulls `zxcvbn` and `webauthn`. Deferred. The guard then caught that `WebauthnCredential` only registered through that import — it is now imported from `posthog/models/__init__.py`.+- `posthog/apps.py` imported `posthog.async_migrations.setup` (which imports every async migration) even when `SKIP_ASYNC_MIGRATIONS_SETUP` is on. Import moved under the branch that runs it. That module also used `infi.clickhouse_orm.utils.import_submodules`, and the `infi` package `__init__` imports `pkg_resources` (~40ms); replaced with a local `pkgutil` helper. Deferring it exposed a latent cycle that setup-first import order had hidden: `async_migrations/utils.py` imported the dependency map from `setup.py` at module scope, `setup.py` imports every migration module, and three migrations import `utils`. Entering at `utils` first (the celery task module, the API module, the tests) now failed with a partially initialised module, so `utils` reads the map at call time.+- `boto3`/`botocore` reached setup through three doors: `products.workflows.backend.providers` (eager aggregator `__init__`, hit by the email and twilio integration models), `posthog/storage/object_storage.py`, and `posthog/models/js_snippet_versioning.py`, plus an `except (BotoCoreError, ClientError)` in `posthog/storage/hypercache.py`. All build clients or classify exceptions at call time now. Web workers pay the boto3 import on their first request that touches object storage.++The _deferred_ modules are pinned in `FORBIDDEN_AT_SETUP` (`scout_harness.suggestions`, `ee.vercel.integration`, the vendor SDKs) — never a product facade or its contracts, which must stay importable from anywhere (see #100055).++**Bytecode.** "Warm" in these numbers means the `.pyc` files exist and the source is in the page cache.+Without first-party `.pyc` files a bare `django.setup()` costs ~2.4s instead of ~1.5s: ~1300 first-party modules get compiled on import.+Site-packages are compiled at image build (`UV_COMPILE_BYTECODE=1`). The app runs as `nobody` (`bin/docker-server`), which cannot write `__pycache__` under the `posthog`-owned `/code`, so before September 2026 _every_ process compiled the first-party modules in memory at _every_ start, not just the first boot of a container.+The production `Dockerfile` now runs `compileall` over the first-party source after the `COPY` (tests excluded; default timestamp validation, so one `stat` per module and a later `COPY` of edited `.py` files still takes effect). Measured locally: ~3s build time, ~15.9k `.pyc` files, ~117 MB in the layer; the layer is rebuilt on every source change.+Locally, the first run after a checkout or a large rebase pays the compile once; `__pycache__` is gitignored and persists after that.+Tests that patched a moved name were repointed to the defining module (`boto3.client`, `products.workflows.backend.providers.SESProvider`).++**Evaluated and left alone**, so nobody re-measures them from scratch:++- `clickhouse_driver` (~70ms, mostly a date lookup table built at import in `columns/datecolumn.py`) — blocked structurally: `posthog/clickhouse/client/connection.py` subclasses `clickhouse_driver.Client`, `posthog/errors.py` subclasses `ServerException`, and `posthog.clickhouse.client` has ~25 setup-path importers. Only evicting `posthog.clickhouse.client` from setup would remove it.+- `posthog.personhog_client` (grpc + protobuf, ~20ms) — six model-file importers for a small win. Not worth the churn.+- `posthog.utils` (~250ms cumulative) is imported by `posthog/settings/utils.py` for `str_to_bool`. Moving the helper only relocates the cost: model files import `posthog.utils` later in setup regardless, and its heavy children (`posthoganalytics`, `structlog`, `rest_framework`, `redis`) each have dozens of other setup-path importers.+- `posthog.celery` (~120ms) is imported from `posthog/__init__.py` so `shared_task` binds to our app. Structural.+- `posthog.settings.web` self time under `TEST=1` is the ephemeral 2048-bit RSA key for OIDC. Test-only.++**Measuring.** [hothog](https://github.com/PostHog/hothog) runs `django.setup()` under an import hook, ranks each heavy import by removable self-time, and names the single best module to defer it in; `hothog --compare base.log pr.log` diffs two captures. Use it before a raw `python -X importtime` read.++**The next lever is `posthog.hogql`**: ~170 modules and ~190ms self time, plus it is what keeps `posthog.clickhouse.client` (and so `clickhouse_driver`) and the `warehouse_sources` facade on the path.+It reaches setup from 27 first-party modules outside the package.+Some are one-line fixes (`posthog/models/group_usage_metric.py` uses `ast.Constant` in a method body), but most define HogQL objects at module scope — `products/cohorts/backend/models/util.py`, `products/customer_analytics/backend/facade/hogql.py`, `products/data_modeling/backend/models/{datawarehouse_saved_query,modeling}.py`, `products/warehouse_sources/backend/models/external_table_definitions.py`, `products/revenue_analytics/backend/views/` — so the work is cutting the `models/__init__` edges that pull those facade modules in, not deferring individual imports.+Expect ~250-300ms; do it entry point by entry point, with the stub A/B first.+## Traps (these have all caused follow-up fixes)**`ready()` that re-drags a heavy subsystem onto startup.**diff --git a/ee/apps.py b/ee/apps.pyindex 75e278ab7f14..634720765123 100644--- a/ee/apps.py+++ b/ee/apps.py@@ -8,4 +8,5 @@ class EnterpriseConfig(AppConfig):def ready(self) -> None:# Connect the Vercel experimentation-item sync receivers at app-population. They used to# wire in via a viewset import; the lazy API router no longer pulls that, so connect here.- from ee.vercel import integration # noqa: F401, PLC0415+ # The receivers live in a light module so ready() does not import ee.vercel.integration.+ from ee.vercel import receivers # noqa: F401, PLC0415diff --git a/ee/vercel/integration.py b/ee/vercel/integration.pyindex 7994354e065b..9133a9be1332 100644--- a/ee/vercel/integration.py+++ b/ee/vercel/integration.py@@ -10,8 +10,6 @@ from django.conf import settingsfrom django.contrib.auth import loginfrom django.core.cache import cachefrom django.db import IntegrityError, transaction-from django.db.models.signals import post_delete, post_save-from django.dispatch import receiverfrom django.utils import timezonefrom django.utils.text import slugify@@ -1346,63 +1344,3 @@ def _safe_vercel_sync(integration="vercel",)capture_exception(e)---@receiver(post_save, sender=FeatureFlag)-def sync_feature_flag_experimentation_item(sender, instance: FeatureFlag, created, **kwargs):- if instance.deleted:- _safe_vercel_sync(- "delete feature flag from Vercel",- instance.pk,- instance.team,- lambda: VercelIntegration.delete_feature_flag_from_vercel(instance),- is_delete=True,- )- else:- _safe_vercel_sync(- "sync feature flag to Vercel",- instance.pk,- instance.team,- lambda: VercelIntegration.sync_feature_flag_to_vercel(instance, created),- )---@receiver(post_delete, sender=FeatureFlag)-def delete_resource_experimentation_item(sender, instance: FeatureFlag, **kwargs):- _safe_vercel_sync(- "delete feature flag from Vercel",- instance.pk,- instance.team,- lambda: VercelIntegration.delete_feature_flag_from_vercel(instance),- is_delete=True,- )---@receiver(post_save, sender=Experiment)-def sync_experiment_experimentation_item(sender, instance: Experiment, created, **kwargs):- if instance.deleted:- _safe_vercel_sync(- "delete experiment from Vercel",- instance.pk,- instance.team,- lambda: VercelIntegration.delete_experiment_from_vercel(instance),- is_delete=True,- )- else:- _safe_vercel_sync(- "sync experiment to Vercel",- instance.pk,- instance.team,- lambda: VercelIntegration.sync_experiment_to_vercel(instance, created),- )---@receiver(post_delete, sender=Experiment)-def delete_experiment_experimentation_item(sender, instance: Experiment, **kwargs):- _safe_vercel_sync(- "delete experiment from Vercel",- instance.pk,- instance.team,- lambda: VercelIntegration.delete_experiment_from_vercel(instance),- is_delete=True,- )diff --git a/ee/vercel/receivers.py b/ee/vercel/receivers.pynew file mode 100644index 000000000000..bb9f335abe38--- /dev/null+++ b/ee/vercel/receivers.py@@ -0,0 +1,94 @@+"""Vercel experimentation-item sync receivers.++Wired from ``EnterpriseConfig.ready()``. Kept apart from ``ee.vercel.integration`` so that+django.setup() does not import that module (and everything it reaches) in every process just+to connect four receivers; the integration is imported when a receiver actually fires.+"""++from typing import Any++from django.db.models.signals import post_delete, post_save+from django.dispatch import receiver++from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++@receiver(post_save, sender=FeatureFlag)+def sync_feature_flag_experimentation_item(sender: Any, instance: FeatureFlag, created: bool, **kwargs: Any) -> None:+ from ee.vercel.integration import ( # noqa: PLC0415 — keeps the heavy dep off the import path+ VercelIntegration,+ _safe_vercel_sync,+ )++ if instance.deleted:+ _safe_vercel_sync(+ "delete feature flag from Vercel",+ instance.pk,+ instance.team,+ lambda: VercelIntegration.delete_feature_flag_from_vercel(instance),+ is_delete=True,+ )+ else:+ _safe_vercel_sync(+ "sync feature flag to Vercel",+ instance.pk,+ instance.team,+ lambda: VercelIntegration.sync_feature_flag_to_vercel(instance, created),+ )+++@receiver(post_delete, sender=FeatureFlag)+def delete_resource_experimentation_item(sender: Any, instance: FeatureFlag, **kwargs: Any) -> None:+ from ee.vercel.integration import ( # noqa: PLC0415 — keeps the heavy dep off the import path+ VercelIntegration,+ _safe_vercel_sync,+ )++ _safe_vercel_sync(+ "delete feature flag from Vercel",+ instance.pk,+ instance.team,+ lambda: VercelIntegration.delete_feature_flag_from_vercel(instance),+ is_delete=True,+ )+++@receiver(post_save, sender=Experiment)+def sync_experiment_experimentation_item(sender: Any, instance: Experiment, created: bool, **kwargs: Any) -> None:+ from ee.vercel.integration import ( # noqa: PLC0415 — keeps the heavy dep off the import path+ VercelIntegration,+ _safe_vercel_sync,+ )++ if instance.deleted:+ _safe_vercel_sync(+ "delete experiment from Vercel",+ instance.pk,+ instance.team,+ lambda: VercelIntegration.delete_experiment_from_vercel(instance),+ is_delete=True,+ )+ else:+ _safe_vercel_sync(+ "sync experiment to Vercel",+ instance.pk,+ instance.team,+ lambda: VercelIntegration.sync_experiment_to_vercel(instance, created),+ )+++@receiver(post_delete, sender=Experiment)+def delete_experiment_experimentation_item(sender: Any, instance: Experiment, **kwargs: Any) -> None:+ from ee.vercel.integration import ( # noqa: PLC0415 — keeps the heavy dep off the import path+ VercelIntegration,+ _safe_vercel_sync,+ )++ _safe_vercel_sync(+ "delete experiment from Vercel",+ instance.pk,+ instance.team,+ lambda: VercelIntegration.delete_experiment_from_vercel(instance),+ is_delete=True,+ )diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex f6ee53cc1482..e7ea16f9cb4f 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -619,7 +619,7 @@ class TestEmailIntegration:self.organization = Organization.objects.create(name="Test Org")self.team = Team.objects.create(organization=self.organization, name="Test Team")- @patch("posthog.models.integration.email.SESProvider")+ @patch("products.workflows.backend.providers.SESProvider")def test_integration_from_domain(self, mock_ses_provider_class):mock_client = MagicMock()mock_ses_provider_class.return_value = mock_client@@ -651,7 +651,7 @@ class TestEmailIntegration:org_team_ids=[self.team.id],)- @patch("posthog.models.integration.email.SESProvider")+ @patch("products.workflows.backend.providers.SESProvider")def test_email_verify_returns_ses_result(self, mock_ses_provider_class):mock_client = MagicMock()mock_ses_provider_class.return_value = mock_client@@ -710,7 +710,7 @@ class TestEmailIntegration:"provider": "ses",}- @patch("posthog.models.integration.email.SESProvider")+ @patch("products.workflows.backend.providers.SESProvider")def test_email_verify_updates_integration(self, mock_ses_provider_class):mock_client = MagicMock()mock_ses_provider_class.return_value = mock_client@@ -747,7 +747,7 @@ class TestEmailIntegration:"provider": "ses",}- @patch("posthog.models.integration.email.SESProvider")+ @patch("products.workflows.backend.providers.SESProvider")def test_email_verify_updates_all_other_integrations_with_same_domain(self, mock_ses_provider_class, settings):settings.SES_ACCESS_KEY_ID = "test_access_key"settings.SES_SECRET_ACCESS_KEY = "test_secret_key"diff --git a/posthog/apps.py b/posthog/apps.pyindex bb4881c2e8ba..349bb09bc500 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -142,11 +142,13 @@ class PostHogConfig(AppConfig):if not posthoganalytics.disabled and posthoganalytics.feature_flag_definitions() is None:posthoganalytics.load_feature_flags()- from posthog.async_migrations.setup import setup_async_migrations-if settings.SKIP_ASYNC_MIGRATIONS_SETUP:logger.warning("Skipping async migrations setup. This is unsafe in production!")else:+ from posthog.async_migrations.setup import (+ setup_async_migrations, # noqa: PLC0415 — keeps the heavy dep off the import path+ )+setup_async_migrations()from posthog.api.file_system import registrations as file_system_registrationsdiff --git a/posthog/async_migrations/setup.py b/posthog/async_migrations/setup.pyindex b0c547afa79b..581211529c51 100644--- a/posthog/async_migrations/setup.py+++ b/posthog/async_migrations/setup.py@@ -1,8 +1,10 @@+import pkgutil+import importlib+from types import ModuleTypefrom typing import Optionalfrom django.core.exceptions import ImproperlyConfigured-from infi.clickhouse_orm.utils import import_submodulesfrom semantic_version.base import Versionfrom posthog.async_migrations.definition import AsyncMigrationDefinition@@ -27,6 +29,15 @@ DEPENDENCY_TO_ASYNC_MIGRATION: dict[Optional[str], str] = {}ASYNC_MIGRATIONS_MODULE_PATH = "posthog.async_migrations.migrations"ASYNC_MIGRATIONS_EXAMPLE_MODULE_PATH = "posthog.async_migrations.examples"++def import_submodules(package_name: str) -> dict[str, ModuleType]:+ """Import every direct submodule of a package, keyed by short name."""+ package = importlib.import_module(package_name)+ return {+ name: importlib.import_module(f"{package_name}.{name}") for _, name, _ in pkgutil.iter_modules(package.__path__)+ }++all_migrations = import_submodules(ASYNC_MIGRATIONS_MODULE_PATH)reload_migration_definitions()diff --git a/posthog/async_migrations/utils.py b/posthog/async_migrations/utils.pyindex a99092e31ea7..d4fe4e9125c8 100644--- a/posthog/async_migrations/utils.py+++ b/posthog/async_migrations/utils.py@@ -11,7 +11,6 @@ import structlogimport posthoganalyticsfrom posthog.async_migrations.definition import AsyncMigrationOperation-from posthog.async_migrations.setup import DEPENDENCY_TO_ASYNC_MIGRATIONfrom posthog.celery import appfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import make_ch_pool@@ -306,6 +305,11 @@ def complete_migration(migration_instance: AsyncMigration, email: bool = True):)if get_instance_setting("AUTO_START_ASYNC_MIGRATIONS"):+ # Call-time import to break a cycle: setup imports every migration module at import, and+ # three of them import this module. Entering here first (celery task module, API module,+ # tests) used to work only because django.setup() had already imported setup.+ from posthog.async_migrations.setup import DEPENDENCY_TO_ASYNC_MIGRATION # noqa: PLC0415+next_migration = DEPENDENCY_TO_ASYNC_MIGRATION.get(migration_instance.name)if next_migration:from posthog.async_migrations.runner import run_next_migrationdiff --git a/posthog/helpers/impersonation.py b/posthog/helpers/impersonation.pyindex 79f4936e9b5b..a92e26855215 100644--- a/posthog/helpers/impersonation.py+++ b/posthog/helpers/impersonation.py@@ -8,8 +8,6 @@ from django.http import HttpRequestfrom loginas import settings as la_settingsfrom loginas.utils import is_impersonated_session-from posthog.auth import OAuthAccessTokenAuthentication-def is_impersonated(request: Optional[HttpRequest]) -> bool:"""Whether the current action is being performed under staff impersonation.@@ -29,6 +27,10 @@ def is_impersonated(request: Optional[HttpRequest]) -> bool:if is_impersonated_session(request):return True+ # Call-time import: this helper is wired at django.setup() via the activity-log signal+ # handlers, and posthog.auth pulls zxcvbn/webauthn, which no background process needs.+ from posthog.auth import OAuthAccessTokenAuthentication # noqa: PLC0415 — keeps the heavy dep off the import path+authenticator = getattr(request, "successful_authenticator", None)if isinstance(authenticator, OAuthAccessTokenAuthentication):return authenticator.access_token.impersonated_by_id is not Nonediff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 92595c2f21c0..22cb88302bcf 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -77,6 +77,7 @@ from .user_repo_preference import UserRepoPreferencefrom .user_scene_personalisation import UserScenePersonalisationfrom .user_home_settings import UserHomeSettingsfrom .user_facet_settings import UserFacetSettings+from .webauthn_credential import WebauthnCredentialfrom .oauth import (CIMDVerificationToken,OAuthAccessToken,@@ -178,6 +179,7 @@ __all__ = ["UserScenePersonalisation","UserHomeSettings","UserFacetSettings",+ "WebauthnCredential","UserManager","UserGroup","UserGroupMembership",diff --git a/posthog/models/integration/email.py b/posthog/models/integration/email.pyindex 9a2ef92ed60a..14a80dc4f5ab 100644--- a/posthog/models/integration/email.py+++ b/posthog/models/integration/email.py@@ -1,6 +1,6 @@"""Native email-sending integration (SES / maildev) and its cleanup signal."""-from typing import Any+from typing import TYPE_CHECKING, Anyfrom django.conf import settingsfrom django.db import models, transaction@@ -14,10 +14,11 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.plugins.plugin_server_api import reload_integrations_on_workers-from products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDS, SESProvider-from . import model+if TYPE_CHECKING:+ from products.workflows.backend.providers import SESProvider+class EmailIntegration:integration: model.Integration@@ -28,7 +29,11 @@ class EmailIntegration:self.integration = integration@property- def ses_provider(self) -> SESProvider:+ def ses_provider(self) -> "SESProvider":+ from products.workflows.backend.providers import (+ SESProvider, # noqa: PLC0415 — keeps the heavy dep off the import path+ )+return SESProvider()@classmethod@@ -55,6 +60,10 @@ class EmailIntegration:# Create domain in the appropriate providerif provider == "ses":+ from products.workflows.backend.providers import (+ SESProvider, # noqa: PLC0415 — keeps the heavy dep off the import path+ )+ses = SESProvider()org_team_ids = list(Team.objects.filter(organization_id=organization_id).values_list("id", flat=True))ses.create_email_domain(@@ -102,6 +111,10 @@ class EmailIntegration:# Update domain in the appropriate providerif provider == "ses":+ from products.workflows.backend.providers import (+ SESProvider, # noqa: PLC0415 — keeps the heavy dep off the import path+ )+ses = SESProvider()ses.update_mail_from_subdomain(domain, mail_from_subdomain=mail_from_subdomain)elif provider == "maildev" and settings.DEBUG:@@ -130,6 +143,10 @@ class EmailIntegration:domain, mail_from_subdomain=mail_from_subdomain, team_id=self.integration.team_id)elif provider == "maildev":+ from products.workflows.backend.providers import (+ MAILDEV_MOCK_DNS_RECORDS, # noqa: PLC0415 — keeps the heavy dep off the import path+ )+verification_result = {"status": "success","dnsRecords": MAILDEV_MOCK_DNS_RECORDS,diff --git a/posthog/models/integration/twilio.py b/posthog/models/integration/twilio.pyindex 69387026df38..7cfcb4448951 100644--- a/posthog/models/integration/twilio.py+++ b/posthog/models/integration/twilio.py@@ -1,17 +1,24 @@"""Twilio integration."""-from rest_framework.exceptions import ValidationError+from typing import TYPE_CHECKING-from products.workflows.backend.providers import TwilioProvider+from rest_framework.exceptions import ValidationErrorfrom . import model+if TYPE_CHECKING:+ from products.workflows.backend.providers import TwilioProvider+class TwilioIntegration:integration: model.Integration- twilio_provider: TwilioProvider+ twilio_provider: "TwilioProvider"def __init__(self, integration: model.Integration) -> None:+ from products.workflows.backend.providers import (+ TwilioProvider, # noqa: PLC0415 — keeps the heavy dep off the import path+ )+if integration.kind != "twilio":raise Exception("TwilioIntegration init called with Integration with wrong 'kind'")self.integration = integrationdiff --git a/posthog/models/js_snippet_versioning.py b/posthog/models/js_snippet_versioning.pyindex a4f8e4ce2bbb..0a4199f652f0 100644--- a/posthog/models/js_snippet_versioning.py+++ b/posthog/models/js_snippet_versioning.py@@ -11,9 +11,7 @@ from typing import Any, NotRequired, Optional, TypedDictfrom django.conf import settingsfrom django.core.cache import cache-import boto3import structlog-from botocore.exceptions import ClientErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.storage.object_storage import ObjectStorageError@@ -29,12 +27,16 @@ _s3_client: Any = Nonedef _get_s3_client():global _s3_clientif _s3_client is None:+ import boto3 # noqa: PLC0415 — keeps the heavy dep off the import path+_s3_client = boto3.client("s3")return _s3_clientdef s3_read(key: str, *, missing_ok: bool = False) -> Optional[str]:"""Read a UTF-8 object from the JS S3 bucket."""+ from botocore.exceptions import ClientError # noqa: PLC0415 — keeps the heavy dep off the import path+try:response = _get_s3_client().get_object(Bucket=settings.POSTHOG_JS_S3_BUCKET, Key=key)return response["Body"].read().decode("utf-8")@@ -59,6 +61,8 @@ def s3_write(key: str, content: str) -> None:def s3_head(key: str) -> bool:"""Check whether an object exists in the JS S3 bucket."""+ from botocore.exceptions import ClientError # noqa: PLC0415 — keeps the heavy dep off the import path+try:_get_s3_client().head_object(Bucket=settings.POSTHOG_JS_S3_BUCKET, Key=key)return Truediff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex af6cbef38887..9177c247cfde 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -9,7 +9,6 @@ from django.core.cache import cache, cachesimport structlogimport redis.exceptions-from botocore.exceptions import BotoCoreError, ClientErrorfrom django_redis.exceptions import ConnectionInterruptedfrom posthoganalytics import capture_exceptionfrom prometheus_client import Counter, Histogram@@ -266,6 +265,13 @@ class HyperCache:return datadef get_from_cache_with_source(self, key: KeyType) -> tuple[dict | None, str]:+ # Call-time import: hypercache loads at django.setup() (via group_type_mapping) and botocore+ # is only needed to classify S3 read failures.+ from botocore.exceptions import ( # noqa: PLC0415 — keeps the heavy dep off the import path+ BotoCoreError,+ ClientError,+ )+cache_key = self.get_cache_key(key)try:data = self.cache_client.get(cache_key)diff --git a/posthog/storage/object_storage.py b/posthog/storage/object_storage.pyindex 79cc1378cfdc..2ae2879ab8c9 100644--- a/posthog/storage/object_storage.py+++ b/posthog/storage/object_storage.py@@ -6,9 +6,6 @@ from urllib.parse import urlparsefrom django.conf import settingsimport structlog-from boto3 import client-from botocore.client import Config-from botocore.exceptions import ClientErrorfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception@@ -197,6 +194,8 @@ class ObjectStorage(ObjectStorageClient):return Nonedef head_object_strict(self, bucket: str, file_key: str) -> Optional[dict]:+ from botocore.exceptions import ClientError # noqa: PLC0415 — keeps the heavy dep off the import path+try:return self.aws_client.head_object(Bucket=bucket, Key=file_key)except ClientError as e:@@ -304,6 +303,8 @@ class ObjectStorage(ObjectStorageClient):return None if result is None else result[0]def read_object(self, bucket: str, key: str, *, missing_ok: bool = False) -> Optional[tuple[bytes, Optional[str]]]:+ from botocore.exceptions import ClientError # noqa: PLC0415 — keeps the heavy dep off the import path+s3_response = {}try:s3_response = self.aws_client.get_object(Bucket=bucket, Key=key)@@ -486,6 +487,11 @@ def object_storage_client() -> ObjectStorageClient:if not settings.OBJECT_STORAGE_ENABLED:_client = UnavailableStorage()elif isinstance(_client, UnavailableStorage):+ # boto3/botocore are imported at call time: this module is on the django.setup() path+ # (hypercache -> group_type_mapping) and the SDK costs ~40ms that non-S3 processes never need.+ from boto3 import client # noqa: PLC0415 — keeps the heavy dep off the import path+ from botocore.client import Config # noqa: PLC0415 — keeps the heavy dep off the import path+s3_config = Config(signature_version="s3v4",connect_timeout=1,@@ -654,6 +660,9 @@ def _get_accelerated_presigned_client() -> Optional[Any]:if _accelerated_presigned_client is None and settings.OBJECT_STORAGE_TRANSFER_ACCELERATION:with _accelerated_client_lock:if _accelerated_presigned_client is None:+ from boto3 import client # noqa: PLC0415 — keeps the heavy dep off the import path+ from botocore.client import Config # noqa: PLC0415 — keeps the heavy dep off the import path+s3_config = Config(signature_version="s3v4",connect_timeout=1,diff --git a/posthog/storage/test/test_object_storage.py b/posthog/storage/test/test_object_storage.pyindex 7a0e33bffd42..f98473fe03a7 100644--- a/posthog/storage/test/test_object_storage.py+++ b/posthog/storage/test/test_object_storage.py@@ -52,7 +52,7 @@ class TestStorage(APIBaseTest):bucket = s3.Bucket(OBJECT_STORAGE_BUCKET)bucket.objects.filter(Prefix=TEST_BUCKET).delete()- @patch("posthog.storage.object_storage.client")+ @patch("boto3.client")def test_does_not_create_client_if_storage_is_disabled(self, patched_s3_client) -> None:with self.settings(OBJECT_STORAGE_ENABLED=False):assert not health_check()@@ -315,7 +315,7 @@ class TestObjectStorageClientFactory(SimpleTestCase):assert is_usable_endpoint(endpoint) is expected@patch("posthog.storage.object_storage.capture_exception")- @patch("posthog.storage.object_storage.client")+ @patch("boto3.client")def test_bad_public_endpoint_does_not_crash_read_path(self, patched_client, patched_capture) -> None:# A bad public endpoint must never raise out of the factory — readers route through it.with self.settings(@@ -333,7 +333,7 @@ class TestObjectStorageClientFactory(SimpleTestCase):patched_capture.assert_called_once()@patch("posthog.storage.object_storage.capture_exception")- @patch("posthog.storage.object_storage.client")+ @patch("boto3.client")def test_boto_failure_building_presigned_client_degrades(self, patched_client, patched_capture) -> None:internal_client = MagicMock()patched_client.side_effect = [internal_client, ValueError("Invalid endpoint")]@@ -350,7 +350,7 @@ class TestObjectStorageClientFactory(SimpleTestCase):assert storage.presigned_client is internal_clientpatched_capture.assert_called_once()- @patch("posthog.storage.object_storage.client")+ @patch("boto3.client")def test_valid_public_endpoint_builds_separate_presigned_client(self, patched_client) -> None:internal_client = MagicMock()presigned_client = MagicMock()diff --git a/posthog/test/repo_invariants/setup_import_baseline.txt b/posthog/test/repo_invariants/setup_import_baseline.txtindex 0162457b6cb0..4d3eece7e47f 100644--- a/posthog/test/repo_invariants/setup_import_baseline.txt+++ b/posthog/test/repo_invariants/setup_import_baseline.txt@@ -16,7 +16,6 @@## Third-party packages on the setup path today (cheap entries listed too, so a slow CI# runner cannot push a known package over the threshold):-botocoreceleryclickhouse_drivercryptography@@ -26,7 +25,6 @@ googlegrpckombuoauth2_provider-pkg_resourcespsycopgredisrichdiff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex 7c6bc459e18c..ca48663d8ac9 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -49,8 +49,8 @@ model_activity:products.tasks.backend.activity_logging.handle_loop_changemodel_activity:products.tracing.backend.activity_logging.handle_traces_retention_rule_activitymodel_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_schema_changemodel_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_source_change-post_delete:ee.vercel.integration.delete_experiment_experimentation_item-post_delete:ee.vercel.integration.delete_resource_experimentation_item+post_delete:ee.vercel.receivers.delete_experiment_experimentation_item+post_delete:ee.vercel.receivers.delete_resource_experimentation_itempost_delete:posthog.caching.organization_serializer_cache._connect_invalidation.<locals>.receiver_fnpost_delete:posthog.models.event_ingestion_restriction_config.delete_redis_cache_with_configpost_delete:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__init_subclass__.<locals>._file_system_post_delete@@ -118,8 +118,8 @@ post_init:posthog.storage.gateway_credential_signal_handlers._snapshot_secret_kepost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_userpost_init:posthog.storage.team_llm_gateway_policy_signal_handlers._snapshot_loaded_statepost_save:ee.models.license.license_saved-post_save:ee.vercel.integration.sync_experiment_experimentation_item-post_save:ee.vercel.integration.sync_feature_flag_experimentation_item+post_save:ee.vercel.receivers.sync_experiment_experimentation_item+post_save:ee.vercel.receivers.sync_feature_flag_experimentation_itempost_save:posthog.caching.organization_serializer_cache._connect_invalidation.<locals>.receiver_fnpost_save:posthog.models.activity_logging.activity_log.activity_log_createdpost_save:posthog.models.comment.comment.log_comment_activitydiff --git a/posthog/test/repo_invariants/test_startup_import_budget.py b/posthog/test/repo_invariants/test_startup_import_budget.pyindex f5ec242ac159..a18ee05cca55 100644--- a/posthog/test/repo_invariants/test_startup_import_budget.py+++ b/posthog/test/repo_invariants/test_startup_import_budget.py@@ -45,6 +45,17 @@ FORBIDDEN_AT_SETUP = ["posthog.hogql_queries", # the query-runner layer (every insight runner)"posthog.api.services.query", # API query service — viewset-request-time only"products.signals.backend.tasks", # celery task module — workers load it by autodiscovery; at setup it drags the signals and tasks contracts in+ "products.signals.backend.scout_harness.suggestions", # reaches the tasks facade contracts (pydantic DTOs) — deferred in the signals receivers; the facade itself stays importable+ "ee.vercel.integration", # reaches ee.api.authentication (@api_view -> DRF schema class) — receivers live in ee.vercel.receivers and import it at call time+ "posthog.api.documentation", # drf_spectacular schema hooks — request-time only+ "django.test", # test client — was dragged in by drf_spectacular.plumbing via rest_framework.test+ "zxcvbn", # password strength — only posthog.auth needs it, deferred in posthog.helpers.impersonation+ "webauthn", # passkeys — same door as zxcvbn (posthog.auth)+ "posthog.async_migrations.setup", # imports every async migration — only when SKIP_ASYNC_MIGRATIONS_SETUP is off+ "infi.clickhouse_orm", # ClickHouse ORM — migration commands only; its package __init__ imports pkg_resources+ "pkg_resources", # setuptools shim (~40ms) — only reached via infi.clickhouse_orm+ "boto3", # AWS SDK — object storage, SES and JS snippet clients build it at call time+ "botocore", # AWS SDK core — same door as boto3]# Runs in a clean interpreter: pytest has already imported half the world, so we cannotdiff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.pyindex 9b0dd54d073b..865623f0a091 100644--- a/products/signals/backend/receivers.py+++ b/products/signals/backend/receivers.py@@ -28,7 +28,6 @@ from products.signals.backend.report_embeddings import (emit_report_tombstone,render_report_documents,)-from products.signals.backend.scout_harness.suggestions import mark_stale_if_fleet_changedfrom products.signals.backend.suggested_reviewer_index import sync_suggested_reviewer_indexfrom products.tasks.backend.facade.task_run_signals import connect_task_run_post_save@@ -897,6 +896,13 @@ def mark_scout_suggestions_stale_on_fleet_change(sender: Any, instance: Any, **kif update_fields is not None and "enabled" not in update_fields:returntry:+ # Call-time import inside the guard: scout_harness reaches the tasks facade contracts+ # (pydantic-heavy), which must not load in every process at django.setup() just to wire+ # this receiver, and an import failure must not fail the config write either.+ from products.signals.backend.scout_harness.suggestions import (+ mark_stale_if_fleet_changed, # noqa: PLC0415 — keeps the heavy dep off the import path+ )+mark_stale_if_fleet_changed(instance.team_id)except Exception:logger.warning("scout_suggestions: failed to mark batch stale", team_id=instance.team_id, exc_info=True)