: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
fix(marketing-analytics): serve goals on revenue virtual properties live (#108114)
Lucas Ricoy4631fe288e9f
diff --git a/posthog/hogql/database/schema/persons.py b/posthog/hogql/database/schema/persons.pyindex d4c9dd61c98f..19e9a21b7527 100644--- a/posthog/hogql/database/schema/persons.py+++ b/posthog/hogql/database/schema/persons.py@@ -68,6 +68,10 @@ PERSONS_FIELDS: dict[str, FieldOrTable] = {}+# Virtual properties that resolve only through the revenue analytics join.+REVENUE_ANALYTICS_VIRTUAL_PROPERTIES = frozenset({"$virt_mrr", "$virt_revenue"})++def _is_virtual_field_requiring_join(expr: ast.Expr) -> bool:"""Check if an expression references a virtual field that requires a joined table.@@ -79,7 +83,7 @@ def _is_virtual_field_requiring_join(expr: ast.Expr) -> bool:for chain_item in expr.chain:if isinstance(chain_item, str) and chain_item.startswith("$virt_"):# Currently, all $virt_ fields that require joins are revenue analytics fields- if chain_item in ("$virt_mrr", "$virt_revenue"):+ if chain_item in REVENUE_ANALYTICS_VIRTUAL_PROPERTIES:return Trueelif isinstance(expr, ast.Call):# Check arguments of function calls recursivelydiff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.pyindex 1306c4ead77c..ee719b16395f 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py@@ -56,6 +56,17 @@ def action_match_expr(conversion_goal: ConversionGoal, team: Team) -> Optional[areturn action_to_expr(action)+def action_property_keys(conversion_goal: ConversionGoal, team: Team) -> list[str]:+ """Property keys the goal's action steps filter on; empty when the goal has no resolvable action."""+ if not isinstance(conversion_goal, ConversionGoalFilter2) or not conversion_goal.id:+ return []+ try:+ action = Action.objects.get(pk=int(conversion_goal.id), team__project_id=team.project_id)+ except (Action.DoesNotExist, TypeError, ValueError):+ return []+ return [prop["key"] for step in action.steps for prop in step.properties or [] if prop.get("key")]++def conversion_goal_match_expr(conversion_goal: ConversionGoal, team: Team) -> Optional[ast.Expr]:"""The event or action half of the goal, without its property filters.diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.pyindex 58f6646afe5c..931e92c07298 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py@@ -23,6 +23,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_exprfrom posthog.hogql.database.schema.exchange_rate import convert_currency_call+from posthog.hogql.database.schema.persons import REVENUE_ANALYTICS_VIRTUAL_PROPERTIESfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.timings import HogQLTimings@@ -47,6 +48,7 @@ from .attribution_weights import ()from .conversion_goal_conditions import (action_match_expr,+ action_property_keys,add_conversion_goal_property_filters,conversion_goal_match_expr,)@@ -586,6 +588,8 @@ class ConversionGoalProcessor:for prop in self.goal.properties or []:if prop.type in ("person", "cohort"):return False+ if self._uses_revenue_analytics_property():+ return False# The shared touchpoints precompute is config-agnostic: build_touchpoints_precompute_query()# always materializes the default UTM property names. A goal that remaps any tracked field via# schema_map would read mismatched columns on the conversion side, so use the direct path.@@ -593,6 +597,23 @@ class ConversionGoalProcessor:return Falsereturn True+ def _uses_revenue_analytics_property(self) -> bool:+ """The revenue virtual properties resolve only through the revenue analytics join, which the+ precompute's plain events scan does not carry, so printing its INSERT fails with "Field not found".+ Other `$virt_` properties map to columns on the events table and precompute fine.++ A substring match, because a HogQL filter's key is a whole expression such as+ `person.properties.$virt_mrr > 0`.+ """+ keys = [getattr(self.goal, "math_property", None)]+ currency = getattr(self.goal, "math_property_revenue_currency", None)+ if currency is not None:+ keys.append(currency.property)+ keys.extend(getattr(prop, "key", None) for prop in self.goal.properties or [])+ if self.goal.kind == "ActionsNode":+ keys.extend(action_property_keys(self.goal, self.team))+ return any(name in key for key in keys if key for name in REVENUE_ANALYTICS_VIRTUAL_PROPERTIES)+def _should_use_precompute(self, date_from: Optional[datetime], date_to: Optional[datetime]) -> bool:"""Read-path eligibility: flag on, explicit date range, goal precomputable, no restricted props."""if not self.config.conversion_goal_precomputation_enabled:diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.pyindex 6cea02ee9ef5..341d8a71d537 100644--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py@@ -11,7 +11,9 @@ from posthog.schema import (AttributionMode,BaseMathType,ConversionGoalFilter1,+ ConversionGoalFilter2,EventPropertyFilter,+ HogQLPropertyFilter,PropertyOperator,RevenueCurrencyPropertyConfig,)@@ -23,6 +25,7 @@ from posthog.hogql.test.utils import pretty_print_in_testsfrom posthog.models import PropertyDefinition+from products.actions.backend.models.action import Actionfrom products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import ConversionGoalProcessorfrom products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig@@ -175,6 +178,69 @@ class TestConversionGoalProcessorRefactor(BaseTest):is expected)+ @parameterized.expand(+ [+ ("revenue_math_property", {"math_property": "$virt_revenue"}, False),+ (+ "revenue_currency_property",+ {+ "math_property": "amount",+ "math_property_revenue_currency": RevenueCurrencyPropertyConfig(property="$virt_mrr"),+ },+ False,+ ),+ (+ "revenue_property_filter",+ {"properties": [EventPropertyFilter(key="$virt_mrr", operator=PropertyOperator.GT, value=0)]},+ False,+ ),+ (+ "revenue_hogql_filter",+ {"properties": [HogQLPropertyFilter(key="person.properties.$virt_mrr > 0")]},+ False,+ ),+ (+ "other_virtual_property",+ {+ "properties": [+ EventPropertyFilter(key="$virt_is_bot", operator=PropertyOperator.EXACT, value="false")+ ]+ },+ True,+ ),+ ]+ )+ def test_revenue_analytics_properties_are_not_precomputable(self, _name: str, goal_overrides: dict, expected: bool):+ # The precompute INSERT has no revenue analytics join, so a goal on a revenue virtual property+ # fails to print there on every warm and must never be treated as precomputable.+ assert self._processor(**goal_overrides).is_goal_precomputable() is expected++ def test_action_step_on_revenue_property_is_not_precomputable(self):+ # An action goal pulls its steps' filters into the INSERT, so they must be checked too.+ action = Action.objects.create(+ team=self.team,+ name="Paying purchase",+ steps_json=[+ {+ "event": "purchase",+ "properties": [{"key": "$virt_revenue", "type": "person", "value": 0, "operator": "gt"}],+ }+ ],+ )+ goal = ConversionGoalFilter2(+ kind="ActionsNode",+ id=str(action.id),+ conversion_goal_id="goal_action",+ conversion_goal_name="Action goal",+ math=BaseMathType.TOTAL,+ schema_map={"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},+ )+ processor = ConversionGoalProcessor(+ goal=goal, index=0, team=self.team, config=MarketingAnalyticsConfig(), filter_test_accounts=False+ )++ assert processor.is_goal_precomputable() is False+def test_tracked_fields_match_touchpoints_table_schema(self):from posthog.clickhouse.preaggregation.marketing_touchpoints_sql import (MARKETING_TOUCHPOINTS_TRACKED_FIELD_NAMES,