: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
feat(hogql): Pass modifiers to HogQL model runs (#107684)
Tomás Farías Santanaa09a5da3a89a
diff --git a/products/batch_exports/backend/debug/debugger.py b/products/batch_exports/backend/debug/debugger.pyindex 7b2cde13e505..5350aa54af83 100644--- a/products/batch_exports/backend/debug/debugger.py+++ b/products/batch_exports/backend/debug/debugger.py@@ -298,6 +298,7 @@ class BatchExportsDebugger:schema=self.batch_export.schema,filters=self.batch_export.filters,hogql_query=self.batch_export.hogql_query,+ hogql_modifiers=self.batch_export.hogql_modifiers,),integration_id=self.batch_export.destination.integration_id,**destination_config,diff --git a/products/batch_exports/backend/hogql_source.py b/products/batch_exports/backend/hogql_source.pyindex 48aae9e9fe2e..7f501eb5ee48 100644--- a/products/batch_exports/backend/hogql_source.py+++ b/products/batch_exports/backend/hogql_source.py@@ -7,6 +7,11 @@ should not import from `products.batch_exports.backend.temporal` or any DRF codeimport typingimport datetime as dt+import structlog+from pydantic import ValidationError++from posthog.schema import HogQLQueryModifiers+from posthog.hogql import astfrom posthog.hogql.constants import FEATURE_FLAG_FALSE_VARIANT_SENTINELfrom posthog.hogql.context import HogQLContext@@ -36,6 +41,8 @@ _VALIDATION_DATA_INTERVAL_END = dt.datetime(2000, 1, 2, tzinfo=dt.UTC)_SUPPORTED_PLACEHOLDERS = f"{{{DATA_INTERVAL_START_PLACEHOLDER}}} and {{{DATA_INTERVAL_END_PLACEHOLDER}}}"+LOGGER = structlog.get_logger(__name__)+class UnsupportedHogQLQueryError(Exception):"""Raised when a HogQL query cannot be used to power a batch export."""@@ -132,7 +139,10 @@ def validate_hogql_batch_export_user(team: "Team", user: "User | None") -> None:def create_hogql_context_for_batch_export(- team: "Team", values: dict[str, typing.Any] | None = None, user: "User | None" = None+ team: "Team",+ values: dict[str, typing.Any] | None = None,+ user: "User | None" = None,+ modifiers: HogQLQueryModifiers | None = None,) -> HogQLContext:"""Build the HogQLContext batch exports use to resolve and print a query.@@ -143,6 +153,9 @@ def create_hogql_context_for_batch_export((`Database.create_for` team-defaults a copy, not this context's instance), and notop-level LIMIT is applied. It reads from Postgres, so worker code must call it offthe event loop.++ `modifiers` are the export's own modifiers. Like query-level modifiers, they+ override the team modifiers key by key."""context = HogQLContext(team=team,@@ -151,7 +164,7 @@ def create_hogql_context_for_batch_export(enable_select_queries=True,limit_top_select=False,values=values if values is not None else {},- modifiers=create_default_modifiers_for_team(team),+ modifiers=create_default_modifiers_for_team(team, modifiers),)context.database = Database.create_for(team=team, user=user, modifiers=context.modifiers)return context@@ -177,7 +190,9 @@ def _validate_select_columns_are_named(parsed: ast.SelectQuery | ast.SelectSetQu)-def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team", *, user: "User") -> None:+def validate_hogql_query_for_batch_export(+ hogql_query: str, team: "Team", *, user: "User", modifiers: HogQLQueryModifiers | None = None+) -> None:"""Validate a HogQL query can power a batch export for the given team.Parses the query, checks output columns are named, and compiles it with the user's@@ -197,7 +212,7 @@ def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team", *, useparsed = replace_interval_placeholders(parsed, _VALIDATION_DATA_INTERVAL_START, _VALIDATION_DATA_INTERVAL_END)- context = create_hogql_context_for_batch_export(team, user=user)+ context = create_hogql_context_for_batch_export(team, user=user, modifiers=modifiers)try:prepared = prepare_ast_for_printing(parsed, context=context, dialect="clickhouse", stack=[])assert prepared is not None@@ -206,6 +221,29 @@ def validate_hogql_query_for_batch_export(hogql_query: str, team: "Team", *, useraise UnsupportedHogQLQueryError(f"Invalid HogQL query: {e}") from e+def load_hogql_modifiers(stored: dict[str, typing.Any] | None) -> HogQLQueryModifiers | None:+ """Load the HogQL modifiers a batch export stored, dropping keys that no longer exist.++ `HogQLQueryModifiers` forbids unknown keys, so a modifier removed from the schema after+ an export stored it would fail every run. No code reads a removed modifier anymore, so+ dropping it keeps the output the same.++ Raises:+ UnsupportedHogQLQueryError: If a stored modifier has a value that is not valid.+ """+ if stored is None:+ return None++ known = {key: value for key, value in stored.items() if key in HogQLQueryModifiers.model_fields}+ if unknown := sorted(stored.keys() - known.keys()):+ LOGGER.warning("Dropping unknown HogQL modifiers", modifiers=unknown)++ try:+ return HogQLQueryModifiers.model_validate(known)+ except ValidationError as e:+ raise UnsupportedHogQLQueryError(f"Invalid HogQL modifiers: {e}") from e++def native_event_property_chain(property_chain: list[str | int]) -> list[str | int]:"""The path an event property has in the native source's JSON.diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex 8c172c082b5c..6a97da676969 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -161,6 +161,8 @@ class BatchExportModel:hogql_query: str | None = None# The user who last modified the batch export. This is used for validating custom HogQL queries. This is stored alongside the query, not looked up at runtime, so that an edit during a run cannot pair the old query with a new user.user_id: int | None = None+ # A dict, not `HogQLQueryModifiers`, because Temporal's default converter only decodes dataclasses and JSON types.+ hogql_modifiers: dict[str, typing.Any] | None = None@dataclass@@ -1215,6 +1217,7 @@ def sync_batch_export(batch_export: BatchExport, created: bool):user_id=batch_export.last_modified_by_idif batch_export.model == BatchExport.Model.HOGQLelse None,+ hogql_modifiers=batch_export.hogql_modifiers,),# TODO: This field is deprecated, but we still set it for backwards compatibility.# New exports created will always have `batch_export_schema` set to `None`, but existingdiff --git a/products/batch_exports/backend/temporal/record_batch_model.py b/products/batch_exports/backend/temporal/record_batch_model.pyindex 948b2cd8e3c1..e1fd857b4b20 100644--- a/products/batch_exports/backend/temporal/record_batch_model.py+++ b/products/batch_exports/backend/temporal/record_batch_model.py@@ -27,6 +27,7 @@ from products.batch_exports.backend.hogql_source import (UnsupportedHogQLQueryError,create_hogql_context_for_batch_export,find_interval_placeholders,+ load_hogql_modifiers,parse_hogql_select_for_batch_export,replace_interval_placeholders,serialize_batch_export_query,@@ -372,11 +373,17 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):"""def __init__(- self, team_id: int, hogql_query: str, batch_export_id: str | None = None, user_id: int | None = None+ self,+ team_id: int,+ hogql_query: str,+ batch_export_id: str | None = None,+ user_id: int | None = None,+ hogql_modifiers: dict[str, typing.Any] | None = None,) -> None:super().__init__(team_id=team_id, batch_export_id=batch_export_id)self.user_id = user_idself.hogql_query = hogql_query+ self.hogql_modifiers = load_hogql_modifiers(hogql_modifiers)self.parsed_hogql_query = parse_hogql_select_for_batch_export(hogql_query)self.wait_for_data_interval_end = DATA_INTERVAL_END_PLACEHOLDER in find_interval_placeholders(self.parsed_hogql_query@@ -387,7 +394,7 @@ class HogQLQueryRecordBatchModel(RecordBatchModel):user = await User.objects.filter(pk=self.user_id).afirst()await database_sync_to_async(validate_hogql_batch_export_user)(team, user)return await database_sync_to_async(create_hogql_context_for_batch_export)(- team, user=user, values={"log_comment": self.get_log_comment()}+ team, user=user, values={"log_comment": self.get_log_comment()}, modifiers=self.hogql_modifiers)async def _print_query(@@ -455,6 +462,7 @@ def resolve_batch_exports_model(hogql_query=model.hogql_query,batch_export_id=batch_export_id,user_id=model.user_id,+ hogql_modifiers=model.hogql_modifiers,)else:model_name = "events"diff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.pyindex b5d394237c62..45e97a6a5adc 100644--- a/products/batch_exports/backend/tests/api/test_create.py+++ b/products/batch_exports/backend/tests/api/test_create.py@@ -528,6 +528,7 @@ def test_create_batch_export_with_custom_schema("schema": expected_schema,"hogql_query": None,"user_id": None,+ "hogql_modifiers": None,}@@ -631,6 +632,7 @@ def test_create_batch_export_with_hogql_model("schema": None,"hogql_query": hogql_batch_export_data["hogql_query"],"user_id": user.pk,+ "hogql_modifiers": None,}diff --git a/products/batch_exports/backend/tests/api/test_update.py b/products/batch_exports/backend/tests/api/test_update.pyindex 5c788eebe40b..6134130776bd 100644--- a/products/batch_exports/backend/tests/api/test_update.py+++ b/products/batch_exports/backend/tests/api/test_update.py@@ -724,6 +724,7 @@ def test_can_patch_hogql_query(},"hogql_query": None,"user_id": None,+ "hogql_modifiers": None,}for patch_data, expected_schema in [@@ -842,6 +843,7 @@ def test_patch_hogql_model_batch_export("schema": None,"hogql_query": new_hogql_query,"user_id": editor.pk,+ "hogql_modifiers": None,}diff --git a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py b/products/batch_exports/backend/tests/temporal/test_record_batch_model.pyindex f6a7483756e9..8c07401025e9 100644--- a/products/batch_exports/backend/tests/temporal/test_record_batch_model.py+++ b/products/batch_exports/backend/tests/temporal/test_record_batch_model.py@@ -537,6 +537,30 @@ class TestHogQLQueryRecordBatchModel:assert record_batch_model.hogql_query == batch_export_model.hogql_queryassert record_batch_model.wait_for_data_interval_end is True+ @pytest.mark.parametrize(+ "hogql_modifiers,converts_timezone",+ [(None, True), ({"convertToProjectTimezone": False}, False)],+ ids=["team-modifiers", "export-modifiers"],+ )+ async def test_resolved_model_prints_query_with_stored_modifiers(+ self, ateam, auser, data_interval_start, data_interval_end, hogql_modifiers, converts_timezone+ ):+ batch_export_model = BatchExportModel(+ name="hogql",+ schema=None,+ hogql_query="SELECT event AS event, timestamp AS timestamp FROM events",+ user_id=auser.pk,+ hogql_modifiers=hogql_modifiers,+ )++ _, record_batch_model, _, _, _, _ = resolve_batch_exports_model(+ team_id=ateam.pk, batch_export_model=batch_export_model+ )+ assert record_batch_model is not None+ printed_query, _ = await record_batch_model.as_query_with_parameters(data_interval_start, data_interval_end)++ assert ("toTimeZone(events.timestamp" in printed_query) is converts_timezone+async def test_resolve_batch_exports_model_raises_without_hogql_query(self):"""Without this, a missing query would fall through to the events template path and export the wrong data."""with pytest.raises(UnsupportedHogQLQueryError):diff --git a/products/batch_exports/backend/tests/test_hogql_source.py b/products/batch_exports/backend/tests/test_hogql_source.pyindex 89eb04eed793..92812d30d258 100644--- a/products/batch_exports/backend/tests/test_hogql_source.py+++ b/products/batch_exports/backend/tests/test_hogql_source.py@@ -7,6 +7,7 @@ from posthog.sync import database_sync_to_asyncfrom products.batch_exports.backend.hogql_source import (UnsupportedHogQLQueryError,create_hogql_context_for_batch_export,+ load_hogql_modifiers,validate_hogql_query_for_batch_export,)@@ -119,18 +120,38 @@ async def test_rejects_unsupported_queries(ateam, auser, hogql_query, expected_mawait _validate(hogql_query, ateam, auser)[email protected]("team_modifiers", [None, {"convertToProjectTimezone": False}])-def test_create_hogql_context_for_batch_exports(team, team_modifiers: dict[str, typing.Any] | None) -> None:+ "team_modifiers,export_modifiers,expected_modifiers",+ [+ (None, None, {}),+ ({"convertToProjectTimezone": False}, None, {"convertToProjectTimezone": False}),+ (+ {"convertToProjectTimezone": False, "optimizeProjections": False},+ {"convertToProjectTimezone": True, "removedModifier": True},+ {"convertToProjectTimezone": True, "optimizeProjections": False},+ ),+ ],+ ids=["no-modifiers", "team-modifiers", "export-modifiers-override-team-modifiers"],+)+def test_create_hogql_context_for_batch_exports(+ team,+ team_modifiers: dict[str, typing.Any] | None,+ export_modifiers: dict[str, typing.Any] | None,+ expected_modifiers: dict[str, typing.Any],+) -> None:if team_modifiers is not None:team.modifiers = team_modifiers- else:- team_modifiers = {}- context = create_hogql_context_for_batch_export(team)+ context = create_hogql_context_for_batch_export(team, modifiers=load_hogql_modifiers(export_modifiers))assert context.team == team- for key, value in team_modifiers.items():+ for key, value in expected_modifiers.items():assert getattr(context.modifiers, key) == value, (- f"Context modifier '{key}' should be set by team modifier. Expected '{value}', got '{getattr(context.modifiers, key)}'"+ f"Context modifier '{key}' should be '{value}', got '{getattr(context.modifiers, key)}'")+++def test_load_hogql_modifiers_rejects_invalid_values() -> None:+ with pytest.raises(UnsupportedHogQLQueryError, match="Invalid HogQL modifiers"):+ load_hogql_modifiers({"personsOnEventsMode": "not_a_mode"})