:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(experiments): delete dead query-layer helpers (#100723)
Anders1d2e286d09a4
diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex 5649b5221f52..8ca63ea9a368 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -320,7 +320,6 @@ products/endpoints/backend/tests/test_rate_limit.py::TestMaterializationCacheproducts/engineering_analytics/backend/tests/test_logic_workflows.py::TestCostPerMergeSeriesproducts/error_tracking/backend/hogql_queries/test/test_error_tracking_pending_fingerprint_issue_state_updates.py::TestPendingUpdateUnionBuilderproducts/error_tracking/backend/test_notifications.py::TestAssignerExcludingResolver-products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.py::TestHogQLAggregationIntegrationproducts/experiments/backend/hogql_queries/test/test_hogql_aggregation_utils.py::TestHogQLAggregationUtilsproducts/experiments/backend/hogql_queries/test/test_hogql_injection.py::TestHogQLInjectionPreventionproducts/experiments/backend/hogql_queries/test/test_metric_source.py::TestMetricSourceInfodiff --git a/products/experiments/backend/hogql_queries/base_query_utils.py b/products/experiments/backend/hogql_queries/base_query_utils.pyindex 88455b1bc0fa..90772f99ab18 100644--- a/products/experiments/backend/hogql_queries/base_query_utils.py+++ b/products/experiments/backend/hogql_queries/base_query_utils.py@@ -14,9 +14,7 @@ from posthog.schema import (ExperimentDataWarehouseNode,ExperimentEventExposureConfig,ExperimentFunnelMetric,- ExperimentMeanMetric,ExperimentMetricMathType,- ExperimentRatioMetric,FunnelConversionWindowTimeUnit,FunnelMathType,GroupMathType,@@ -28,13 +26,10 @@ from posthog.hogql.parser import parse_exprfrom posthog.hogql.property import action_to_expr, property_to_exprfrom posthog.clickhouse.query_tagging import tag_contains_user_hogql-from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.team import Teamfrom products.actions.backend.models.action import Actionfrom products.experiments.backend.hogql_queries.hogql_aggregation_utils import (- aggregation_needs_numeric_input,- build_aggregation_call,contains_aggregation,extract_aggregation_and_inner_expr,)@@ -178,16 +173,6 @@ def get_source_value_expr(source: Union[EventsNode, ActionsNode, ExperimentDataWreturn ast.Constant(value=1)-def get_metric_value(- metric: ExperimentMeanMetric, source: Union[EventsNode, ActionsNode, ExperimentDataWarehouseNode, None] = None-) -> ast.Expr:- """- Backward compatibility wrapper for get_source_value_expr.- """- actual_source = source if source is not None else metric.source- return get_source_value_expr(actual_source)--def event_or_action_to_filter(team: Team, entity_node: Union[EventsNode, ActionsNode, ExperimentEventExposureConfig]) -> ast.Expr:@@ -325,119 +310,6 @@ def experiment_window(experiment: Experiment, team: Team, as_of: datetime) -> Dareturn analysis_window(experiment.start_date, experiment.end_date, team, as_of)-def get_source_time_window(- date_range_query: QueryDateRange,- left: ast.Expr,- conversion_window: int | None = None,- conversion_window_unit=None,-) -> list[ast.CompareOperation]:- """- Returns the time window conditions based on conversion window and date range.- Pure source-based function that doesn't depend on metric object.- """-- if conversion_window is not None and conversion_window_unit is not None:- # If conversion window is set, limit events to date_to + window- date_to = ast.CompareOperation(- left=left,- right=ast.Call(- name="plus",- args=[- ast.Constant(value=date_range_query.date_to()),- ast.Call(- name="toIntervalSecond",- args=[- ast.Constant(value=conversion_window_to_seconds(conversion_window, conversion_window_unit)),- ],- ),- ],- ),- op=ast.CompareOperationOp.Lt,- )- else:- # If no conversion window, just limit to experiment end date- date_to = ast.CompareOperation(- op=ast.CompareOperationOp.Lt,- left=left,- right=ast.Constant(value=date_range_query.date_to()),- )-- return [- # Improve query performance by only fetching events after the experiment started- ast.CompareOperation(- op=ast.CompareOperationOp.GtEq,- left=left,- right=ast.Constant(value=date_range_query.date_from()),- ),- date_to,- ]---def get_metric_time_window(- metric: Union[ExperimentMeanMetric, ExperimentFunnelMetric, ExperimentRatioMetric],- date_range_query: QueryDateRange,- left: ast.Expr,-) -> list[ast.CompareOperation]:- """- Backward compatibility wrapper for get_source_time_window.- """- return get_source_time_window(date_range_query, left, metric.conversion_window, metric.conversion_window_unit)---def get_source_aggregation_expr(- source: Union[EventsNode, ActionsNode, ExperimentDataWarehouseNode], table_alias: str = "metric_events"-) -> ast.Expr:- """- Returns the aggregation expression for a specific source based on its math type.- Uses the specified table_alias for field references.- """- if isinstance(source, EventsNode) or isinstance(source, ActionsNode):- math_type = getattr(source, "math", None)- if math_type in [- ExperimentMetricMathType.UNIQUE_SESSION,- ExperimentMetricMathType.DAU,- ExperimentMetricMathType.UNIQUE_GROUP,- ]:- # Clickhouse counts empty values as distinct, so need to explicitly exclude them- # Also handle the special case of null UUIDs (00000000-0000-0000-0000-000000000000)- return parse_expr(f"""toFloat(count(distinct- multiIf(- toTypeName({table_alias}.value) = 'UUID' AND reinterpretAsUInt128({table_alias}.value) = 0, NULL,- toString({table_alias}.value) = '', NULL,- {table_alias}.value- )- ))""")- elif math_type == ExperimentMetricMathType.MIN:- return parse_expr(f"min(coalesce(toFloat({table_alias}.value), 0))")- elif math_type == ExperimentMetricMathType.MAX:- return parse_expr(f"max(coalesce(toFloat({table_alias}.value), 0))")- elif math_type == ExperimentMetricMathType.AVG:- return parse_expr(f"avg(coalesce(toFloat({table_alias}.value), 0))")- elif math_type == ExperimentMetricMathType.HOGQL:- math_hogql = getattr(source, "math_hogql", None)- if math_hogql is not None:- tag_contains_user_hogql()- aggregation_function, _, params, distinct = extract_aggregation_and_inner_expr(math_hogql)- if aggregation_function:- inner_value_expr = parse_expr(f"{table_alias}.value")- if aggregation_needs_numeric_input(aggregation_function):- inner_value_expr = ast.Call(name="toFloat", args=[inner_value_expr])- agg_call = build_aggregation_call(- aggregation_function, inner_value_expr, params=params, distinct=distinct- )- # Non-numeric aggregations (count, uniq, etc.) return UInt64, which is- # incompatible with Float64 in ClickHouse greatest/least functions used- # by winsorization. Wrap with toFloat to ensure consistent Float64 type.- if not aggregation_needs_numeric_input(aggregation_function):- agg_call = ast.Call(name="toFloat", args=[agg_call])- return ast.Call(name="coalesce", args=[agg_call, ast.Constant(value=0)])- # Default to sum if no aggregation function is found- return parse_expr(f"sum(coalesce(toFloat({table_alias}.value), 0))")-- # Default aggregation for all other cases (including data warehouse)- return parse_expr(f"sum(coalesce(toFloat({table_alias}.value), 0))")--def funnel_steps_to_filter(team: Team, funnel_steps: list[EventsNode | ActionsNode | ExperimentDataWarehouseNode]) -> ast.Expr:diff --git a/products/experiments/backend/hogql_queries/breakdown_injector.py b/products/experiments/backend/hogql_queries/breakdown_injector.pyindex 647c918dd63c..ffb112b9b6c6 100644--- a/products/experiments/backend/hogql_queries/breakdown_injector.py+++ b/products/experiments/backend/hogql_queries/breakdown_injector.py@@ -45,10 +45,6 @@ class BreakdownInjector:"""Returns True if any breakdowns are configured"""return len(self.breakdowns) > 0- def _get_breakdown_count(self) -> int:- """Returns the number of breakdowns configured"""- return len(self.breakdowns)-def _get_breakdown_aliases(self) -> list[str]:"""Returns list of breakdown aliases: ['breakdown_value_1', 'breakdown_value_2', ...]"""return [f"breakdown_value_{i + 1}" for i in range(len(self.breakdowns))]diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.pyindex 1c571e8facb9..4a49df3821a4 100644--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py@@ -303,7 +303,6 @@ class ExperimentQueryRunner(QueryRunner):start_is_dw = isinstance(self.query.metric.start_event, ExperimentDataWarehouseNode)completion_is_dw = isinstance(self.query.metric.completion_event, ExperimentDataWarehouseNode)self.is_data_warehouse_query = start_is_dw or completion_is_dw- self.is_ratio_metric = isinstance(self.query.metric, ExperimentRatioMetric)self.stats_method = get_experiment_stats_method(self.experiment)diff --git a/products/experiments/backend/hogql_queries/exposure_query_logic.py b/products/experiments/backend/hogql_queries/exposure_query_logic.pyindex 7af5a15cd850..5a005fbf719d 100644--- a/products/experiments/backend/hogql_queries/exposure_query_logic.py+++ b/products/experiments/backend/hogql_queries/exposure_query_logic.py@@ -19,13 +19,11 @@ from posthog.schema import ()from posthog.hogql import ast-from posthog.hogql.parser import parse_exprfrom posthog.hogql.property import action_to_expr, property_to_exprfrom posthog.models.team.team import Teamfrom products.actions.backend.models.action import Action-from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEYlogger = logging.getLogger(__name__)@@ -167,39 +165,6 @@ def get_multiple_variant_handling_from_experiment(return MultipleVariantHandling.EXCLUDE-def get_variant_selection_expr(- feature_flag_variant_property: str, multiple_variant_handling: MultipleVariantHandling-) -> ast.Expr:- """- Returns the appropriate variant selection expression based on multiple_variant_handling configuration.-- Args:- feature_flag_variant_property: The property name containing the variant value- multiple_variant_handling: How to handle multiple exposures (EXCLUDE or FIRST_SEEN)- """- variant_property_field = ast.Field(chain=["properties", feature_flag_variant_property])-- match multiple_variant_handling:- case MultipleVariantHandling.FIRST_SEEN:- # Use variant from earliest exposure (minimum timestamp)- return parse_expr(- "argMin({variant_property}, timestamp)",- placeholders={- "variant_property": variant_property_field,- },- )- case _:- # Default behavior is EXCLUDE. Users who have seen more than one variant is assigned to the- # MULTIPLE_VARIANT_KEY group- return parse_expr(- "if(count(distinct {variant_property}) > 1, {multiple_variant_key}, any({variant_property}))",- placeholders={- "variant_property": variant_property_field,- "multiple_variant_key": ast.Constant(value=MULTIPLE_VARIANT_KEY),- },- )--def get_test_accounts_filter(team: Team, exposure_criteria: Union[ExperimentExposureCriteria, dict, None] = None) -> list[ast.Expr]:diff --git a/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.py b/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.pydeleted file mode 100644index c0e8d9128971..000000000000--- a/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.py+++ /dev/null@@ -1,101 +0,0 @@-from posthog.test.base import BaseTest--from parameterized import parameterized-from rest_framework.exceptions import ValidationError--from posthog.schema import EventsNode, ExperimentDataWarehouseNode, ExperimentMeanMetric, ExperimentMetricMathType--from posthog.hogql import ast--from products.experiments.backend.hogql_queries.base_query_utils import get_metric_value, get_source_value_expr---class TestHogQLAggregationIntegration(BaseTest):- def test_get_metric_value_with_hogql_aggregation(self):- """Test that get_metric_value correctly extracts inner expressions from HogQL aggregations."""-- # Test with aggregation function- metric_with_agg = ExperimentMeanMetric(- source=EventsNode(- event="revenue_event",- math=ExperimentMetricMathType.HOGQL,- math_hogql="sum(properties.revenue - properties.expense)",- )- )-- result = get_metric_value(metric_with_agg)-- # Should return the inner expression (ArithmeticOperation), not the full sum() call- self.assertIsInstance(result, ast.ArithmeticOperation)- self.assertEqual(result.op, ast.ArithmeticOperationOp.Sub) # type: ignore[attr-defined]-- # Test without aggregation function- metric_without_agg = ExperimentMeanMetric(- source=EventsNode(- event="revenue_event", math=ExperimentMetricMathType.HOGQL, math_hogql="properties.revenue"- )- )-- result_no_agg = get_metric_value(metric_without_agg)-- # Should return the field expression directly- self.assertIsInstance(result_no_agg, ast.Field)- self.assertEqual(result_no_agg.chain, ["properties", "revenue"]) # type: ignore[attr-defined]-- @parameterized.expand(- [- ("division", "sum(properties.revenue) / count()"),- ("addition", "sum(properties.a) + sum(properties.b)"),- ("wrapped", "toFloat(sum(properties.revenue))"),- ("nested", "avg(sum(properties.revenue))"),- ]- )- def test_rejects_compound_aggregate_expressions(self, _name: str, expr: str):- # The extracted value expression is evaluated per row; aggregates left inside it- # (compound or nested) would fail in ClickHouse with NOT_AN_AGGREGATE.- metric = ExperimentMeanMetric(- source=EventsNode(event="revenue_event", math=ExperimentMetricMathType.HOGQL, math_hogql=expr)- )- with self.assertRaises(ValidationError):- get_metric_value(metric)-- def test_allows_scalar_md5_despite_registry_quirk(self):- # md5 lives in HOGQL_AGGREGATIONS for its rewriting but compiles to a scalar —- # it must not trip the aggregate check.- metric = ExperimentMeanMetric(- source=EventsNode(- event="revenue_event",- math=ExperimentMetricMathType.HOGQL,- math_hogql="count(distinct md5(properties.user))",- )- )- result = get_metric_value(metric)- self.assertIsInstance(result, ast.Call)- self.assertEqual(result.name, "md5") # type: ignore[attr-defined]-- def test_rejects_aggregates_in_data_warehouse_math_property(self):- source = ExperimentDataWarehouseNode(- table_name="payments",- events_join_key="person_id",- data_warehouse_join_key="user_id",- timestamp_field="ts",- math_property="sum(amount)",- )- with self.assertRaises(ValidationError):- get_source_value_expr(source)-- @parameterized.expand(- [- ("plain_column", "amount"),- ("scalar_md5", "md5(user_id)"),- ]- )- def test_allows_per_row_data_warehouse_math_property(self, _name: str, math_property: str):- source = ExperimentDataWarehouseNode(- table_name="payments",- events_join_key="person_id",- data_warehouse_join_key="user_id",- timestamp_field="ts",- math_property=math_property,- )- get_source_value_expr(source)diff --git a/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_utils.py b/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_utils.pyindex ebf53a9fcf5a..8cd9b24ac483 100644--- a/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_utils.py+++ b/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_utils.py@@ -1,8 +1,14 @@from posthog.test.base import BaseTest+from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from posthog.schema import EventsNode, ExperimentDataWarehouseNode, ExperimentMeanMetric, ExperimentMetricMathType+from posthog.hogql import astfrom posthog.hogql.parser import parse_expr+from products.experiments.backend.hogql_queries.base_query_utils import get_source_value_exprfrom products.experiments.backend.hogql_queries.hogql_aggregation_utils import (build_aggregation_call,extract_aggregation_and_inner_expr,@@ -171,3 +177,90 @@ class TestHogQLAggregationUtils(BaseTest):self.assertIsInstance(result_no_params, ast.Call)self.assertEqual(result_no_params.name, "sum")self.assertIsNone(result_no_params.params)++ def test_source_value_expr_with_hogql_aggregation(self):+ # Test with aggregation function+ metric_with_agg = ExperimentMeanMetric(+ source=EventsNode(+ event="revenue_event",+ math=ExperimentMetricMathType.HOGQL,+ math_hogql="sum(properties.revenue - properties.expense)",+ )+ )++ result = get_source_value_expr(metric_with_agg.source)++ # Should return the inner expression (ArithmeticOperation), not the full sum() call+ self.assertIsInstance(result, ast.ArithmeticOperation)+ self.assertEqual(result.op, ast.ArithmeticOperationOp.Sub) # type: ignore[attr-defined]++ # Test without aggregation function+ metric_without_agg = ExperimentMeanMetric(+ source=EventsNode(+ event="revenue_event", math=ExperimentMetricMathType.HOGQL, math_hogql="properties.revenue"+ )+ )++ result_no_agg = get_source_value_expr(metric_without_agg.source)++ # Should return the field expression directly+ self.assertIsInstance(result_no_agg, ast.Field)+ self.assertEqual(result_no_agg.chain, ["properties", "revenue"]) # type: ignore[attr-defined]++ @parameterized.expand(+ [+ ("division", "sum(properties.revenue) / count()"),+ ("addition", "sum(properties.a) + sum(properties.b)"),+ ("wrapped", "toFloat(sum(properties.revenue))"),+ ("nested", "avg(sum(properties.revenue))"),+ ]+ )+ def test_rejects_compound_aggregate_expressions(self, _name: str, expr: str):+ # The extracted value expression is evaluated per row; aggregates left inside it+ # (compound or nested) would fail in ClickHouse with NOT_AN_AGGREGATE.+ metric = ExperimentMeanMetric(+ source=EventsNode(event="revenue_event", math=ExperimentMetricMathType.HOGQL, math_hogql=expr)+ )+ with self.assertRaises(ValidationError):+ get_source_value_expr(metric.source)++ def test_allows_scalar_md5_despite_registry_quirk(self):+ # md5 lives in HOGQL_AGGREGATIONS for its rewriting but compiles to a scalar —+ # it must not trip the aggregate check.+ metric = ExperimentMeanMetric(+ source=EventsNode(+ event="revenue_event",+ math=ExperimentMetricMathType.HOGQL,+ math_hogql="count(distinct md5(properties.user))",+ )+ )+ result = get_source_value_expr(metric.source)+ self.assertIsInstance(result, ast.Call)+ self.assertEqual(result.name, "md5") # type: ignore[attr-defined]++ def test_rejects_aggregates_in_data_warehouse_math_property(self):+ source = ExperimentDataWarehouseNode(+ table_name="payments",+ events_join_key="person_id",+ data_warehouse_join_key="user_id",+ timestamp_field="ts",+ math_property="sum(amount)",+ )+ with self.assertRaises(ValidationError):+ get_source_value_expr(source)++ @parameterized.expand(+ [+ ("plain_column", "amount"),+ ("scalar_md5", "md5(user_id)"),+ ]+ )+ def test_allows_per_row_data_warehouse_math_property(self, _name: str, math_property: str):+ source = ExperimentDataWarehouseNode(+ table_name="payments",+ events_join_key="person_id",+ data_warehouse_join_key="user_id",+ timestamp_field="ts",+ math_property=math_property,+ )+ get_source_value_expr(source)