: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
refactor(hogql): defer printer boundary loads and guard the full compile pipeline (#72352)
George Munyoro0f183c185d2a
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex 9fd2657bcaad..4e3d3c62b7eb 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -29,7 +29,6 @@ from posthog.hogql.printer.postgres import PostgresPrinterfrom posthog.hogql.printer.redshift import RedshiftPrinterfrom posthog.hogql.printer.snowflake import SnowflakePrinterfrom posthog.hogql.resolver import ResolverFactory, resolve_types-from posthog.hogql.transforms.clickhouse_property_resolution import clickhouse_property_resolutionfrom posthog.hogql.transforms.events_predicate_pushdown import apply_events_predicate_pushdown, events_pushdown_enabledfrom posthog.hogql.transforms.in_cohort import resolve_in_cohorts, resolve_in_cohorts_conjoinedfrom posthog.hogql.transforms.json_property_pushdown import (@@ -48,9 +47,6 @@ from posthog.hogql.visitor import clone_exprfrom posthog.hogql.workload import WorkloadCollectorfrom posthog.clickhouse.workload import Workload-from posthog.models.team.event_retention import events_retention_months_for_team--from products.access_control.backend.property_access_control import get_restricted_properties_for_teamPRINTER_CLASSES: dict[HogQLDialect, type[BasePrinter]] = {"clickhouse": ClickHousePrinter,@@ -157,6 +153,13 @@ def prepare_ast_for_printing(# restricted property as NULL). The warehouse (Postgres / DuckDB) dialects only compile external data-warehouse# sources, which carry no restrictable event/person properties, so they need no enforcement here.if context.team_id is not None and context.restricted_properties is None:+ # Deferred: a Django-side load at the prepare boundary (same seam as Database.create_for and+ # load_property_metadata) — keeping it behind the call is what lets the printer package import+ # without django.setup().+ from products.access_control.backend.property_access_control import ( # noqa: PLC0415+ get_restricted_properties_for_team,+ )+with context.timings.measure("load_restricted_properties"):if context.team is not None and context.team.pk == context.team_id:context.restricted_properties = get_restricted_properties_for_team(user=context.user, team=context.team)@@ -280,6 +283,9 @@ def prepare_ast_for_printing(# enforcement floor still can't be circumvented by a query-supplied modifier.with context.timings.measure("events_retention_floor"):if context.apply_events_retention_floor:+ # Deferred: Django-side load at the prepare boundary; see the restricted-properties load above.+ from posthog.models.team.event_retention import events_retention_months_for_team # noqa: PLC0415+context.events_retention_months = events_retention_months_for_team(context.team, context.team_id)# Events predicate pushdown runs on the lowered AST (between lowering and property resolution), so it matches the@@ -292,6 +298,13 @@ def prepare_ast_for_printing(node = apply_events_predicate_pushdown(node, context)with context.timings.measure("clickhouse_property_resolution"):+ # Deferred to break the module-level cycle cpr → printer.base → printer package init →+ # utils → cpr, so clickhouse_property_resolution imports standalone in a bare+ # interpreter (guarded by test_no_django_imports).+ from posthog.hogql.transforms.clickhouse_property_resolution import ( # noqa: PLC0415+ clickhouse_property_resolution,+ )+node = clickhouse_property_resolution(node, context)# We support global query settings, and local subquery settings.diff --git a/posthog/hogql/test/test_no_django_imports.py b/posthog/hogql/test/test_no_django_imports.pyindex 6877ba5f4430..a7f7bb2232fc 100644--- a/posthog/hogql/test/test_no_django_imports.py+++ b/posthog/hogql/test/test_no_django_imports.py@@ -27,8 +27,7 @@ DJANGO_FREE_MODULES = ["posthog.hogql.parser",# database.database transitively imports every schema table module, so importing it here# guards the whole schema layer; the resolver is the headline Seam 0 win (parse -> resolve- # -> AST with no django.setup()). The printer stays coupled until the property-metadata- # providers land (it transitively imports the property transforms).+ # -> AST with no django.setup())."posthog.hogql.database.database","posthog.hogql.resolver","posthog.hogql.property_metadata",@@ -37,6 +36,13 @@ DJANGO_FREE_MODULES = ["posthog.hogql.transforms.property_types","posthog.hogql.transforms.lazy_tables","posthog.hogql.transforms.in_cohort",+ # clickhouse_property_resolution before printer, deliberately in the cold-start order that used+ # to deadlock: cpr pulls in printer.base/printer.clickhouse (triggering the package init), and+ # printer/utils defers its cpr import to the call site precisely so this standalone import works.+ # The printer package init imports every dialect printer plus utils, so that one import then+ # guards the whole printer layer.+ "posthog.hogql.transforms.clickhouse_property_resolution",+ "posthog.hogql.printer",]_CHILD = f"""@@ -50,6 +56,29 @@ assert isinstance(parse_select("select 1"), ast.SelectQuery)assert isinstance(parse_expr("1 + 1"), ast.Expr)# The static table catalog builds without Django — no team, no ORM.assert Database(include_posthog_tables=True).has_table("events")++# End-to-end compile: parse -> resolve -> prepare -> print to ClickHouse SQL, with every+# Django-side load either pre-seeded on the context or stubbed at its declared boundary.+# Anything on the compile path that reaches the ORM outside those boundaries crashes here.+from unittest.mock import patch+from posthog.hogql.context import HogQLContext+from posthog.hogql.printer import prepare_and_print_ast+from posthog.hogql.property_metadata import PropertyMetadata++context = HogQLContext(team_id=1, enable_select_queries=True)+context.database = Database(include_posthog_tables=True) # else Database.create_for hits the ORM+context.restricted_properties = set() # else the access-control load hits the ORM+context.use_new_events_schema = False # else the lazy instance-setting read hits the ORM+context.apply_events_retention_floor = False # backend opt-out; else the retention load hits the ORM+# The unaliased count() exercises the resolver's lazy printer import for implicit-alias derivation.+node = parse_select("select count() from events where properties.$browser = 'Chrome'")+with patch(+ "posthog.hogql.transforms.property_types.load_property_metadata", return_value=PropertyMetadata()+):+ sql, _ = prepare_and_print_ast(node, context, "clickhouse")+assert sql and "FROM events" in sql, sql+assert "count()" in sql, sql+assert any(v == "Chrome" for v in context.values.values()), context.valuesprint("DJANGO_FREE_OK")"""diff --git a/posthog/temporal/messaging/test/test_hogql_compile.py b/posthog/temporal/messaging/test/test_hogql_compile.pyindex 92f68a53aa12..7f386bc0844a 100644--- a/posthog/temporal/messaging/test/test_hogql_compile.py+++ b/posthog/temporal/messaging/test/test_hogql_compile.py@@ -24,7 +24,9 @@ class TestCompileHogqlForStreaming:)with patch(- "posthog.hogql.printer.utils.get_restricted_properties_for_team",+ # Patch the defining module: printer/utils imports this at call time, so a patch on+ # the printer.utils namespace would never intercept.+ "products.access_control.backend.property_access_control.get_restricted_properties_for_team",side_effect=AssertionError("get_restricted_properties_for_team must not be called"),):sql, params = await compile_hogql_for_streaming(node, team_id=team.id)diff --git a/products/access_control/backend/apps.py b/products/access_control/backend/apps.pyindex e1309c178d07..6e5a3a6c7c2e 100644--- a/products/access_control/backend/apps.py+++ b/products/access_control/backend/apps.py@@ -6,3 +6,10 @@ from django.apps import AppConfigclass AccessControlConfig(AppConfig):name = "products.access_control.backend"label = "access_control"++ def ready(self) -> None:+ # Connect the restriction-cache invalidation receivers at app-population. They used to be+ # wired as a side effect of the HogQL printer importing this module at django.setup();+ # that import is now deferred to compile time, so the wiring must happen here or the+ # receivers connect in no process and cache invalidation silently stops.+ from products.access_control.backend import property_access_control # noqa: F401, PLC0415