: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
perf(devex): cut setup-time import chains into the HogQL/schema layer (#62726)
Julian Bez3f26908c5044
diff --git a/ee/models/license.py b/ee/models/license.pyindex 9799559b3c11..2e683b34a83d 100644--- a/ee/models/license.py+++ b/ee/models/license.py@@ -11,7 +11,6 @@ from rest_framework import exceptions, statusfrom posthog.constants import AvailableFeaturefrom posthog.models.utils import sane_repr-from posthog.tasks.tasks import sync_all_organization_available_product_featuresclass LicenseError(exceptions.APIException):@@ -117,4 +116,8 @@ def get_licensed_users_available() -> Optional[int]:@receiver(post_save, sender=License)def license_saved(sender, instance: License, created: bool, raw: bool, using: str, **kwargs: object) -> None:+ # posthog.tasks.__init__ eagerly imports every task module (celery autoimport);+ # this model loads at django.setup(), so keep the task graph off the module level.+ from posthog.tasks.tasks import sync_all_organization_available_product_features # noqa: PLC0415+sync_all_organization_available_product_features()diff --git a/posthog/apps.py b/posthog/apps.pyindex 35079e3783eb..ce1c37643ab1 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -9,7 +9,6 @@ from asgiref.sync import async_to_syncfrom posthoganalytics.client import Clientfrom posthog.git import get_git_branch, get_git_commit_short-from posthog.tasks.tasks import sync_all_organization_available_product_featuresfrom posthog.utils import (get_available_timezones_with_offsets,get_dogfood_flags_team_id,@@ -80,6 +79,11 @@ class PostHogConfig(AppConfig):# log development server launch to posthogif os.getenv("RUN_MAIN") == "true":+ # posthog.tasks.__init__ is a celery autoimport aggregator: importing any+ # submodule loads every task module. Keep that off django.setup() for all+ # processes; celery workers get it via autodiscover_tasks().+ from posthog.tasks.tasks import sync_all_organization_available_product_features # noqa: PLC0415+# Sync all organization.available_product_features once on launch, in case plans changedsync_all_organization_available_product_features()diff --git a/posthog/celery_queues.py b/posthog/celery_queues.pynew file mode 100644index 000000000000..d7bf7d7ccdea--- /dev/null+++ b/posthog/celery_queues.py@@ -0,0 +1,43 @@+# NOTE: These are the queues used for logically separating workloads.+# Many queues are consumed by one "consumer" - a worker configured to consume from that queue.+# The goal should be to split up queues based on the type of work being done, so that we can scale effectively+# and change the consumer configs without the need for code changes+#+# Worker consumers config here https://github.com/PostHog/charts/blob/main/config/posthog/prod-us.yaml.gotmpl#L538+# e.g.+# consumers:+# - name: priority+# queues:+# - stats+# - name: default+# concurrency: 4+# queues:+# - celery # default queue for Celery+# - name: async+# concurrency: 4+# queues:+# - analytics_queries+# - subscriptions+#+# This module must stay import-light: queue names are needed at decorator-eval time by+# modules that load during django.setup(), and the posthog.tasks package (the enum's old+# home) eagerly imports every task module on first touch.++# NOTE: Keep in sync with bin/celery-queues.env+from enum import Enum+++class CeleryQueue(Enum):+ DEFAULT = "celery"+ STATS = "stats"+ EMAIL = "email"+ LONG_RUNNING = "long_running" # any task that has a good chance of taking more than a few seconds should go here+ ANALYTICS_QUERIES = "analytics_queries"+ ANALYTICS_LIMITED = "analytics_limited"+ EXPORTS = "exports"+ SUBSCRIPTION_DELIVERY = "subscription_delivery"+ USAGE_REPORTS = "usage_reports"+ INTEGRATIONS = "integrations"+ FEATURE_FLAGS = "feature_flags"+ FEATURE_FLAGS_LONG_RUNNING = "feature_flags_long_running"diff --git a/posthog/clickhouse/client/__init__.py b/posthog/clickhouse/client/__init__.pyindex a249ebbabb4a..f98391c75b55 100644--- a/posthog/clickhouse/client/__init__.py+++ b/posthog/clickhouse/client/__init__.py@@ -1,8 +1,22 @@+from typing import TYPE_CHECKING+from posthog.clickhouse.client.execute import query_with_columns, sync_execute-from posthog.clickhouse.client.execute_async import execute_process_query++if TYPE_CHECKING:+ from posthog.clickhouse.client.execute_async import execute_process_query__all__ = ["sync_execute","query_with_columns","execute_process_query",]+++# execute_async imports the schema/celery layers, and this package loads at django.setup()+# (async_migrations, kafka client). PEP 562 keeps the lazy name working for consumers.+def __getattr__(name: str) -> object:+ if name == "execute_process_query":+ from posthog.clickhouse.client.execute_async import execute_process_query # noqa: PLC0415++ return execute_process_query+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.pyindex f6f30da7f801..ae1ed6aca774 100644--- a/posthog/clickhouse/client/execute_async.py+++ b/posthog/clickhouse/client/execute_async.py@@ -20,7 +20,6 @@ from posthog.clickhouse.query_tagging import get_query_tags, tag_queriesfrom posthog.errors import CHQueryErrorTooManySimultaneousQueries, ExposedCHQueryErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.renderers import SafeJSONRenderer-from posthog.tasks.tasks import process_query_taskif TYPE_CHECKING:from posthog.event_usage import AnalyticsProps@@ -338,6 +337,10 @@ def enqueue_process_query_task(except Exception as e:capture_exception(e, {"cache_key": cache_key})+ # posthog.tasks.__init__ eagerly imports every task module (celery autoimport), and this+ # module loads at django.setup() via posthog.clickhouse.client — keep the task graph off it.+ from posthog.tasks.tasks import process_query_task # noqa: PLC0415+limit_context = LimitContext.POSTHOG_AI if is_posthog_ai else LimitContext.QUERY_ASYNCtask_signature = process_query_task.si(team.id,diff --git a/posthog/email.py b/posthog/email.pyindex 864ecc7d63a4..30a2353d523a 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -25,11 +25,11 @@ import posthoganalyticsfrom celery import shared_taskfrom lxml import html as lxml_html+from posthog.celery_queues import CeleryQueuefrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import sanitize_email_stringfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.messaging import MessagingRecord-from posthog.tasks.utils import CeleryQueuedef inline_css(value: str) -> str:diff --git a/posthog/hogql/context.py b/posthog/hogql/context.pyindex c7308f021688..b6281ed4b0cb 100644--- a/posthog/hogql/context.py+++ b/posthog/hogql/context.py@@ -2,14 +2,14 @@ from dataclasses import dataclass, fieldfrom functools import cached_propertyfrom typing import TYPE_CHECKING, Any, Literal, Optional-from posthog.schema import DataWarehouseSyncWarning, HogQLNotice, HogQLQueryModifiers-from posthog.hogql.constants import LimitContextfrom posthog.hogql.timings import HogQLTimingsfrom posthog.clickhouse.workload import Workloadif TYPE_CHECKING:+ from posthog.schema import DataWarehouseSyncWarning, HogQLNotice, HogQLQueryModifiers+from posthog.hogql.database.database import Databasefrom posthog.hogql.observability import HogQLTypeObservabilityfrom posthog.hogql.transforms.property_types import PropertySwapper@@ -17,6 +17,14 @@ if TYPE_CHECKING:from posthog.models import Team, User+def _default_modifiers() -> "HogQLQueryModifiers":+ # Deferred: posthog.schema (the pydantic models) stays off django.setup(); this module+ # loads there via the legacy filter classes and the warehouse models.+ from posthog.schema import HogQLQueryModifiers # noqa: PLC0415++ return HogQLQueryModifiers()++@dataclassclass HogQLFieldAccess:input: list[str]@@ -73,7 +81,7 @@ class HogQLContext:# Timings in seconds for different parts of the HogQL querytimings: HogQLTimings = field(default_factory=HogQLTimings)# Modifications requested by the HogQL client- modifiers: HogQLQueryModifiers = field(default_factory=HogQLQueryModifiers)+ modifiers: "HogQLQueryModifiers" = field(default_factory=_default_modifiers)# Enables more verbose output for debuggingdebug: bool = False# Internal optimizer flag. Keep disabled until typed rewrites have broader compatibility coverage.@@ -114,6 +122,8 @@ class HogQLContext:fix: Optional[str] = None,):if not any(n.start == start and n.end == end and n.message == message and n.fix == fix for n in self.notices):+ from posthog.schema import HogQLNotice # noqa: PLC0415+self.notices.append(HogQLNotice(start=start, end=end, message=message, fix=fix))def add_warning(@@ -124,6 +134,8 @@ class HogQLContext:fix: Optional[str] = None,):if not any(n.start == start and n.end == end and n.message == message and n.fix == fix for n in self.warnings):+ from posthog.schema import HogQLNotice # noqa: PLC0415+self.warnings.append(HogQLNotice(start=start, end=end, message=message, fix=fix))def add_error(@@ -134,6 +146,8 @@ class HogQLContext:fix: Optional[str] = None,):if not any(n.start == start and n.end == end and n.message == message and n.fix == fix for n in self.errors):+ from posthog.schema import HogQLNotice # noqa: PLC0415+self.errors.append(HogQLNotice(start=start, end=end, message=message, fix=fix))def add_data_warehouse_sync_warning(self, table_id: str, warning: "DataWarehouseSyncWarning") -> None:diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex cd1341bf13c6..2250ab8313ae 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -14,23 +14,6 @@ import posthoganalyticsfrom opentelemetry import tracefrom pydantic import BaseModel, ConfigDict-from posthog.schema import (- DatabaseSchemaDataWarehouseTable,- DatabaseSchemaEndpointTable,- DatabaseSchemaField,- DatabaseSchemaManagedViewTable,- DatabaseSchemaPostHogTable,- DatabaseSchemaSchema,- DatabaseSchemaSource,- DatabaseSchemaSystemTable,- DatabaseSchemaViewTable,- DatabaseSerializedFieldType,- HogQLQuery,- HogQLQueryModifiers,- PersonsOnEventsMode,- SessionTableVersion,-)-from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.direct_postgres_table import DirectPostgresTable@@ -155,6 +138,7 @@ from posthog.models.group_type_mapping import get_group_types_for_projectfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Team, WeekStartDayfrom posthog.rbac.user_access_control import NO_ACCESS_LEVEL, UserAccessControl+from posthog.schema_enums import DatabaseSerializedFieldType, PersonsOnEventsMode, SessionTableVersionfrom posthog.synthetic_user import SyntheticUserfrom products.data_tools.backend.models.join import DataWarehouseJoin@@ -166,8 +150,20 @@ from products.warehouse_sources.backend.models.external_data_schema import Exterfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable, DataWarehouseTableColumns+# posthog.schema (the pydantic models) is runtime-imported inside serialize()/serialize_fields()+# so it stays off django.setup(), where this module loads via the warehouse/data-modeling models.if TYPE_CHECKING:- from posthog.schema import DataWarehouseSyncWarning+ from posthog.schema import (+ DatabaseSchemaDataWarehouseTable,+ DatabaseSchemaEndpointTable,+ DatabaseSchemaField,+ DatabaseSchemaManagedViewTable,+ DatabaseSchemaPostHogTable,+ DatabaseSchemaSystemTable,+ DatabaseSchemaViewTable,+ DataWarehouseSyncWarning,+ HogQLQueryModifiers,+ )from posthog.models import User@@ -195,7 +191,7 @@ class HogQLDatabaseSources:team: "Team"user: Optional["User | SyntheticUser"]connection_id: str | None- modifiers: HogQLQueryModifiers+ modifiers: "HogQLQueryModifiers"is_managed_viewset_enabled: boolis_hogql_access_control_enabled: booldirect_connection_metadata: dict[str, Any] | None@@ -689,6 +685,18 @@ class Database(BaseModel):include_only: set[str] | None = None,include_hidden_posthog_tables: bool = False,) -> dict[str, DatabaseSchemaTable]:+ from posthog.schema import ( # noqa: PLC0415+ DatabaseSchemaDataWarehouseTable,+ DatabaseSchemaEndpointTable,+ DatabaseSchemaManagedViewTable,+ DatabaseSchemaPostHogTable,+ DatabaseSchemaSchema,+ DatabaseSchemaSource,+ DatabaseSchemaSystemTable,+ DatabaseSchemaViewTable,+ HogQLQuery,+ )+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuerytables: dict[str, DatabaseSchemaTable] = {}@@ -923,7 +931,7 @@ class Database(BaseModel):*,team: Optional["Team"] = None,user: Optional["User | SyntheticUser"] = None,- modifiers: HogQLQueryModifiers | None = None,+ modifiers: "HogQLQueryModifiers | None" = None,timings: HogQLTimings | None = None,connection_id: str | None = None,) -> "Database":@@ -946,7 +954,7 @@ class Database(BaseModel):*,team: Optional["Team"] = None,user: Optional["User | SyntheticUser"] = None,- modifiers: HogQLQueryModifiers | None = None,+ modifiers: "HogQLQueryModifiers | None" = None,timings: HogQLTimings | None = None,connection_id: str | None = None,) -> HogQLDatabaseSources:@@ -1806,7 +1814,7 @@ def _setup_group_key_fields(database: Database, group_types: list[dict[str, Any])-def _use_virtual_fields(database: Database, modifiers: HogQLQueryModifiers, timings: HogQLTimings) -> None:+def _use_virtual_fields(database: Database, modifiers: "HogQLQueryModifiers", timings: HogQLTimings) -> None:events_table = database.get_table("events")persons_table = database.get_table("persons")groups_table = database.get_table("groups")@@ -2045,7 +2053,9 @@ def serialize_fields(table_chain: list[str],db_columns: DataWarehouseTableColumns | None = None,table_type: Literal["posthog"] | Literal["external"] = "posthog",-) -> list[DatabaseSchemaField]:+) -> list["DatabaseSchemaField"]:+ from posthog.schema import DatabaseSchemaField # noqa: PLC0415+from posthog.hogql.resolver import resolve_types_from_tablefield_output: list[DatabaseSchemaField] = []diff --git a/posthog/hogql/database/schema/channel_type.py b/posthog/hogql/database/schema/channel_type.pyindex 14a2be5816bd..926d271c5bab 100644--- a/posthog/hogql/database/schema/channel_type.py+++ b/posthog/hogql/database/schema/channel_type.py@@ -1,8 +1,11 @@from dataclasses import dataclassfrom functools import cache-from typing import Optional, Union+from typing import TYPE_CHECKING, Optional, Union-from posthog.schema import CustomChannelField, CustomChannelOperator, CustomChannelRule, DefaultChannelTypes+from posthog.schema_enums import CustomChannelField, CustomChannelOperator, DefaultChannelTypes++if TYPE_CHECKING:+ from posthog.schema import CustomChannelRulefrom posthog.hogql import astfrom posthog.hogql.database.models import ExpressionField@@ -80,7 +83,7 @@ if(def create_initial_channel_type(name: str,- custom_rules: Optional[list[CustomChannelRule]] = None,+ custom_rules: Optional[list["CustomChannelRule"]] = None,timings: Optional[HogQLTimings] = None,properties_path: Optional[list[str]] = None,) -> ExpressionField:@@ -189,7 +192,7 @@ def custom_condition_to_expr(raise NotImplementedError(f"PropertyOperator {operator} not implemented")-def custom_rule_to_expr(custom_rule: CustomChannelRule, source_exprs: ChannelTypeExprs) -> ast.Expr:+def custom_rule_to_expr(custom_rule: "CustomChannelRule", source_exprs: ChannelTypeExprs) -> ast.Expr:conditions: list[Union[ast.Expr | ast.Call]] = []for condition in custom_rule.items:if condition.key == CustomChannelField.UTM_SOURCE:@@ -229,7 +232,7 @@ def custom_rule_to_expr(custom_rule: CustomChannelRule, source_exprs: ChannelTypdef create_channel_type_expr(- custom_rules: Optional[list[CustomChannelRule]],+ custom_rules: Optional[list["CustomChannelRule"]],source_exprs: ChannelTypeExprs,timings: Optional[HogQLTimings] = None,) -> ast.Expr:diff --git a/posthog/hogql/database/schema/exchange_rate.py b/posthog/hogql/database/schema/exchange_rate.pyindex 8250dcfdfc3f..cd6ab8af3983 100644--- a/posthog/hogql/database/schema/exchange_rate.py+++ b/posthog/hogql/database/schema/exchange_rate.py@@ -1,4 +1,4 @@-from posthog.schema import RevenueAnalyticsEventItem+from typing import TYPE_CHECKINGfrom posthog.hogql import astfrom posthog.hogql.database.models import (@@ -12,6 +12,9 @@ from posthog.hogql.database.models import (from posthog.models.exchange_rate.sql import EXCHANGE_RATE_DECIMAL_PRECISIONfrom posthog.models.team.team import Team+if TYPE_CHECKING:+ from posthog.schema import RevenueAnalyticsEventItem+class ExchangeRateTable(DANGEROUS_NoTeamIdCheckTable):fields: dict[str, FieldOrTable] = {@@ -42,7 +45,7 @@ def convert_currency_call(# Given an event config and the base config, figure out what the currency should look like-def currency_expression_for_events(team: Team, event_config: RevenueAnalyticsEventItem) -> ast.Expr:+def currency_expression_for_events(team: Team, event_config: "RevenueAnalyticsEventItem") -> ast.Expr:# Shouldn't happen but we need it here to make the type checker happyif not event_config.revenueCurrencyProperty:return ast.Constant(value=team.base_currency)@@ -64,7 +67,7 @@ def currency_expression_for_events(team: Team, event_config: RevenueAnalyticsEve# - Convert the revenue to the base currency if neededdef revenue_comparison_and_value_exprs_for_events(team: Team,- event_config: RevenueAnalyticsEventItem,+ event_config: "RevenueAnalyticsEventItem",do_currency_conversion: bool = True,amount_expr: ast.Expr | None = None,) -> tuple[ast.Expr, ast.Expr]:diff --git a/posthog/hogql/database/schema/sessions_v2.py b/posthog/hogql/database/schema/sessions_v2.pyindex 6f7d3a3edb60..875e01a49135 100644--- a/posthog/hogql/database/schema/sessions_v2.py+++ b/posthog/hogql/database/schema/sessions_v2.py@@ -1,8 +1,6 @@import refrom typing import TYPE_CHECKING, Optional, cast-from posthog.schema import BounceRatePageViewMode, CustomChannelRule, SessionsV2JoinMode-from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.models import (@@ -34,10 +32,13 @@ from posthog.models.raw_sessions.sessions_v2 import (RAW_SELECT_SESSION_PROP_STRING_VALUES_SQL_WITH_FILTER,)from posthog.queries.insight import insight_sync_execute+from posthog.schema_enums import BounceRatePageViewMode, SessionsV2JoinModefrom products.event_definitions.backend.models.property_definition import PropertyTypeif TYPE_CHECKING:+ from posthog.schema import CustomChannelRule+from posthog.models.team import TeamRAW_SESSIONS_FIELDS: dict[str, FieldOrTable] = {diff --git a/posthog/hogql/database/schema/sessions_v3.py b/posthog/hogql/database/schema/sessions_v3.pyindex 345b8e76380e..bd8ff231b123 100644--- a/posthog/hogql/database/schema/sessions_v3.py+++ b/posthog/hogql/database/schema/sessions_v3.py@@ -1,8 +1,6 @@import refrom typing import TYPE_CHECKING, Optional, cast-from posthog.schema import CustomChannelRule-from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.models import (@@ -36,6 +34,8 @@ from posthog.queries.insight import insight_sync_executefrom products.event_definitions.backend.models.property_definition import PropertyTypeif TYPE_CHECKING:+ from posthog.schema import CustomChannelRule+from posthog.models.team import Teamdiff --git a/posthog/hogql/modifiers.py b/posthog/hogql/modifiers.pyindex a3587cfb64af..8c9af2ce647f 100644--- a/posthog/hogql/modifiers.py+++ b/posthog/hogql/modifiers.py@@ -1,12 +1,10 @@from typing import TYPE_CHECKING, Optionalimport posthoganalytics-from pydantic import ValidationError-from posthog.schema import (+from posthog.cloud_utils import is_cloud+from posthog.schema_enums import (BounceRatePageViewMode,- CustomChannelRule,- HogQLQueryModifiers,InCohortVia,InlineCohortCalculation,MaterializationMode,@@ -16,15 +14,19 @@ from posthog.schema import (SessionTableVersion,)-from posthog.cloud_utils import is_cloud-+# This module loads at django.setup() via Team; posthog.schema (the pydantic models) is+# runtime-imported in the functions that build modifier objects to keep it off that path.if TYPE_CHECKING:+ from posthog.schema import HogQLQueryModifiers+from posthog.models import Team, Userdef create_default_modifiers_for_user(- user: "User", team: "Team", modifiers: Optional[HogQLQueryModifiers] = None-) -> HogQLQueryModifiers:+ user: "User", team: "Team", modifiers: Optional["HogQLQueryModifiers"] = None+) -> "HogQLQueryModifiers":+ from posthog.schema import HogQLQueryModifiers # noqa: PLC0415+if modifiers is None:modifiers = HogQLQueryModifiers()else:@@ -44,8 +46,12 @@ def create_default_modifiers_for_user(def create_default_modifiers_for_team(- team: "Team", modifiers: Optional[HogQLQueryModifiers] = None-) -> HogQLQueryModifiers:+ team: "Team", modifiers: Optional["HogQLQueryModifiers"] = None+) -> "HogQLQueryModifiers":+ from pydantic import ValidationError # noqa: PLC0415++ from posthog.schema import CustomChannelRule, HogQLQueryModifiers # noqa: PLC0415+if modifiers is None:modifiers = HogQLQueryModifiers()else:@@ -76,7 +82,7 @@ def create_default_modifiers_for_team(return modifiers-def set_default_modifier_values(modifiers: HogQLQueryModifiers, team: "Team"):+def set_default_modifier_values(modifiers: "HogQLQueryModifiers", team: "Team"):if modifiers.personsOnEventsMode is None:modifiers.personsOnEventsMode = team.person_on_events_mode_flag_based_default@@ -120,7 +126,7 @@ def set_default_modifier_values(modifiers: HogQLQueryModifiers, team: "Team"):modifiers.sessionPropertyPreAggregation = False-def set_default_in_cohort_via(modifiers: HogQLQueryModifiers) -> HogQLQueryModifiers:+def set_default_in_cohort_via(modifiers: "HogQLQueryModifiers") -> "HogQLQueryModifiers":if modifiers.inCohortVia is None or modifiers.inCohortVia == InCohortVia.AUTO:modifiers.inCohortVia = InCohortVia.SUBQUERYdiff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex c98ea10d5792..49246100aabf 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -1,6 +1,9 @@-from typing import cast+from typing import TYPE_CHECKING, cast-from posthog.schema import HogQLQueryModifiers, InCohortVia+from posthog.schema_enums import InCohortVia++if TYPE_CHECKING:+ from posthog.schema import HogQLQueryModifiersfrom posthog.hogql import astfrom posthog.hogql.base import _T_AST@@ -38,7 +41,7 @@ from posthog.models.team import Teamfrom products.access_control.backend.property_access_control import get_restricted_properties_for_team-def to_printed_hogql(query: ast.Expr, team: Team, modifiers: HogQLQueryModifiers | None = None) -> str:+def to_printed_hogql(query: ast.Expr, team: Team, modifiers: "HogQLQueryModifiers | None" = None) -> str:"""Prints the HogQL query without mutating the node"""return prepare_and_print_ast(clone_expr(query),diff --git a/posthog/hogql/property_planner.py b/posthog/hogql/property_planner.pyindex 38133664b3f9..6301f3ce4d87 100644--- a/posthog/hogql/property_planner.py+++ b/posthog/hogql/property_planner.py@@ -3,8 +3,6 @@ from dataclasses import dataclassfrom enum import StrEnumfrom typing import Literal, Optional, cast-from posthog.schema import PropertyGroupsMode-from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.models import DatabaseField@@ -33,6 +31,7 @@ from posthog.clickhouse.materialized_columns import ()from posthog.clickhouse.property_groups import property_groupsfrom posthog.models.property import PropertyName, TableColumn+from posthog.schema_enums import PropertyGroupsModefrom products.event_definitions.backend.models.property_definition import PropertyTypediff --git a/posthog/hogql/resolver_utils.py b/posthog/hogql/resolver_utils.pyindex db673b45a36a..7d1050f3949c 100644--- a/posthog/hogql/resolver_utils.py+++ b/posthog/hogql/resolver_utils.py@@ -28,8 +28,6 @@ from posthog.hogql.database.models import ()from posthog.hogql.errors import QueryError, ResolutionError, SyntaxError-from posthog import schema-def lookup_field_by_name(scope: ast.SelectQueryType | ast.SelectSetQueryType, name: str, context: HogQLContext@@ -221,6 +219,10 @@ def ast_to_query_node(expr: ast.Expr | ast.HogQLXTag):elif isinstance(expr, ast.Tuple):return tuple(ast_to_query_node(e) for e in expr.exprs)elif isinstance(expr, ast.HogQLXTag):+ # Deferred: posthog.schema stays off django.setup(); this module loads there via+ # hogql.ast, which the warehouse/data-modeling models import.+ from posthog import schema # noqa: PLC0415+for klass in schema.__dict__.values():if isinstance(klass, type) and issubclass(klass, BaseModel) and klass.__name__ == expr.kind:attributes = expr.to_dict()diff --git a/posthog/hogql/timings.py b/posthog/hogql/timings.pyindex 94b4c95a2bcf..870e84670761 100644--- a/posthog/hogql/timings.py+++ b/posthog/hogql/timings.py@@ -1,9 +1,11 @@from contextlib import contextmanager, nullcontextfrom time import perf_counter+from typing import TYPE_CHECKINGfrom opentelemetry import trace-from posthog.schema import QueryTiming+if TYPE_CHECKING:+ from posthog.schema import QueryTiming_tracer = trace.get_tracer(__name__)@@ -53,7 +55,11 @@ class HogQLTimings:timings[key] = round(timings.get(key, 0.0) + (perf_counter() - start), TIMING_DECIMAL_PLACES)return timings- def to_list(self, back_out_stack=True) -> list[QueryTiming]:+ def to_list(self, back_out_stack=True) -> list["QueryTiming"]:+ # Deferred: posthog.schema stays off django.setup(); this module loads there via+ # hogql.context.+ from posthog.schema import QueryTiming # noqa: PLC0415+return [QueryTiming(k=key, t=round(time, TIMING_DECIMAL_PLACES))for key, time in (self.to_dict() if back_out_stack else self.timings).items()diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.pyindex 334cf9c5e5ef..8dffd8bca325 100644--- a/posthog/hogql/transforms/clickhouse_property_resolution.py+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py@@ -24,8 +24,6 @@ exist in the blob" test, but tightening it would change query results.from dataclasses import dataclassfrom typing import Literal, cast-from posthog.schema import MaterializationMode, PropertyGroupsMode-from posthog.hogql import astfrom posthog.hogql.base import _T_ASTfrom posthog.hogql.context import HogQLContext@@ -48,6 +46,7 @@ from posthog.hogql.visitor import CloningVisitorfrom posthog.clickhouse.materialized_columns import TablesWithMaterializedColumns, get_materialized_column_for_propertyfrom posthog.clickhouse.property_groups import property_groupsfrom posthog.models.property import PropertyName, TableColumn+from posthog.schema_enums import MaterializationMode, PropertyGroupsMode# In non-nullable materialized columns these stored strings are treated as NULL.MAT_COL_NULL_SENTINELS = ["", "null"]diff --git a/posthog/hogql/transforms/events_predicate_pushdown.py b/posthog/hogql/transforms/events_predicate_pushdown.pyindex 69315aee8f7a..9db6fcbaea01 100644--- a/posthog/hogql/transforms/events_predicate_pushdown.py+++ b/posthog/hogql/transforms/events_predicate_pushdown.py@@ -33,12 +33,10 @@ Two things are built by hand here, on purpose:wraps in `ifNull(...)` only when the value is genuinely nullable."""-from typing import cast+from typing import TYPE_CHECKING, castimport structlog-from posthog.schema import HogQLQueryModifiers-from posthog.hogql import astfrom posthog.hogql.base import _T_ASTfrom posthog.hogql.constants import LimitContext, get_max_limit_for_context@@ -51,10 +49,13 @@ from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_exprfrom posthog.settings import TEST+if TYPE_CHECKING:+ from posthog.schema import HogQLQueryModifiers+logger = structlog.get_logger(__name__)-def events_pushdown_enabled(modifiers: HogQLQueryModifiers) -> bool:+def events_pushdown_enabled(modifiers: "HogQLQueryModifiers") -> bool:"""Enabled when explicitly on, or unset under TEST. Shared by the call site and the transform."""return bool(modifiers.pushDownPredicates or (modifiers.pushDownPredicates is None and TEST))diff --git a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py b/posthog/hogql/transforms/test/test_events_predicate_pushdown.pyindex 28ca5e946445..ec88e0ce2208 100644--- a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py+++ b/posthog/hogql/transforms/test/test_events_predicate_pushdown.py@@ -19,7 +19,13 @@ from django.test import override_settingsfrom parameterized import parameterized-from posthog.schema import InCohortVia, InlineCohortCalculation, PersonsOnEventsMode, PropertyGroupsMode+from posthog.schema import (+ HogQLQueryModifiers,+ InCohortVia,+ InlineCohortCalculation,+ PersonsOnEventsMode,+ PropertyGroupsMode,+)from posthog.hogql import astfrom posthog.hogql.context import HogQLContext@@ -27,7 +33,6 @@ from posthog.hogql.database.database import Databasefrom posthog.hogql.database.models import IntegerDatabaseField, SavedQuery, StringDatabaseField, TableNodefrom posthog.hogql.database.schema.events import EventsTablefrom posthog.hogql.database.schema.util.where_clause_extractor import EventsPredicatePushdownExtractor-from posthog.hogql.modifiers import HogQLQueryModifiersfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer.utils import prepare_and_print_astfrom posthog.hogql.query import execute_hogql_querydiff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex b4665730eeb8..7da477f75534 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -18,10 +18,11 @@ from django.test import override_settingsfrom parameterized import parameterized+from posthog.schema import HogQLQueryModifiers+from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Database-from posthog.hogql.modifiers import HogQLQueryModifiersfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.property_planner import (diff --git a/posthog/models/entity/entity.py b/posthog/models/entity/entity.pyindex 6ee1e8915597..8779f024d405 100644--- a/posthog/models/entity/entity.py+++ b/posthog/models/entity/entity.py@@ -1,13 +1,11 @@import inspectfrom collections import Counter-from typing import Any, Literal, Optional+from typing import TYPE_CHECKING, Any, Literal, Optionalfrom django.conf import settingsfrom rest_framework.exceptions import ValidationError-from posthog.schema import RevenueCurrencyPropertyConfig-from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE, TREND_FILTER_TYPE_EVENTSfrom posthog.models.filters.mixins.funnel import FunnelFromToStepsMixinfrom posthog.models.filters.mixins.property import PropertyMixin@@ -17,6 +15,9 @@ from posthog.models.utils import sane_reprfrom products.actions.backend.models.action import Action+if TYPE_CHECKING:+ from posthog.schema import RevenueCurrencyPropertyConfig+MathType = Literal["total","dau",@@ -61,7 +62,7 @@ class Entity(PropertyMixin):custom_name: Optional[str]math: Optional[MathType]math_property: Optional[str]- math_property_revenue_currency: Optional[RevenueCurrencyPropertyConfig]+ math_property_revenue_currency: Optional["RevenueCurrencyPropertyConfig"]math_hogql: Optional[str]math_group_type_index: Optional[GroupTypeIndex]# Index is not set at all by default (meaning: access = AttributeError) - it's populated in EntitiesMixin.entitiesdiff --git a/posthog/models/filters/base_filter.py b/posthog/models/filters/base_filter.pyindex 3dd7a950d42d..dea97226b047 100644--- a/posthog/models/filters/base_filter.py+++ b/posthog/models/filters/base_filter.py@@ -5,8 +5,6 @@ from typing import TYPE_CHECKING, Any, Optionalfrom rest_framework import requestfrom rest_framework.exceptions import ValidationError-from posthog.hogql.context import HogQLContext-from posthog.constants import PROPERTIESfrom posthog.models.utils import sane_reprfrom posthog.utils import encode_get_request_params@@ -14,6 +12,8 @@ from posthog.utils import encode_get_request_paramsfrom .mixins.common import BaseParamMixinif TYPE_CHECKING:+ from posthog.hogql.context import HogQLContext+from posthog.models.team.team import Team@@ -21,7 +21,7 @@ class BaseFilter(BaseParamMixin):_data: dictteam: Optional["Team"]kwargs: dict- hogql_context: HogQLContext+ hogql_context: "HogQLContext"def __init__(self,@@ -54,6 +54,10 @@ class BaseFilter(BaseParamMixin):self.kwargs = kwargsself.team = team+ # Deferred: hogql.context pulls the HogQL/schema layer, and the legacy filter+ # classes load at django.setup() in every process via the models package.+ from posthog.hogql.context import HogQLContext # noqa: PLC0415+# Set the HogQL context for the requestself.hogql_context = self.kwargs.get("hogql_context",diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 9117ec116cef..9c94ef4206d1 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -37,8 +37,6 @@ from rest_framework.request import Requestfrom slack_sdk import WebClientfrom slack_sdk.errors import SlackApiError-from posthog.schema import SlackIntegrationScope, SlackIntegrationScopeInReview-from posthog.cache_utils import cache_forfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.encrypted_fields import EncryptedJSONField@@ -50,6 +48,7 @@ from posthog.models.user import Userfrom posthog.models.utils import IntegrityError, generate_random_oauth_access_token, generate_random_oauth_refresh_tokenfrom posthog.plugins.plugin_server_api import reload_integrations_on_workersfrom posthog.rbac.decorators import field_access_control+from posthog.schema_enums import SlackIntegrationScope, SlackIntegrationScopeInReviewfrom posthog.security.url_validation import is_url_allowedfrom posthog.sync import database_sync_to_asyncfrom posthog.utils import get_instance_regiondiff --git a/posthog/models/team/team.py b/posthog/models/team/team.pyindex 42cd61000e98..2fe60f737e96 100644--- a/posthog/models/team/team.py+++ b/posthog/models/team/team.py@@ -43,11 +43,13 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_templates import DashboardTemplatefrom ...hogql.modifiers import set_default_modifier_values-from ...schema import CurrencyCode, HogQLQueryModifiers, PathCleaningFilter, PersonsOnEventsMode+from ...schema_enums import CurrencyCode, PersonsOnEventsModefrom .extensions import get_or_create_team_extensionfrom .team_caching import get_team_in_cache, set_team_in_cacheif TYPE_CHECKING:+ from posthog.schema import PathCleaningFilter+from posthog.models.user import UserTIMEZONES = [(tz, tz) for tz in pytz.all_timezones]@@ -742,6 +744,10 @@ class Team(UUIDTClassicModel):@propertydef default_modifiers(self) -> dict:+ # Deferred: posthog.schema (the pydantic models) stays off django.setup(),+ # where this model loads in every process.+ from posthog.schema import HogQLQueryModifiers # noqa: PLC0415+modifiers = HogQLQueryModifiers()set_default_modifier_values(modifiers, self)return modifiers.model_dump()@@ -871,7 +877,9 @@ class Team(UUIDTClassicModel):def timezone_info(self) -> ZoneInfo:return ZoneInfo(self.timezone)- def path_cleaning_filter_models(self) -> list[PathCleaningFilter]:+ def path_cleaning_filter_models(self) -> list["PathCleaningFilter"]:+ from posthog.schema import PathCleaningFilter # noqa: PLC0415+filters = []for f in self.path_cleaning_filters:try:diff --git a/posthog/models/team/team_marketing_analytics_config.py b/posthog/models/team/team_marketing_analytics_config.pyindex d86f001bb712..3480d46a0b4b 100644--- a/posthog/models/team/team_marketing_analytics_config.py+++ b/posthog/models/team/team_marketing_analytics_config.py@@ -1,13 +1,18 @@import logging+from typing import TYPE_CHECKINGfrom django.core.exceptions import ValidationErrorfrom django.db import models-from posthog.schema import AttributionMode, NodeKind, SourceMap-from posthog.models.team import Teamfrom posthog.models.team.extensions import register_team_extension_signalfrom posthog.rbac.decorators import field_access_control+from posthog.schema_enums import AttributionMode, NodeKind++# This model loads at django.setup() in every process; posthog.schema (the pydantic models)+# is runtime-imported in the accessors that materialize typed objects.+if TYPE_CHECKING:+ from posthog.schema import SourceMap# ruff: noqa: DJ012 # Properties act as field accessors for mangled DB fields, so they need to come before save()@@ -347,8 +352,10 @@ class TeamMarketingAnalyticsConfig(models.Model):raise ValidationError(f"Invalid sources map schema: {str(e)}")@property- def sources_map_typed(self) -> dict[str, SourceMap]:+ def sources_map_typed(self) -> dict[str, "SourceMap"]:"""Return sources_map as typed SourceMap objects for Python usage"""+ from posthog.schema import SourceMap # noqa: PLC0415+response = {}for source_id, field_mapping in self._sources_map.items():if field_mapping is None:diff --git a/posthog/models/team/team_revenue_analytics_config.py b/posthog/models/team/team_revenue_analytics_config.pyindex da989327b0ab..44919231060f 100644--- a/posthog/models/team/team_revenue_analytics_config.py+++ b/posthog/models/team/team_revenue_analytics_config.py@@ -1,15 +1,19 @@import logging+from typing import TYPE_CHECKINGfrom django.core.exceptions import ValidationErrorfrom django.db import models-from posthog.schema import RevenueAnalyticsEventItem, RevenueAnalyticsGoal-from posthog.models.team import Teamfrom posthog.models.team.extensions import register_team_extension_signalfrom posthog.models.team.team import CURRENCY_CODE_CHOICES, DEFAULT_CURRENCYfrom posthog.rbac.decorators import field_access_control+# This model loads at django.setup() in every process; posthog.schema (the pydantic models)+# is runtime-imported in the accessors that materialize typed objects.+if TYPE_CHECKING:+ from posthog.schema import RevenueAnalyticsEventItem, RevenueAnalyticsGoal+logger = logging.getLogger(__name__)@@ -32,11 +36,15 @@ class TeamRevenueAnalyticsConfig(models.Model):base_currency = models.CharField(max_length=3, choices=CURRENCY_CODE_CHOICES, default=DEFAULT_CURRENCY)@property- def events(self) -> list[RevenueAnalyticsEventItem]:+ def events(self) -> list["RevenueAnalyticsEventItem"]:+ from posthog.schema import RevenueAnalyticsEventItem # noqa: PLC0415+return [RevenueAnalyticsEventItem.model_validate(event) for event in self._events or []]@events.setterdef events(self, value: list[dict]) -> None:+ from posthog.schema import RevenueAnalyticsEventItem # noqa: PLC0415+value = value or []try:dumped_value = [RevenueAnalyticsEventItem.model_validate(event).model_dump() for event in value]@@ -50,11 +58,15 @@ class TeamRevenueAnalyticsConfig(models.Model):raise ValidationError(f"Invalid events schema: {str(e)}")@property- def goals(self) -> list[RevenueAnalyticsGoal]:+ def goals(self) -> list["RevenueAnalyticsGoal"]:+ from posthog.schema import RevenueAnalyticsGoal # noqa: PLC0415+return [RevenueAnalyticsGoal.model_validate(goal) for goal in self._goals or []]@goals.setterdef goals(self, value: list[dict]) -> None:+ from posthog.schema import RevenueAnalyticsGoal # noqa: PLC0415+value = value or []try:dumped_value = sorted(diff --git a/posthog/models/utils.py b/posthog/models/utils.pyindex 30024b748757..4c380f99afe5 100644--- a/posthog/models/utils.py+++ b/posthog/models/utils.py@@ -22,14 +22,14 @@ from django.db.models import Q, Subquery, UniqueConstraintfrom django.db.models.constraints import BaseConstraintfrom django.utils.text import slugify-from posthog.hogql import ast-from posthog.constants import MAX_SLUG_LENGTHfrom posthog.person_db_router import PERSONS_DB_MODELSif TYPE_CHECKING:from random import Random+ from posthog.hogql import ast+T = TypeVar("T")BASE62 = string.digits + string.ascii_letters # All lowercase ASCII letters + all uppercase ASCII letters + digits@@ -243,7 +243,7 @@ class BytecodeModelMixin(models.Model):self.bytecode = Noneself.bytecode_error = str(e)- def get_expr(self) -> ast.Expr:+ def get_expr(self) -> "ast.Expr":raise NotImplementedError()diff --git a/posthog/products.py b/posthog/products.pyindex 105d9988f935..3e1098fc52e4 100644--- a/posthog/products.py+++ b/posthog/products.py@@ -1,18 +1,23 @@import jsonfrom collections import defaultdictfrom pathlib import Path-from typing import Optional+from typing import TYPE_CHECKING, Optionalfrom django.conf import settings-from posthog.schema import ProductItem, ProductItemCategory, ProductKey, ProductsData+from posthog.schema_enums import ProductItemCategory, ProductKey++# This module loads at django.setup() via the file-system product list; posthog.schema+# (the pydantic models) is runtime-imported only when products.json is actually loaded.+if TYPE_CHECKING:+ from posthog.schema import ProductItem, ProductsDataclass Products:"""Singleton class to access products.json data with automatic reloading."""_instance: Optional["Products"] = None- _data: Optional[ProductsData] = None+ _data: Optional["ProductsData"] = None_file_path: Optional[Path] = Nonedef __new__(cls) -> "Products":@@ -30,6 +35,8 @@ class Products:def _load_data(self) -> None:"""Load products.json data from disk and validate with Pydantic."""+ from posthog.schema import ProductsData # noqa: PLC0415+if self._file_path is None or not self._file_path.exists():raise FileNotFoundError(f"products.json not found at {self._file_path}. Generate it by running: hogli build:products"@@ -46,7 +53,7 @@ class Products:instance._load_data()@staticmethod- def _get_data() -> ProductsData:+ def _get_data() -> "ProductsData":"""Get the loaded data, loading if necessary."""instance = Products()if instance._data is None:@@ -56,17 +63,17 @@ class Products:return instance._data@staticmethod- def products() -> list[ProductItem]:+ def products() -> list["ProductItem"]:"""Get the list of products."""return Products._get_data().products@staticmethod- def games() -> list[ProductItem]:+ def games() -> list["ProductItem"]:"""Get the list of games."""return Products._get_data().games@staticmethod- def metadata() -> list[ProductItem]:+ def metadata() -> list["ProductItem"]:"""Get the list of metadata items."""return Products._get_data().metadata@@ -76,7 +83,7 @@ class Products:return [product.path for product in Products.products()]@staticmethod- def get_products_by_intent(intent: ProductKey) -> list[ProductItem]:+ def get_products_by_intent(intent: ProductKey) -> list["ProductItem"]:"""Get all products that the intent is associated with."""return [product for product in Products.products() if intent in product.intents]diff --git a/posthog/queries/insight.py b/posthog/queries/insight.pyindex 3886fca93d43..55a29a8627f1 100644--- a/posthog/queries/insight.py+++ b/posthog/queries/insight.py@@ -1,11 +1,13 @@-from typing import Optional+from typing import TYPE_CHECKING, Optionalfrom rest_framework.exceptions import ValidationErrorfrom posthog.clickhouse.client import query_with_columns, sync_executefrom posthog.clickhouse.query_tagging import tag_queriesfrom posthog.errors import ExposedCHQueryError-from posthog.types import FilterType++if TYPE_CHECKING:+ from posthog.types import FilterType# Wrapper around sync_execute, adding query tags for insights performancediff --git a/posthog/session_recordings/models/session_recording.py b/posthog/session_recordings/models/session_recording.pyindex 94f2e790faa0..84d4b7869aa3 100644--- a/posthog/session_recordings/models/session_recording.py+++ b/posthog/session_recordings/models/session_recording.py@@ -17,7 +17,6 @@ from posthog.personhog_client.metrics import ()from posthog.session_recordings.models.metadata import RecordingMatchingEvents, RecordingMetadatafrom posthog.session_recordings.models.session_recording_event import SessionRecordingViewed-from posthog.session_recordings.queries.session_replay_events import SessionReplayEventslogger = structlog.get_logger(__name__)@@ -107,6 +106,10 @@ class SessionRecording(UUIDTModel):# Nothing todo as we have all the metadata in the modelpasselse:+ # Deferred: session_replay_events pulls the HogQL/schema layer, and this model+ # loads at django.setup() in every process.+ from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents # noqa: PLC0415+# Try to load from Clickhousemetadata = SessionReplayEvents().get_metadata(team=self.team,diff --git a/posthog/storage/team_llm_gateway_policy_signal_handlers.py b/posthog/storage/team_llm_gateway_policy_signal_handlers.pyindex b4dc384d380c..17ff21de9a17 100644--- a/posthog/storage/team_llm_gateway_policy_signal_handlers.py+++ b/posthog/storage/team_llm_gateway_policy_signal_handlers.py@@ -22,7 +22,6 @@ import structlogfrom posthog.models.team import Teamfrom posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTERfrom posthog.storage.team_llm_gateway_policy_cache import clear_team_llm_gateway_policy_cache-from posthog.tasks.team_llm_gateway_policy import update_team_llm_gateway_policy_cache_tasklogger = structlog.get_logger(__name__)@@ -126,6 +125,10 @@ def _update_cache_on_save(sender: type[Team], instance: Team, created: bool, **kinstance.__dict__[_LOADED_REVOKED_AT_ATTR] = new_revoked_atdef enqueue_task() -> None:+ # posthog.tasks.__init__ eagerly imports every task module (celery autoimport);+ # this signal module is wired at django.setup(), so import the task lazily.+ from posthog.tasks.team_llm_gateway_policy import update_team_llm_gateway_policy_cache_task # noqa: PLC0415+try:update_team_llm_gateway_policy_cache_task.delay(instance.id)kinds = ["redis"] if settings.TEST else Nonediff --git a/posthog/storage/test/test_team_llm_gateway_policy_cache.py b/posthog/storage/test/test_team_llm_gateway_policy_cache.pyindex 082fc4cf37ad..616d074a29e6 100644--- a/posthog/storage/test/test_team_llm_gateway_policy_cache.py+++ b/posthog/storage/test/test_team_llm_gateway_policy_cache.py@@ -114,7 +114,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_team_save_enqueues_update(self, mock_delay, mock_settings, mock_transaction):mock_settings.AI_GATEWAY_REDIS_URL = "redis://localhost"mock_transaction.on_commit.side_effect = lambda fn: fn()@@ -125,7 +125,7 @@ class TestLLMGatewayPolicySignals(BaseTest):mock_delay.assert_called_with(self.team.id)@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_team_save_noop_without_ai_gateway_redis_url(self, mock_delay, mock_settings):mock_settings.AI_GATEWAY_REDIS_URL = None@@ -148,7 +148,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_api_token_rotation_clears_old_token_cache(self, mock_delay, mock_clear, mock_settings, mock_transaction):"""Rotating api_token must invalidate the cache keyed by the OLD token.@@ -169,7 +169,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_unrelated_save_does_not_clear_cache(self, mock_delay, mock_clear, mock_settings, mock_transaction):"""A save that touches no tracked field (api_token, llm_gateway_enabled_at,llm_gateway_revoked_at) must not invalidate the cache; the async task still@@ -187,7 +187,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_setting_revoked_at_clears_current_token_cache_on_commit(self, mock_delay, mock_clear, mock_settings, mock_transaction):@@ -211,7 +211,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_setting_enabled_at_clears_current_token_cache_on_commit(self, mock_delay, mock_clear, mock_settings, mock_transaction):@@ -234,7 +234,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_chained_token_rotation_clears_each_old_token(self, mock_delay, mock_clear, mock_settings, mock_transaction):@@ -261,7 +261,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_deferred_api_token_load_still_clears_old_token_on_rotation(self, mock_delay, mock_clear, mock_settings, mock_transaction):@@ -286,7 +286,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_simultaneous_enable_and_revoke_clears_cache_once(self, mock_delay, mock_clear, mock_settings, mock_transaction):@@ -310,7 +310,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_deferred_enabled_at_load_still_clears_cache_on_flip(self, mock_delay, mock_clear, mock_settings, mock_transaction):@@ -334,7 +334,7 @@ class TestLLMGatewayPolicySignals(BaseTest):@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.transaction")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.settings")@patch("posthog.storage.team_llm_gateway_policy_signal_handlers.clear_team_llm_gateway_policy_cache")- @patch("posthog.storage.team_llm_gateway_policy_signal_handlers.update_team_llm_gateway_policy_cache_task.delay")+ @patch("posthog.tasks.team_llm_gateway_policy.update_team_llm_gateway_policy_cache_task.delay")def test_chained_enabled_at_flips_invalidate_each_save(self, mock_delay, mock_clear, mock_settings, mock_transaction):diff --git a/posthog/tasks/utils.py b/posthog/tasks/utils.pyindex 72d0a10ed964..b08657ce7fe4 100644--- a/posthog/tasks/utils.py+++ b/posthog/tasks/utils.py@@ -1,36 +1,14 @@-# NOTE: These are the queues used for logically separating workloads.-# Many queues are consumed by one "consumer" - a worker configured to consume from that queue.-# The goal should be to split up queues based on the type of work being done, so that we can scale effectively-# and change the consumer configs without the need for code changes-#-# Worker consumers config here https://github.com/PostHog/charts/blob/main/config/posthog/prod-us.yaml.gotmpl#L538-# e.g.-# consumers:-# - name: priority-# queues:-# - stats-# - name: default-# concurrency: 4-# queues:-# - celery # default queue for Celery-# - name: async-# concurrency: 4-# queues:-# - analytics_queries-# - subscriptions--import timeimport threading--# NOTE: Keep in sync with bin/celery-queues.env-from enum import Enumfrom typing import Anyfrom celery import Taskfrom prometheus_client import CollectorRegistry, Gauge+# Re-exported for the many existing `from posthog.tasks.utils import CeleryQueue` consumers.+# The enum lives in posthog.celery_queues so import-light modules can use it at decorator-eval+# time without triggering the posthog.tasks package init (which imports every task module).+from posthog.celery_queues import CeleryQueue as CeleryQueuefrom posthog.metrics import pushed_metrics_registry@@ -87,18 +65,3 @@ class PushGatewayTask(Task):finally:duration_gauge.set(time.monotonic() - start_time)self._local.registry = None---class CeleryQueue(Enum):- DEFAULT = "celery"- STATS = "stats"- EMAIL = "email"- LONG_RUNNING = "long_running" # any task that has a good chance of taking more than a few seconds should go here- ANALYTICS_QUERIES = "analytics_queries"- ANALYTICS_LIMITED = "analytics_limited"- EXPORTS = "exports"- SUBSCRIPTION_DELIVERY = "subscription_delivery"- USAGE_REPORTS = "usage_reports"- INTEGRATIONS = "integrations"- FEATURE_FLAGS = "feature_flags"- FEATURE_FLAGS_LONG_RUNNING = "feature_flags_long_running"diff --git a/posthog/test/setup_import_baseline.txt b/posthog/test/setup_import_baseline.txtindex 3ea73aa334f9..0162457b6cb0 100644--- a/posthog/test/setup_import_baseline.txt+++ b/posthog/test/setup_import_baseline.txt@@ -32,4 +32,3 @@ redisrichtrio# First-party modules with a known, structural import cost:-posthog.schema # the generated data model — splitting it is tracked as its own projectdiff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex ab60b55c40d9..6e1000a6b9bd 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -33,7 +33,7 @@ model_activity:products.feature_flags.backend.activity_logging.handle_feature_flmodel_activity:products.legal_documents.backend.signals.handle_legal_document_changemodel_activity:products.logs.backend.activity_logging.handle_logs_alert_activitymodel_activity:products.logs.backend.activity_logging.handle_logs_sampling_rule_activity-model_activity:products.managed_migrations.backend.api.batch_imports.handle_batch_import_change+model_activity:products.managed_migrations.backend.activity_logging.handle_batch_import_changemodel_activity:products.signals.backend.activity_logging.handle_signal_scout_config_changepost_delete:ee.vercel.integration.delete_experiment_experimentation_itempost_delete:ee.vercel.integration.delete_resource_experimentation_item@@ -170,7 +170,7 @@ pre_delete:posthog.storage.team_access_cache_signal_handlers.clear_project_secrepre_delete:posthog.storage.team_llm_gateway_policy_signal_handlers._clear_cache_on_deletepre_delete:products.alerts.backend.activity_logging.cleanup_alert_hog_functionspre_delete:products.alerts.backend.activity_logging.handle_alert_subscription_delete-pre_delete:products.managed_migrations.backend.api.batch_imports.handle_batch_import_delete+pre_delete:products.managed_migrations.backend.activity_logging.handle_batch_import_deletepre_save:posthog.models.event_ingestion_restriction_config.capture_old_restriction_typepre_save:posthog.models.organization.organization_about_to_be_createdpre_save:posthog.models.organization.organization_membership_saveddiff --git a/posthog/test/test_startup_import_budget.py b/posthog/test/test_startup_import_budget.pyindex 270b23a9842a..e161c033498e 100644--- a/posthog/test/test_startup_import_budget.py+++ b/posthog/test/test_startup_import_budget.py@@ -35,6 +35,10 @@ FORBIDDEN_AT_SETUP = ["pandas", # only query/export paths need it — reached via clickhouse_connect's import-time probe"pyarrow", # arrow tables — reached via pandas.compat and batch-export internals, both deferred"numpy", # alert detectors / weighted sampling / warehouse coercion — all call-time now+ "posthog.schema", # the generated pydantic data model (~2s) — enums live in posthog.schema_enums+ "posthog.hogql.query", # query execution entrypoint — drags the layers below in+ "posthog.hogql_queries", # the query-runner layer (every insight runner)+ "posthog.api.services.query", # API query service — viewset-request-time only]# Runs in a clean interpreter: pytest has already imported half the world, so we cannotdiff --git a/products/alerts/backend/models/alert.py b/products/alerts/backend/models/alert.pyindex 63c6b2611570..b80c4b3a8600 100644--- a/products/alerts/backend/models/alert.py+++ b/products/alerts/backend/models/alert.py@@ -14,11 +14,10 @@ if TYPE_CHECKING:import pydanticimport posthoganalytics-from posthog.schema import AlertCalculationInterval, AlertState, InsightThreshold-from posthog.constants import ALERTS_15_MINUTE_INTERVAL_FEATURE_FLAG_KEY, AvailableFeaturefrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import CreatedMetaFields, UUIDTModel+from posthog.schema_enums import AlertCalculationInterval, AlertStateALERT_STATE_CHOICES = [(AlertState.FIRING, AlertState.FIRING),@@ -95,6 +94,10 @@ class Threshold(ModelActivityMixin, CreatedMetaFields, UUIDTModel):def clean(self) -> None:try:+ # Deferred: posthog.schema (the pydantic models) stays off django.setup(),+ # where this model loads in every process.+ from posthog.schema import InsightThreshold # noqa: PLC0415+config = InsightThreshold.model_validate(self.configuration)except pydantic.ValidationError as e:raise ValidationError(f"Invalid threshold configuration: {e}")diff --git a/products/cdp/backend/tasks/hog_functions.py b/products/cdp/backend/tasks/hog_functions.pyindex 6c3927f812b0..aad007930f58 100644--- a/products/cdp/backend/tasks/hog_functions.py+++ b/products/cdp/backend/tasks/hog_functions.py@@ -6,11 +6,10 @@ from django.utils import timezonefrom celery import shared_taskfrom structlog import get_logger-from posthog.cdp.filters import compile_filters_bytecode+from posthog.celery_queues import CeleryQueuefrom posthog.plugins.plugin_server_api import reload_hog_functions_on_workersfrom posthog.redis import get_clientfrom posthog.scoping_audit import skip_team_scope_audit-from posthog.tasks.utils import CeleryQueuefrom products.actions.backend.models.action import Action@@ -79,6 +78,10 @@ def refresh_affected_hog_functions(actions_by_id = {action.id: action for action in all_related_actions}+ # posthog.cdp.filters pulls hogql.property and with it the HogQL/schema layer;+ # posthog.apps ready() imports this module in every process at setup.+ from posthog.cdp.filters import compile_filters_bytecode # noqa: PLC0415 — keeps HogQL off the import path+successfully_compiled_hog_functions = []for hog_function in affected_hog_functions:compiled_filters = compile_filters_bytecode(hog_function.filters, hog_function.team, actions_by_id)diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex e8a28f3666d0..d9323f15303b 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -15,8 +15,6 @@ from dateutil import parserfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework.exceptions import ValidationError-from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode, ProductKey-from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings, LimitContextfrom posthog.hogql.hogql import HogQLContext@@ -44,6 +42,7 @@ from posthog.models.person.sql import (PERSON_STATIC_COHORT_TABLE,)from posthog.models.property import Property, PropertyGroup+from posthog.schema_enums import PersonsOnEventsMode, ProductKeyfrom products.actions.backend.models.action import Actionfrom products.actions.backend.models.util import format_action_filter@@ -59,6 +58,8 @@ from products.cohorts.backend.models.sql import ()if TYPE_CHECKING:+ from posthog.schema import HogQLQueryModifiers+from posthog.personhog_client import ReadConsistencyfrom posthog.queries.util import PersonPropertiesMode@@ -587,7 +588,7 @@ def _cohort_distinct_ids_sql(cohort: Cohort, index: int, *, team: Team) -> tuplesql, context = HogQLQueryExecutor(query_type="CohortFilterDistinctIds",query=query,- modifiers=HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED),+ modifiers=_cohort_calculation_modifiers(),team=team,limit_context=LimitContext.COHORT_CALCULATION,settings=HogQLGlobalSettings(),@@ -596,6 +597,14 @@ def _cohort_distinct_ids_sql(cohort: Cohort, index: int, *, team: Team) -> tuplereturn _prefix_cohort_hogql_params(sql, context.values, cohort=cohort, index=index)+def _cohort_calculation_modifiers() -> HogQLQueryModifiers:+ # Deferred: posthog.schema (the pydantic models) stays off django.setup(), where this+ # module loads in every process via the cohort model.+ from posthog.schema import HogQLQueryModifiers # noqa: PLC0415++ return HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED)++def format_filter_query(cohort: Cohort, index: int) -> tuple[str, dict[str, Any]]:distinct_ids_sql, params = _cohort_distinct_ids_sql(cohort, index, team=cohort.team)# The leading `SELECT distinct_id` is load-bearing: breakdown_props rewrites it via string replace.diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.pyindex 90ee07ea84be..650b39bef7c4 100644--- a/products/conversations/backend/api/tests/test_events.py+++ b/products/conversations/backend/api/tests/test_events.py@@ -407,7 +407,7 @@ class TestConversationEvents(BaseTest):])@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.person_lookup._get_persons_by_email")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_email_fallback_groups(self, _name, channel, traits_email, email_from, mock_get_persons, mock_get_by_email, mock_capture@@ -456,7 +456,7 @@ class TestConversationEvents(BaseTest):])@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.person_lookup._get_persons_by_email")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_email_fallback_no_groups(self, _name, person_found, mock_get_persons, mock_get_by_email, mock_capture@@ -490,7 +490,7 @@ class TestConversationEvents(BaseTest):assert "$groups" not in call_kwargs["properties"]@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.person_lookup._get_persons_by_email")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_identified_person_without_membership_skips_email_fallback(self, mock_get_persons, mock_get_by_email, mock_capture@@ -516,7 +516,7 @@ class TestConversationEvents(BaseTest):])@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.person_lookup._get_persons_by_email")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_non_verified_channels_skip_email_fallback(self, _name, channel, mock_get_persons, mock_get_by_email, mock_capture@@ -556,7 +556,7 @@ class TestConversationEvents(BaseTest):])@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_group_types_for_project")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_analytics_fallback_groups(@@ -594,7 +594,7 @@ class TestConversationEvents(BaseTest):])@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_group_types_for_project")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_analytics_fallback_no_groups(@@ -613,7 +613,7 @@ class TestConversationEvents(BaseTest):assert "$groups" not in call_kwargs["properties"]@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_membership_hit_skips_analytics_fallback(self, mock_get_persons, mock_hogql, mock_capture@@ -633,9 +633,9 @@ class TestConversationEvents(BaseTest):assert call_kwargs["properties"]["$groups"]["organization"] == str(person_org.id)@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_group_types_for_project")- @patch("products.conversations.backend.events._get_persons_by_email")+ @patch("products.conversations.backend.person_lookup._get_persons_by_email")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_capture_ticket_created_email_channel_analytics_fallback_groups(self, mock_get_persons, mock_get_by_email, mock_group_types, mock_hogql, mock_capture@@ -673,7 +673,7 @@ class TestConversationEvents(BaseTest):])@patch("products.conversations.backend.events.capture_internal_routed")- @patch("products.conversations.backend.events.execute_hogql_query")+ @patch("posthog.hogql.query.execute_hogql_query")@patch("products.conversations.backend.events.get_group_types_for_project")@patch("products.conversations.backend.events.get_persons_by_distinct_ids")def test_analytics_fallback_result_is_cached(diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.pyindex 9c410ce679c5..bb1f705da75a 100644--- a/products/conversations/backend/events.py+++ b/products/conversations/backend/events.py@@ -10,9 +10,6 @@ from typing import Literalimport structlog-from posthog.hogql import ast-from posthog.hogql.query import execute_hogql_query-from posthog.api.capture_dispatch import capture_internal_routedfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.event_usage import groups as build_groups@@ -26,7 +23,6 @@ from posthog.settings import SITE_URLfrom products.conversations.backend.cache import get_cached_resolved_groups, set_cached_resolved_groupsfrom products.conversations.backend.models import Ticketfrom products.conversations.backend.models.constants import Channel-from products.conversations.backend.person_lookup import _get_persons_by_emaillogger = structlog.get_logger(__name__)@@ -125,6 +121,11 @@ def _resolve_groups_from_analytics(team: Team, distinct_ids: list[str]) -> dict)query = GROUPS_FROM_EVENTS_QUERY.format(org_col=org_col, customer_select=customer_select)+ # Deferred: hogql.query pulls the whole query-runner layer, and this module loads+ # at django.setup() via the conversations signal wiring.+ from posthog.hogql import ast # noqa: PLC0415+ from posthog.hogql.query import execute_hogql_query # noqa: PLC0415+with tags_context(product=Product.CONVERSATIONS, feature=Feature.QUERY):response = execute_hogql_query(query,@@ -188,6 +189,10 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:email = (ticket.anonymous_traits or {}).get("email") or ticket.email_fromif email:+ # person_lookup pulls the HogQL query layer; this module loads at django.setup()+ # via the conversations signal wiring, so import it lazily.+ from products.conversations.backend.person_lookup import _get_persons_by_email # noqa: PLC0415+person = _get_persons_by_email(team, [email]).get(email.lower())if person is not None and person.distinct_ids:membership = (diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.pyindex 3603072e1c85..0a7a77da342c 100644--- a/products/conversations/backend/signals.py+++ b/products/conversations/backend/signals.py@@ -14,7 +14,6 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Userfrom posthog.models.comment import Commentfrom posthog.models.instance_setting import get_instance_setting-from posthog.tasks.email import send_new_ticket_notificationfrom .cache import invalidate_messages_cache, invalidate_tickets_cachefrom .events import capture_message_received, capture_message_sent, capture_ticket_created@@ -147,6 +146,10 @@ def update_ticket_on_message(sender, instance: Comment, created: bool, **kwargs)try:conversations_settings = ticket.team.conversations_settings or {}if conversations_settings.get("notification_recipients"):+ # posthog.tasks.__init__ eagerly imports every task module; this signal+ # module is wired at django.setup(), so import the task lazily.+ from posthog.tasks.email import send_new_ticket_notification # noqa: PLC0415+send_new_ticket_notification.delay(ticket_id=item_id,team_id=team_id,diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 07e955094772..b820d1156cfc 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -1,7 +1,7 @@import reimport uuidfrom datetime import datetime, timedelta-from typing import Any, Optional, Union+from typing import TYPE_CHECKING, Any, Optional, Unionfrom urllib.parse import urlparsefrom django.conf import settings@@ -10,7 +10,8 @@ from django.db import models, transactionimport structlog-from posthog.schema import DataWarehouseSavedQueryOrigin, HogQLQueryModifiers+if TYPE_CHECKING:+ from posthog.schema import HogQLQueryModifiersfrom posthog.hogql import astfrom posthog.hogql.database.database import Database@@ -20,6 +21,7 @@ from posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel+from posthog.schema_enums import DataWarehouseSavedQueryOriginfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.data_imports.naming_convention import NamingConvention@@ -319,7 +321,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,return f"https://{settings.DATAWAREHOUSE_BUCKET_DOMAIN}/dlt/team_{self.team.pk}_model_{self.id.hex}/modeling/{self.normalized_name}"def hogql_definition(- self, modifiers: Optional[HogQLQueryModifiers] = None+ self, modifiers: Optional["HogQLQueryModifiers"] = None) -> Union[SavedQuery, HogQLDataWarehouseTable, DirectPostgresTable]:if self.table is not None and self.is_materialized and modifiers is not None and modifiers.useMaterializedViews:return self.table.hogql_definition(modifiers)diff --git a/products/data_warehouse/backend/sync_status.py b/products/data_warehouse/backend/sync_status.pyindex 5dee8d77d2aa..b231c1cd62cb 100644--- a/products/data_warehouse/backend/sync_status.py+++ b/products/data_warehouse/backend/sync_status.py@@ -7,11 +7,11 @@ from django.db.models import Qimport humanize-from posthog.schema import DataWarehouseSyncWarning-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemaif TYPE_CHECKING:+ from posthog.schema import DataWarehouseSyncWarning+from products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -55,6 +55,10 @@ def _build_warning_for_schema(schema: ExternalDataSchema,now: datetime,) -> DataWarehouseSyncWarning | None:+ # Deferred: posthog.schema (the pydantic models) stays off django.setup(), where this+ # module loads in every process via the warehouse table model.+ from posthog.schema import DataWarehouseSyncWarning # noqa: PLC0415+schema_status = schema.statussource_type = schema.source.source_type if schema.source_id else "unknown"source_id = str(schema.source_id) if schema.source_id else Nonediff --git a/products/error_tracking/backend/test/test_weekly_digest.py b/products/error_tracking/backend/test/test_weekly_digest.pyindex eb72940b3326..dad2ce3abf28 100644--- a/products/error_tracking/backend/test/test_weekly_digest.py+++ b/products/error_tracking/backend/test/test_weekly_digest.py@@ -10,11 +10,11 @@ from parameterized import parameterizedfrom posthog.models import Teamfrom posthog.models.organization import Organizationfrom posthog.models.utils import uuid7+from posthog.tasks.email_utils import compute_week_over_week_changefrom products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingIssueFingerprintV2from products.error_tracking.backend.weekly_digest import (auto_select_project_for_user,- compute_week_over_week_change,get_crash_free_sessions,get_daily_exception_counts,get_exception_counts,diff --git a/products/error_tracking/backend/weekly_digest.py b/products/error_tracking/backend/weekly_digest.pyindex 3e37ee9a3eb9..41e149a4aace 100644--- a/products/error_tracking/backend/weekly_digest.py+++ b/products/error_tracking/backend/weekly_digest.py@@ -6,11 +6,11 @@ from django.utils import timezoneimport structlog-from posthog.schema import HogQLFilters, ProductKey+from posthog.schema import HogQLFiltersfrom posthog.clickhouse.query_tagging import tag_queriesfrom posthog.models import Team-from posthog.tasks.email_utils import compute_week_over_week_change+from posthog.schema_enums import ProductKeylogger = structlog.get_logger(__name__)@@ -131,6 +131,10 @@ def get_crash_free_sessions(team: Team) -> dict:"""Calculate crash free sessions rate for the last 7 days with previous week comparison."""from posthog.hogql.query import execute_hogql_query+ # posthog.tasks.__init__ eagerly imports every task module (celery autoimport);+ # import the helper at call time so this module doesn't pull the task graph.+ from posthog.tasks.email_utils import compute_week_over_week_change # noqa: PLC0415+tag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:crash_free_sessions")try:diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.pyindex 30f30ca29983..8cca604ca861 100644--- a/products/exports/backend/models/subscription.py+++ b/products/exports/backend/models/subscription.py@@ -1,3 +1,4 @@+import sysfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literal, Optional, cast@@ -10,8 +11,6 @@ from django.utils import timezonefrom dateutil.rrule import DAILY, FR, MO, MONTHLY, SA, SU, TH, TU, WE, WEEKLY, YEARLY, rrule-from posthog.schema import SubscriptionFreeTierLimit-from posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exceptionfrom posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt@@ -24,10 +23,32 @@ from posthog.utils import absolute_uriif TYPE_CHECKING:from posthog.models.organization import Organization+ # Resolved lazily via __getattr__ below; declared here so consumers type-check as int.+ SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER: int+UNSUBSCRIBE_TOKEN_EXP_DAYS = 30-# Single source of truth shared with the frontend create gate via generated schema (SubscriptionFreeTierLimit.COUNT).-SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER: int = SubscriptionFreeTierLimit.model_fields["root"].default++# Single source of truth shared with the frontend create gate via generated schema+# (SubscriptionFreeTierLimit.COUNT). Resolved lazily via PEP 562 so posthog.schema (the+# pydantic models) stays off django.setup(), where this model loads in every process.+def __getattr__(name: str) -> int:+ if name == "SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER":+ from posthog.schema import SubscriptionFreeTierLimit # noqa: PLC0415++ value = SubscriptionFreeTierLimit.model_fields["root"].default+ # Cache as a real module attribute: later reads skip __getattr__, and tests+ # patching the attribute keep working since mock restores what getattr returns.+ globals()[name] = value+ return value+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+++def _free_tier_subscription_limit() -> int:+ # Module-attribute lookup (not a direct global read) so tests patching+ # SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER on this module still take effect.+ return sys.modules[__name__].SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER+# Max length of the prompt snippet used as an AI subscription's display name when it has no title.AI_PROMPT_DISPLAY_MAX_LEN = 60@@ -265,8 +286,10 @@ class Subscription(ModelActivityMixin, models.Model):# A None limit means unlimited (paid plans without a numeric cap).if allowed is not None and existing_count >= allowed:return f"Your team has reached the limit of {allowed} subscriptions on your plan."- elif existing_count >= SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER:- return f"Your plan is limited to {SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER} subscriptions."+ else:+ limit = _free_tier_subscription_limit()+ if existing_count >= limit:+ return f"Your plan is limited to {limit} subscriptions."return Nonediff --git a/products/managed_migrations/backend/activity_logging.py b/products/managed_migrations/backend/activity_logging.pynew file mode 100644index 000000000000..4a6edb74adb2--- /dev/null+++ b/products/managed_migrations/backend/activity_logging.py@@ -0,0 +1,100 @@+# Activity-log receivers, kept in a module with no API/query-runner imports so+# AppConfig.ready() can wire them cheaply in every process type (celery, temporal,+# migrate) without pulling the viewset import graph into django.setup().+import dataclasses++from django.db.models.signals import pre_delete+from django.dispatch import receiver++from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity+from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated+from posthog.models.signals import model_activity_signal, mutable_receiver++from products.managed_migrations.backend.models.batch_import_utils import (+ extract_batch_import_info,+ get_batch_import_created_by_info,+ get_batch_import_detail_name,+)+from products.managed_migrations.backend.models.batch_imports import BatchImport++[email protected](frozen=True)+class BatchImportContext(ActivityContextBase):+ source_type: str+ content_type: str+ start_date: str | None+ end_date: str | None+ created_by_user_id: str | None+ created_by_user_email: str | None+ created_by_user_name: str | None+++@mutable_receiver(model_activity_signal, sender=BatchImport)+def handle_batch_import_change(+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs+):+ # Use after_update for create/update, before_update for delete+ batch_import = after_update or before_update++ if not batch_import:+ return++ source_type, content_type, start_date, end_date = extract_batch_import_info(batch_import)+ created_by_user_id, created_by_user_email, created_by_user_name = get_batch_import_created_by_info(batch_import)+ detail_name = get_batch_import_detail_name(source_type, content_type)++ context = BatchImportContext(+ source_type=source_type,+ content_type=content_type,+ start_date=start_date,+ end_date=end_date,+ created_by_user_id=created_by_user_id,+ created_by_user_email=created_by_user_email,+ created_by_user_name=created_by_user_name,+ )++ log_activity(+ organization_id=batch_import.team.organization_id,+ team_id=batch_import.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=batch_import.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(scope, previous=before_update, current=after_update),+ name=detail_name,+ context=context,+ ),+ )+++@receiver(pre_delete, sender=BatchImport)+def handle_batch_import_delete(sender, instance, **kwargs):+ user = get_current_user()+ was_impersonated = get_was_impersonated()++ source_type, content_type, start_date, end_date = extract_batch_import_info(instance)+ created_by_user_id, created_by_user_email, created_by_user_name = get_batch_import_created_by_info(instance)+ detail_name = get_batch_import_detail_name(source_type, content_type)++ context = BatchImportContext(+ source_type=source_type,+ content_type=content_type,+ start_date=start_date,+ end_date=end_date,+ created_by_user_id=created_by_user_id,+ created_by_user_email=created_by_user_email,+ created_by_user_name=created_by_user_name,+ )++ log_activity(+ organization_id=instance.team.organization_id,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=instance.id,+ scope="BatchImport",+ activity="deleted",+ detail=Detail(name=detail_name, context=context),+ )diff --git a/products/managed_migrations/backend/api/batch_imports.py b/products/managed_migrations/backend/api/batch_imports.pyindex a6c97e4e7a7d..bd23cffeda30 100644--- a/products/managed_migrations/backend/api/batch_imports.py+++ b/products/managed_migrations/backend/api/batch_imports.py@@ -1,10 +1,6 @@import uuid-import dataclassesfrom datetime import timedelta-from django.db.models.signals import pre_delete-from django.dispatch import receiver-import posthoganalyticsfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema_field@@ -16,16 +12,8 @@ from rest_framework.response import Responsefrom posthog.api.documentation import _FallbackSerializerfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer-from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, changes_between, log_activity-from posthog.models.activity_logging.model_activity import get_current_user, get_was_impersonated-from posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.user import User-from products.managed_migrations.backend.models.batch_import_utils import (- extract_batch_import_info,- get_batch_import_created_by_info,- get_batch_import_detail_name,-)from products.managed_migrations.backend.models.batch_imports import BatchImport, ContentType, DateRangeExportSource@@ -61,8 +49,8 @@ class BatchImportSerializer(serializers.ModelSerializer):def validate_endpoint_url(self, value: str | None) -> str | None:if not value or not value.strip():return None- # Deferred: batch_export pulls the batch-export Temporal framework; keeping it out of- # module scope lets this module connect its delete receiver at AppConfig.ready() cheaply.+ # Deferred: batch_export pulls the batch-export Temporal framework, which has no+ # business on this module's import path.from products.batch_exports.backend.api.batch_export import resolve_and_validate_url # noqa: PLC0415try:@@ -615,85 +603,3 @@ class BatchImportViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)return Response({"status": "resumed"})--[email protected](frozen=True)-class BatchImportContext(ActivityContextBase):- source_type: str- content_type: str- start_date: str | None- end_date: str | None- created_by_user_id: str | None- created_by_user_email: str | None- created_by_user_name: str | None---@mutable_receiver(model_activity_signal, sender=BatchImport)-def handle_batch_import_change(- sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs-):- # Use after_update for create/update, before_update for delete- batch_import = after_update or before_update-- if not batch_import:- return-- source_type, content_type, start_date, end_date = extract_batch_import_info(batch_import)- created_by_user_id, created_by_user_email, created_by_user_name = get_batch_import_created_by_info(batch_import)- detail_name = get_batch_import_detail_name(source_type, content_type)-- context = BatchImportContext(- source_type=source_type,- content_type=content_type,- start_date=start_date,- end_date=end_date,- created_by_user_id=created_by_user_id,- created_by_user_email=created_by_user_email,- created_by_user_name=created_by_user_name,- )-- log_activity(- organization_id=batch_import.team.organization_id,- team_id=batch_import.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=batch_import.id,- scope=scope,- activity=activity,- detail=Detail(- changes=changes_between(scope, previous=before_update, current=after_update),- name=detail_name,- context=context,- ),- )---@receiver(pre_delete, sender=BatchImport)-def handle_batch_import_delete(sender, instance, **kwargs):- user = get_current_user()- was_impersonated = get_was_impersonated()-- source_type, content_type, start_date, end_date = extract_batch_import_info(instance)- created_by_user_id, created_by_user_email, created_by_user_name = get_batch_import_created_by_info(instance)- detail_name = get_batch_import_detail_name(source_type, content_type)-- context = BatchImportContext(- source_type=source_type,- content_type=content_type,- start_date=start_date,- end_date=end_date,- created_by_user_id=created_by_user_id,- created_by_user_email=created_by_user_email,- created_by_user_name=created_by_user_name,- )-- log_activity(- organization_id=instance.team.organization_id,- team_id=instance.team_id,- user=user,- was_impersonated=was_impersonated,- item_id=instance.id,- scope="BatchImport",- activity="deleted",- detail=Detail(name=detail_name, context=context),- )diff --git a/products/managed_migrations/backend/apps.py b/products/managed_migrations/backend/apps.pyindex d26063d55a8b..ef9db69e0c5c 100644--- a/products/managed_migrations/backend/apps.py+++ b/products/managed_migrations/backend/apps.py@@ -7,9 +7,9 @@ class ManagedMigrationsConfig(AppConfig):label = "managed_migrations"def ready(self) -> None:- # batch_imports.py holds the BatchImport activity-log receiver (handle_batch_import_change)- # plus a pre_delete cleanup receiver. They used to wire in via the viewset import; the lazy- # API router no longer pulls that, so a process that never builds the router (celery, temporal,- # migrate, shell) would stop logging batch-import activity and skip the delete cleanup. The- # module is light, so import it directly here.- from products.managed_migrations.backend.api import batch_imports # noqa: F401, PLC0415+ # The BatchImport activity-log receiver and pre_delete cleanup receiver used to wire in+ # via the viewset import; the lazy API router no longer pulls that, so a process that+ # never builds the router (celery, temporal, migrate, shell) would stop logging+ # batch-import activity and skip the delete cleanup. They live in activity_logging.py,+ # which has no API/query-runner imports, so wiring them here is cheap.+ from products.managed_migrations.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.pyindex 27bb238b2cdf..b5a586733a68 100644--- a/products/product_analytics/backend/models/insight.py+++ b/products/product_analytics/backend/models/insight.py@@ -16,7 +16,6 @@ from posthog.logging.timing import timedfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentation-from posthog.models.filters.utils import get_filterfrom posthog.models.utils import RootTeamManager, RootTeamMixin, sane_reprfrom posthog.utils import absolute_uri, generate_cache_key, generate_short_id@@ -360,6 +359,10 @@ class InsightViewed(models.Model):@timed("generate_insight_cache_key")def generate_insight_filters_hash(insight: Insight, dashboard: Optional["Dashboard"]) -> str:+ # Deferred: the legacy filters layer imports the HogQL/schema universe, and this model+ # loads at django.setup() in every process.+ from posthog.models.filters.utils import get_filter # noqa: PLC0415+try:dashboard_insight_filter = get_filter(data=insight.dashboard_filters(dashboard=dashboard), team=insight.team)candidate_filters_hash = generate_cache_key(diff --git a/products/product_analytics/backend/models/insight_caching_state.py b/products/product_analytics/backend/models/insight_caching_state.pyindex 43f280a70d73..baba711f302c 100644--- a/products/product_analytics/backend/models/insight_caching_state.py+++ b/products/product_analytics/backend/models/insight_caching_state.py@@ -4,7 +4,6 @@ from django.db.models.signals import post_savefrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.signals import mutable_receiverfrom posthog.models.utils import UniqueConstraintByExpression, UUIDTModel-from posthog.tasks.tasks import sync_insight_caching_statefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile@@ -48,23 +47,31 @@ class InsightCachingState(UUIDTModel):updated_at = models.DateTimeField(auto_now=True)+def _queue_sync_insight_caching_state(team_id: int, **kwargs: int | None) -> None:+ # posthog.tasks.__init__ eagerly imports every task module (celery autoimport), so a+ # module-level import here would pull the whole task graph into django.setup() via models.+ from posthog.tasks.tasks import sync_insight_caching_state # noqa: PLC0415++ sync_insight_caching_state.delay(team_id, **kwargs)++@mutable_receiver(post_save, sender=SharingConfiguration)def sync_sharing_configuration(sender, instance: SharingConfiguration, **kwargs):if instance.insight is not None and not instance.insight.deleted:- sync_insight_caching_state.delay(instance.team_id, insight_id=instance.insight_id)+ _queue_sync_insight_caching_state(instance.team_id, insight_id=instance.insight_id)elif instance.dashboard is not None and not instance.dashboard.deleted:for tile in instance.dashboard.tiles.all():- sync_insight_caching_state.delay(instance.team_id, dashboard_tile_id=tile.pk)+ _queue_sync_insight_caching_state(instance.team_id, dashboard_tile_id=tile.pk)@mutable_receiver(post_save, sender=Insight)def sync_insight(sender, instance: Insight, **kwargs):- sync_insight_caching_state.delay(instance.team_id, insight_id=instance.pk)+ _queue_sync_insight_caching_state(instance.team_id, insight_id=instance.pk)@mutable_receiver(post_save, sender=DashboardTile)def sync_dashboard_tile(sender, instance: DashboardTile, **kwargs):- sync_insight_caching_state.delay(instance.dashboard.team_id, dashboard_tile_id=instance.pk)+ _queue_sync_insight_caching_state(instance.dashboard.team_id, dashboard_tile_id=instance.pk)@mutable_receiver(post_save, sender=Dashboard)@@ -78,4 +85,4 @@ def sync_dashboard_updated(sender, instance: Dashboard, **kwargs):returnfor tile_id in DashboardTile.objects.filter(dashboard=instance).values_list("pk", flat=True):- sync_insight_caching_state.delay(instance.team_id, dashboard_tile_id=tile_id)+ _queue_sync_insight_caching_state(instance.team_id, dashboard_tile_id=tile_id)diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.pyindex ae2879695979..51ce5360fe45 100644--- a/products/replay_vision/backend/models/replay_scanner.py+++ b/products/replay_vision/backend/models/replay_scanner.py@@ -1,11 +1,16 @@+from typing import TYPE_CHECKING+from django.core.validators import MaxValueValidator, MinValueValidatorfrom django.db import models, transactionfrom django.utils import timezone-from posthog.schema import RecordingsQuery-from posthog.models.utils import UUIDModel+# This model loads at django.setup() in every process; posthog.schema (the pydantic+# models) is runtime-imported in the accessor that materializes the typed query.+if TYPE_CHECKING:+ from posthog.schema import RecordingsQuery+class ScannerType(models.TextChoices):MONITOR = "monitor", "Monitor"@@ -137,8 +142,10 @@ class ReplayScanner(UUIDModel):returnsuper().save(*args, **kwargs)- def recordings_query(self) -> RecordingsQuery:+ def recordings_query(self) -> "RecordingsQuery":"""The persisted candidate filter; an empty `query` parses as a bare RecordingsQuery."""+ from posthog.schema import RecordingsQuery # noqa: PLC0415+return RecordingsQuery.model_validate(self.query or {"kind": "RecordingsQuery"})def __str__(self) -> str:diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 2d3cb40c6cd8..e7a2895bed23 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -11,8 +11,6 @@ from django.db.models import Qimport structlogfrom clickhouse_driver.errors import ServerException as ClickHouseServerException-from posthog.schema import DatabaseSerializedFieldType, HogQLQueryModifiers-from posthog.hogql import astfrom posthog.hogql.constants import HogQLQuerySettingsfrom posthog.hogql.context import HogQLContext@@ -29,6 +27,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.errors import CHQueryErrorTooManySimultaneousQueries, wrap_clickhouse_query_errorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr+from posthog.schema_enums import DatabaseSerializedFieldTypefrom posthog.settings import TESTfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.data_imports.pipelines.pipeline.consts import PARTITION_KEY@@ -50,7 +49,7 @@ from .credential import DataWarehouseCredentialfrom .external_table_definitions import external_tablesif TYPE_CHECKING:- pass+ from posthog.schema import HogQLQueryModifiersSERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING: dict[DatabaseSerializedFieldType, str] = {DatabaseSerializedFieldType.INTEGER: "Int64",@@ -202,6 +201,10 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletselect_from=ast.JoinExpr(table=ast.Field(chain=[self.name])),)+ # Deferred: posthog.schema (the pydantic models) stays off django.setup(),+ # where this model loads in every process.+ from posthog.schema import HogQLQueryModifiers # noqa: PLC0415+tag_queries(product=Product.WAREHOUSE, feature=Feature.QUERY)execute_hogql_query(query,@@ -457,7 +460,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet)(name=column_name, nullable=is_nullable)def hogql_definition(- self, modifiers: Optional[HogQLQueryModifiers] = None+ self, modifiers: Optional["HogQLQueryModifiers"] = None) -> HogQLDataWarehouseTable | DirectPostgresTable:columns = self.columns or {}