: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(marketing-analytics): remove old per-goal attributed precompute (#60734)
Javier Bahamondesd710ee720572
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 3e73a24f0595..be5ef2d22b9b 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -64,9 +64,6 @@ from posthog.hogql.database.schema.app_metrics2 import AppMetrics2Tablefrom posthog.hogql.database.schema.channel_type import create_initial_channel_type, create_initial_domain_typefrom posthog.hogql.database.schema.cohort_membership import CohortMembershipTablefrom posthog.hogql.database.schema.cohort_people import CohortPeople, RawCohortPeople-from posthog.hogql.database.schema.conversion_goal_attributed_preaggregated import (- ConversionGoalAttributedPreaggregatedTable,-)from posthog.hogql.database.schema.document_embeddings import (HOGQL_MODEL_TABLES,DocumentEmbeddingsTable,@@ -404,10 +401,6 @@ def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:"web_overview_preaggregated": TableNode(name="web_overview_preaggregated", table=WebOverviewPreaggregatedTable()),- "conversion_goal_attributed_preaggregated": TableNode(- name="conversion_goal_attributed_preaggregated",- table=ConversionGoalAttributedPreaggregatedTable(),- ),"marketing_touchpoints_preaggregated": TableNode(name="marketing_touchpoints_preaggregated",table=MarketingTouchpointsPreaggregatedTable(),diff --git a/posthog/hogql/database/schema/conversion_goal_attributed_preaggregated.py b/posthog/hogql/database/schema/conversion_goal_attributed_preaggregated.pydeleted file mode 100644index a5da5f842299..000000000000--- a/posthog/hogql/database/schema/conversion_goal_attributed_preaggregated.py+++ /dev/null@@ -1,73 +0,0 @@-from pydantic import Field--from posthog.hogql.constants import HogQLQuerySettings-from posthog.hogql.database.models import (- DateDatabaseField,- DateTimeDatabaseField,- FieldOrTable,- FloatDatabaseField,- IntegerDatabaseField,- StringDatabaseField,- Table,-)--from posthog.clickhouse.preaggregation.conversion_goal_attributed_sql import (- CONVERSION_GOAL_ATTRIBUTED_TRACKED_FIELD_NAMES,- DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE,-)---def _build_fields() -> dict[str, FieldOrTable]:- fields: dict[str, FieldOrTable] = {- "team_id": IntegerDatabaseField(name="team_id"),- "job_id": StringDatabaseField(- name="job_id", description="Identifier of the preaggregation job that produced this row."- ),- "person_id": StringDatabaseField(- name="person_id", description="Person credited with the conversion; join to `persons`."- ),- "conversion_timestamp": DateTimeDatabaseField(- name="conversion_timestamp", description="When the conversion occurred (UTC)."- ),- "conversion_value": FloatDatabaseField(- name="conversion_value",- description="Value of the conversion (e.g. revenue or count for the conversion goal).",- ),- "touchpoint_timestamp": DateTimeDatabaseField(- name="touchpoint_timestamp", description="When the attributed marketing touchpoint occurred (UTC)."- ),- "touchpoint_weight": FloatDatabaseField(- name="touchpoint_weight",- description="Attribution weight of this touchpoint; single-touch is 1.0, multi-touch emits fractional weights summing to 1 across the conversion's rows.",- ),- }- for tracked_name in CONVERSION_GOAL_ATTRIBUTED_TRACKED_FIELD_NAMES:- col = f"{tracked_name}_name"- fields[col] = StringDatabaseField(- name=col, description=f"Value of the '{tracked_name}' marketing attribute for the attributed touchpoint."- )- fields["computed_at"] = DateTimeDatabaseField(- name="computed_at", description="When this preaggregated row was computed; also the ReplacingMergeTree version."- )- fields["expires_at"] = DateDatabaseField(- name="expires_at", description="Date when this row expires and is dropped via TTL."- )- return fields---class ConversionGoalAttributedPreaggregatedTable(Table):- description: str = (- "Internal preaggregated table holding the attributed output of the conversion-goal pipeline: "- "one row per (team, job, person, conversion, touchpoint) with the attribution weight for that touchpoint."- )- top_level_settings: HogQLQuerySettings | None = Field(- default_factory=lambda: HogQLQuerySettings(load_balancing="in_order")- )-- fields: dict[str, FieldOrTable] = _build_fields()-- def to_printed_clickhouse(self, context):- return DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE()-- def to_printed_hogql(self):- return "conversion_goal_attributed_preaggregated"diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex f3770ce3053c..454140eb16b5 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -376,7 +376,6 @@ class LazyComputationTable(StrEnum):PREAGGREGATION_RESULTS = "preaggregation_results"EXPERIMENT_EXPOSURES_PREAGGREGATED = "experiment_exposures_preaggregated"EXPERIMENT_METRIC_EVENTS_PREAGGREGATED = "experiment_metric_events_preaggregated"- CONVERSION_GOAL_ATTRIBUTED_PREAGGREGATED = "conversion_goal_attributed_preaggregated"MARKETING_TOUCHPOINTS_PREAGGREGATED = "marketing_touchpoints_preaggregated"MARKETING_CONVERSIONS_PREAGGREGATED = "marketing_conversions_preaggregated"MARKETING_COSTS_PREAGGREGATED = "marketing_costs_preaggregated"@@ -398,7 +397,6 @@ class LazyComputationTable(StrEnum):_DATE_EXPIRES_AT_TABLES: set[LazyComputationTable] = {LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,LazyComputationTable.EXPERIMENT_METRIC_EVENTS_PREAGGREGATED,- LazyComputationTable.CONVERSION_GOAL_ATTRIBUTED_PREAGGREGATED,LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED,LazyComputationTable.MARKETING_COSTS_PREAGGREGATED,diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goal_processor_refactor.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goal_processor_refactor.ambrindex dce33b6b87f5..f0227cf09390 100644--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goal_processor_refactor.ambr+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goal_processor_refactor.ambr@@ -1,119 +1,4 @@# serializer version: 1-# name: TestConversionGoalProcessorRefactor.test_precompute_insert_template_sql_snapshot- '''-- SELECT- person_id AS person_id,- if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,- if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,- if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,- if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,- if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,- if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,- if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,- if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,- if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,- 1 AS conversion_value,- fromUnixTimestamp(conversion_time) AS conversion_timestamp,- fromUnixTimestamp(if(greater(last_utm_timestamp, 0), last_utm_timestamp, conversion_time)) AS touchpoint_timestamp,- 1.0 AS touchpoint_weight- FROM- (- SELECT- person_id,- conversion_timestamps[i] AS conversion_time,- conversion_math_values[i] AS conversion_math_value,- conversion_campaigns[i] AS conversion_campaign,- conversion_sources[i] AS conversion_source,- conversion_mediums[i] AS conversion_medium,- conversion_contents[i] AS conversion_content,- conversion_terms[i] AS conversion_term,- conversion_referring_domains[i] AS conversion_referring_domain,- conversion_gclids[i] AS conversion_gclid,- conversion_fbclids[i] AS conversion_fbclid,- conversion_gad_sources[i] AS conversion_gad_source,- arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,- if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,- if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,- if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,- if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,- if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,- if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,- if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,- if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,- if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source- FROM- (- SELECT- events.person_id,- arrayFilter(x -> greater(x, 0), groupArray(if(equals(events.event, 'purchase'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,- arrayFilter(x -> greater(x, 0), groupArray(if(equals(events.event, 'purchase'), toFloat(1), 0))) AS conversion_math_values,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'purchase'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,- arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources- FROM- events- WHERE- or(and(equals(events.event, 'purchase'), greaterOrEquals(events.timestamp, toDateTime('2025-01-01 00:00:00.000000')), lessOrEquals(events.timestamp, toDateTime('2025-01-02 00:00:00.000000'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2025-01-01 00:00:00.000000'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2025-01-02 00:00:00.000000'))))- GROUP BY- events.person_id- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)- LIMIT 50000- '''-# ----# name: TestConversionGoalProcessorRefactor.test_precompute_read_query_sql_snapshot- '''-- SELECT- if(notEmpty(campaign_name), campaign_name, 'organic') AS match_key,- if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,- if(notEmpty(campaign_id), campaign_id, '-') AS id,- if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,- count() AS conversion_0- FROM- (- SELECT- person_id,- campaign_name,- source_name,- medium_name,- content_name,- term_name,- referring_domain_name,- gclid_name,- fbclid_name,- gad_source_name,- '-' AS campaign_id,- multiply(conversion_value, touchpoint_weight) AS conversion_value- FROM- conversion_goal_attributed_preaggregated- WHERE- and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2025-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2025-01-31 00:00:00.000000')))) AS attributed_conversions- GROUP BY- campaign,- id,- source- LIMIT 50000- '''-# ---# name: TestConversionGoalProcessorRefactor.test_snapshot_funnel_query_multi_touch_linear'''diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.pyindex c7b0f8dd5afb..c1445d16e657 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py@@ -321,24 +321,6 @@ class ConversionGoalProcessor:return self._generate_funnel_query(additional_conditions, date_from, date_to)return self._generate_direct_query(additional_conditions)- def get_precompute_hash_inputs(self) -> dict:- """Stable cache key for this goal's precomputed output.-- Changing any field here invalidates prior caches — required because the preagg table- stores the resolved attribution with scalar UTM columns tied to TRACKED_FIELDS.- """- return {- "team_id": self.team.pk,- "goal_kind": self.goal.kind,- "goal_event": getattr(self.goal, "event", None),- "goal_action_id": getattr(self.goal, "id", None) if self.goal.kind == "ActionsNode" else None,- "goal_property_filters": [p.model_dump() for p in (getattr(self.goal, "properties", None) or [])],- "schema_map": dict(getattr(self.goal, "schema_map", None) or {}),- "attribution_window_days": self.config.attribution_window_days,- "attribution_mode": str(self.config.attribution_mode),- "tracked_fields": [f.name for f in TRACKED_FIELDS],- }-def _generate_funnel_query(self,additional_conditions: Sequence[ast.Expr],@@ -421,73 +403,6 @@ class ConversionGoalProcessor:)return bool(restricted) and not restricted.isdisjoint(self._precompute_materialized_event_properties())- def _build_attributed_source_from_precompute(- self, date_from: datetime, date_to: datetime- ) -> Optional[ast.SelectQuery]:- """Ensure precompute exists and return a SelectQuery reading from the preagg table.-- Returns None if jobs are not ready — caller falls back to direct path.- """- insert_select = self.get_attributed_query_for_precomputation()-- result = ensure_precomputed(- team=self.team,- insert_query=insert_select,- time_range_start=date_from,- time_range_end=date_to,- ttl_seconds={- "0d": 15 * 60,- "1d": 60 * 60,- "7d": 24 * 60 * 60,- "default": 7 * 24 * 60 * 60,- },- table=LazyComputationTable.CONVERSION_GOAL_ATTRIBUTED_PREAGGREGATED,- )-- if not result.ready:- return None-- return self.build_attributed_source_from_precomputed(- job_ids=result.job_ids,- date_from=date_from,- date_to=date_to,- )-- def get_attributed_query_for_precomputation(self) -> ast.SelectQuery:- """Build the INSERT SELECT AST that materialises one job's pre-attributed rows.-- The time window is left as ``time_window_min``/``time_window_max`` placeholders that the lazy- framework resolves per job. Single-touch emits weight=1.0; multi-touch emits N rows per- conversion with fractional weights that sum to 1.- """- if self.goal.kind not in ("EventsNode", "ActionsNode"):- raise NotImplementedError(f"Precompute is not supported for goal kind {self.goal.kind!r}")- if self.goal.kind == "EventsNode" and not self.goal.event:- raise NotImplementedError("EventsNode goal requires a specific event for precompute")- if self.goal.kind == "ActionsNode" and not getattr(self.goal, "id", None):- raise NotImplementedError("ActionsNode goal requires an action id for precompute")-- additional_conditions: list[ast.Expr] = [- ast.CompareOperation(- left=ast.Field(chain=["events", "timestamp"]),- op=ast.CompareOperationOp.GtEq,- right=ast.Placeholder(expr=ast.Field(chain=["time_window_min"])),- ),- ast.CompareOperation(- left=ast.Field(chain=["events", "timestamp"]),- op=ast.CompareOperationOp.LtEq,- right=ast.Placeholder(expr=ast.Field(chain=["time_window_max"])),- ),- ]- array_collection = self.build_array_collection_query(additional_conditions)-- attribution_window_seconds = self.config.attribution_window_days * DAY_IN_SECONDS- if self.config.is_multi_touch:- array_join = self._build_multi_touch_array_join_subquery(array_collection, attribution_window_seconds)- return self._build_multi_touch_attribution_subquery(array_join, for_precompute=True)- array_join = self._build_single_touch_array_join_subquery(array_collection, attribution_window_seconds)- return self._build_single_touch_attribution_subquery(array_join, for_precompute=True)-def build_conversions_precompute_query(self) -> ast.SelectQuery:"""Per-goal conversion precompute: one row per conversion event, independent of attribution modeor window. The query embeds the goal's event/action + property filters + math, so its query hash@@ -874,63 +789,6 @@ class ConversionGoalProcessor:),)- def build_attributed_source_from_precomputed(- self,- job_ids: Sequence[str | uuid.UUID],- date_from: datetime,- date_to: datetime,- ) -> ast.SelectQuery:- """Read pre-attributed rows from the preagg table.-- Multiplies ``conversion_value * touchpoint_weight`` at read time so the- downstream final aggregation works uniformly for single- and multi-touch- (weight=1.0 is a no-op for single-touch).- """- select_columns: list[ast.Expr] = [ast.Field(chain=["person_id"])]- select_columns.extend(ast.Field(chain=[f.attributed_name]) for f in TRACKED_FIELDS)- select_columns.append(ast.Alias(alias="campaign_id", expr=ast.Constant(value="-")))- select_columns.append(- ast.Alias(- alias="conversion_value",- expr=ast.ArithmeticOperation(- left=ast.Field(chain=["conversion_value"]),- op=ast.ArithmeticOperationOp.Mult,- right=ast.Field(chain=["touchpoint_weight"]),- ),- )- )-- return ast.SelectQuery(- select=select_columns,- select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "conversion_goal_attributed_preaggregated"])),- where=ast.And(- exprs=[- ast.Call(- name="in",- args=[- ast.Field(chain=["job_id"]),- ast.Tuple(exprs=[ast.Constant(value=str(jid)) for jid in job_ids]),- ],- ),- ast.CompareOperation(- left=ast.Field(chain=["team_id"]),- op=ast.CompareOperationOp.Eq,- right=ast.Constant(value=self.team.pk),- ),- ast.CompareOperation(- left=ast.Field(chain=["conversion_timestamp"]),- op=ast.CompareOperationOp.GtEq,- right=ast.Constant(value=date_from),- ),- ast.CompareOperation(- left=ast.Field(chain=["conversion_timestamp"]),- op=ast.CompareOperationOp.LtEq,- right=ast.Constant(value=date_to),- ),- ]- ),- )-def _build_array_collection_subquery(self, conversion_event: Optional[str], where_conditions: list[ast.Expr]) -> ast.SelectQuery:@@ -1880,24 +1738,19 @@ class ConversionGoalProcessor:def _build_multi_touch_attribution_subquery(self,array_join_query: ast.SelectQuery,- for_precompute: bool = False,) -> ast.SelectQuery:"""Build subquery that explodes touchpoints and applies multi-touch weights.Takes one row per conversion (from array_join_query) and produces one rowper touchpoint, each with the attribution weight for that touchpoint.- When for_precompute=True, emits raw conversion_value + touchpoint_timestamp- + touchpoint_weight as separate columns (the read path multiplies). When- False, emits conversion_value = value * weight for direct-path consumption.+ Emits conversion_value = value * weight for direct-path consumption."""# Inner subquery: ARRAY JOIN on touchpoints to explode themtouchpoint_select: list[ast.Expr] = [ast.Field(chain=["person_id"]),ast.Field(chain=["conversion_math_value"]),]- if for_precompute:- touchpoint_select.append(ast.Field(chain=["conversion_time"]))for field in TRACKED_FIELDS:touchpoint_select.append(ast.Field(chain=[field.conversion_value]))@@ -1923,17 +1776,6 @@ class ConversionGoalProcessor:))- if for_precompute:- touchpoint_select.append(- ast.Alias(- alias="touchpoint_time",- expr=ast.ArrayAccess(- array=ast.Field(chain=["filtered_utm_timestamps"]),- property=ast.Field(chain=["tp_idx"]),- ),- )- )-touchpoint_exploded = ast.SelectQuery(select=touchpoint_select,select_from=ast.JoinExpr(table=array_join_query),@@ -1949,10 +1791,9 @@ class ConversionGoalProcessor:],)- # for_precompute: alias person_id so the lazy-computation INSERT builder gets a named column.person_id_field = ast.Field(chain=["person_id"])outer_select: list[ast.Expr] = [- ast.Alias(alias="person_id", expr=person_id_field) if for_precompute else person_id_field,+ person_id_field,]for field in TRACKED_FIELDS:@@ -1963,35 +1804,19 @@ class ConversionGoalProcessor:))- if for_precompute:- outer_select.extend(- [- ast.Alias(alias="conversion_value", expr=self._get_final_conversion_value_expr()),- ast.Alias(- alias="conversion_timestamp",- expr=ast.Call(name="fromUnixTimestamp", args=[ast.Field(chain=["conversion_time"])]),- ),- ast.Alias(- alias="touchpoint_timestamp",- expr=ast.Call(name="fromUnixTimestamp", args=[ast.Field(chain=["touchpoint_time"])]),- ),- ast.Alias(alias="touchpoint_weight", expr=ast.Field(chain=["attribution_weight"])),- ]- )- else:- outer_select.extend(- [- ast.Alias(alias="campaign_id", expr=ast.Constant(value="-")),- ast.Alias(- alias="conversion_value",- expr=ast.ArithmeticOperation(- left=self._get_final_conversion_value_expr(),- op=ast.ArithmeticOperationOp.Mult,- right=ast.Field(chain=["attribution_weight"]),- ),+ outer_select.extend(+ [+ ast.Alias(alias="campaign_id", expr=ast.Constant(value="-")),+ ast.Alias(+ alias="conversion_value",+ expr=ast.ArithmeticOperation(+ left=self._get_final_conversion_value_expr(),+ op=ast.ArithmeticOperationOp.Mult,+ right=ast.Field(chain=["attribution_weight"]),),- ]- )+ ),+ ]+ )return ast.SelectQuery(select=outer_select,@@ -2001,18 +1826,11 @@ class ConversionGoalProcessor:def _build_single_touch_attribution_subquery(self,array_join_query: ast.SelectQuery,- for_precompute: bool = False,) -> ast.SelectQuery:- """Build subquery that applies attribution logic.-- When for_precompute=True, emits the extra columns that the preagg INSERT- stores (conversion_timestamp, touchpoint_timestamp, touchpoint_weight=1.0)- and drops the constant campaign_id (the read path re-injects it).- """- # for_precompute: alias person_id so the lazy-computation INSERT builder gets a named column.+ """Build subquery that applies attribution logic."""person_id_field = ast.Field(chain=["person_id"])select_columns: list[ast.Expr] = [- ast.Alias(alias="person_id", expr=person_id_field) if for_precompute else person_id_field,+ person_id_field,]for field in TRACKED_FIELDS:@@ -2023,14 +1841,13 @@ class ConversionGoalProcessor:))- if not for_precompute:- select_columns.append(- ast.Alias(- alias="campaign_id",- # Campaign IDs don't exist in event data, only in marketing platform data- expr=ast.Constant(value="-"),- )+ select_columns.append(+ ast.Alias(+ alias="campaign_id",+ # Campaign IDs don't exist in event data, only in marketing platform data+ expr=ast.Constant(value="-"),)+ )select_columns.append(ast.Alias(@@ -2039,41 +1856,6 @@ class ConversionGoalProcessor:))- if for_precompute:- # fromUnixTimestamp, not toDateTime: timestamps are Int64 here and toDateTime expects String in HogQL.- # Organic conversions (no UTM pageview in attribution window) leave last_utm_timestamp=0- # via arrayMax over an empty array; fall back to conversion_time so the stored DateTime- # is meaningful instead of 1970-01-01.- select_columns.extend(- [- ast.Alias(- alias="conversion_timestamp",- expr=ast.Call(name="fromUnixTimestamp", args=[ast.Field(chain=["conversion_time"])]),- ),- ast.Alias(- alias="touchpoint_timestamp",- expr=ast.Call(- name="fromUnixTimestamp",- args=[- ast.Call(- name="if",- args=[- ast.CompareOperation(- left=ast.Field(chain=["last_utm_timestamp"]),- op=ast.CompareOperationOp.Gt,- right=ast.Constant(value=0),- ),- ast.Field(chain=["last_utm_timestamp"]),- ast.Field(chain=["conversion_time"]),- ],- ),- ],- ),- ),- ast.Alias(alias="touchpoint_weight", expr=ast.Constant(value=1.0)),- ]- )-return ast.SelectQuery(select=select_columns,select_from=ast.JoinExpr(table=array_join_query),diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.pyindex 5c8c14f6e5e4..b98d19abb3bd 100644--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py@@ -12,9 +12,6 @@ from posthog.hogql import astfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.execute import sync_execute-from posthog.clickhouse.preaggregation.conversion_goal_attributed_sql import (- TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,-)from posthog.clickhouse.preaggregation.marketing_conversions_sql import TRUNCATE_MARKETING_CONVERSIONS_TABLE_SQLfrom posthog.clickhouse.preaggregation.marketing_touchpoints_sql import TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL@@ -34,7 +31,6 @@ class TestConversionGoalPrecomputeEquivalence(ClickhouseTestMixin, APIBaseTest):super().tearDown()def _clean_preaggregation_data(self):- sync_execute(TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL())sync_execute(TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL())sync_execute(TRUNCATE_MARKETING_CONVERSIONS_TABLE_SQL())PreaggregationJob.objects.all().delete()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 780665191c07..2c2b61508330 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@@ -7,19 +7,11 @@ from unittest.mock import patchfrom parameterized import parameterized-from posthog.schema import (- AttributionMode,- BaseMathType,- ConversionGoalFilter1,- ConversionGoalFilter3,- EventPropertyFilter,- PropertyOperator,-)+from posthog.schema import AttributionMode, BaseMathType, ConversionGoalFilter1, EventPropertyFilter, PropertyOperatorfrom posthog.hogql import astfrom posthog.hogql.context import HogQLContext-from posthog.hogql.placeholders import find_placeholders, replace_placeholders-from posthog.hogql.printer import prepare_and_print_ast, to_printed_hogql+from posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.test.utils import pretty_print_in_testsfrom products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import ConversionGoalProcessor@@ -42,45 +34,14 @@ def _make_event_goal()-def _make_data_warehouse_goal() -> ConversionGoalFilter3:- return ConversionGoalFilter3(- kind="DataWarehouseNode",- id="stripe_charges",- id_field="id",- table_name="stripe_charges",- distinct_id_field="customer_email",- timestamp_field="created_at",- conversion_goal_id="goal_dw",- conversion_goal_name="Test DW Goal",- schema_map={"utm_campaign_name": "utm_campaign"},- )---def _resolve_precompute_select(select_ast: ast.SelectQuery) -> ast.SelectQuery:- """Resolve the time-window placeholders the way the lazy framework does per job."""- resolved = replace_placeholders(- select_ast,- {- "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),- "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),- },- )- assert isinstance(resolved, ast.SelectQuery)- return resolved--class TestConversionGoalProcessorRefactor(BaseTest):- """Tests for the public refactor surface.-- Contract tests pin the shape of the new public API:+ """Contract tests for the public attribution pipeline surface:- build_array_collection_query returns a SelectQuery grouped by person_id- build_attribution_pipeline accepts any SelectQuery with the array schema- composition pipeline(collection(...)) equals _generate_funnel_query(...)- Snapshot tests pin the actual HogQL SQL of _generate_funnel_query so the- refactor can be diffed against the pre-refactor baseline: revert the- processor file to master, regenerate snapshots, stage them, re-apply the- refactor, regenerate again, and read the git diff on the .ambr file.+ Snapshot tests pin the actual HogQL SQL of _generate_funnel_query so changes in the+ pipeline can be diffed against the prior baseline."""CLASS_DATA_LEVEL_SETUP = False@@ -123,33 +84,6 @@ class TestConversionGoalProcessorRefactor(BaseTest):assert self._print_sql(composed) == self._print_sql(funnel_direct)- def test_hash_inputs_stable_for_identical_goals(self):- a = self._processor()- b = self._processor()- assert a.get_precompute_hash_inputs() == b.get_precompute_hash_inputs()-- def test_hash_inputs_differ_for_different_event(self):- a = self._processor(event="purchase")- b = self._processor(event="signup")- assert a.get_precompute_hash_inputs() != b.get_precompute_hash_inputs()-- def test_hash_inputs_differ_for_different_attribution_window(self):- a = self._processor()- a.config.attribution_window_days = 30- b = self._processor()- b.config.attribution_window_days = 90- assert a.get_precompute_hash_inputs() != b.get_precompute_hash_inputs()-- def test_hash_inputs_includes_team_id(self):- processor = self._processor()- assert processor.get_precompute_hash_inputs()["team_id"] == self.team.pk-- def test_hash_inputs_serializable(self):- import json-- processor = self._processor()- json.dumps(processor.get_precompute_hash_inputs(), default=str, sort_keys=True)-def test_attribution_pipeline_respects_multi_touch_config(self):single_touch_processor = self._processor()single_touch_processor.config.attribution_mode = AttributionMode.LAST_TOUCH@@ -163,59 +97,10 @@ class TestConversionGoalProcessorRefactor(BaseTest):assert single.select != multi.select- def test_hash_inputs_depend_on_attribution_mode(self):- first = self._processor()- first.config.attribution_mode = AttributionMode.FIRST_TOUCH-- last = self._processor()- last.config.attribution_mode = AttributionMode.LAST_TOUCH-- assert first.get_precompute_hash_inputs() != last.get_precompute_hash_inputs()-- def test_precompute_query_exposes_time_window_placeholders(self):- processor = self._processor()- select_ast = processor.get_attributed_query_for_precomputation()- placeholder_fields = find_placeholders(select_ast).placeholder_fields- assert ["time_window_min"] in placeholder_fields- assert ["time_window_max"] in placeholder_fields-- def test_precompute_query_resolves_with_framework_placeholders(self):- processor = self._processor()- resolved = _resolve_precompute_select(processor.get_attributed_query_for_precomputation())- assert isinstance(resolved, ast.SelectQuery)-- def test_precompute_query_matches_preagg_table_columns(self):- processor = self._processor()- write_template = _resolve_precompute_select(processor.get_attributed_query_for_precomputation())- aliases = [e.alias for e in write_template.select if isinstance(e, ast.Alias)]- for col in write_template.select:- assert isinstance(col, ast.Alias), f"SELECT column not aliased: {col}"- assert "person_id" in aliases- from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import TRACKED_FIELDS-- for field in TRACKED_FIELDS:- assert field.attributed_name in aliases, field.attributed_name- assert "conversion_value" in aliases- assert "conversion_timestamp" in aliases- assert "touchpoint_timestamp" in aliases- assert "touchpoint_weight" in aliases- # campaign_id is injected at read time, not stored.- assert "campaign_id" not in aliases-- def test_precompute_template_raises_for_unsupported_goal_kinds(self):- processor = ConversionGoalProcessor(- goal=_make_data_warehouse_goal(),- index=0,- team=self.team,- config=MarketingAnalyticsConfig(),- )- with pytest.raises(NotImplementedError):- processor.get_attributed_query_for_precomputation()-def test_precompute_skipped_when_tracked_property_restricted(self):- # Precompute materializes tracked attribution properties into scalar columns, bypassing the- # per-user masking HogQL applies to events.properties. When such a property is restricted for- # the user, eligibility must fail so the direct (masked) events query is used instead.+ # Precompute materializes tracked attribution properties via the touchpoints table, bypassing+ # the per-user masking HogQL applies to events.properties. When such a property is restricted+ # for the user, eligibility must fail so the direct (masked) events query is used instead.processor = self._processor()processor.config.conversion_goal_precomputation_enabled = Truedate_from = datetime(2025, 1, 1, tzinfo=UTC)@@ -231,68 +116,14 @@ class TestConversionGoalProcessorRefactor(BaseTest):with patch(target, return_value={"utm_source"}):assert processor._should_use_precompute(date_from, date_to) is False- def test_precompute_query_supports_multi_touch(self):- processor = self._processor()- processor.config.attribution_mode = AttributionMode.LINEAR- parsed = _resolve_precompute_select(processor.get_attributed_query_for_precomputation())- aliases = [e.alias for e in parsed.select if isinstance(e, ast.Alias)]- assert "touchpoint_weight" in aliases- assert "touchpoint_timestamp" in aliases- assert "conversion_timestamp" in aliases-- def test_build_attributed_source_from_precomputed_is_final_aggregateable(self):- processor = self._processor()- read = processor.build_attributed_source_from_precomputed(- job_ids=["00000000-0000-0000-0000-000000000001"],- date_from=datetime(2025, 1, 1, tzinfo=UTC),- date_to=datetime(2025, 1, 31, tzinfo=UTC),- )- assert isinstance(read, ast.SelectQuery)-- final = processor._build_final_aggregation_query(read)- assert isinstance(final, ast.SelectQuery)-- def test_tracked_fields_match_preagg_table_schema(self):- from posthog.clickhouse.preaggregation.conversion_goal_attributed_sql import (- CONVERSION_GOAL_ATTRIBUTED_TRACKED_FIELD_NAMES,+ def test_tracked_fields_match_touchpoints_table_schema(self):+ from posthog.clickhouse.preaggregation.marketing_touchpoints_sql import (+ MARKETING_TOUCHPOINTS_TRACKED_FIELD_NAMES,)from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import TRACKED_FIELDS- assert [f.name for f in TRACKED_FIELDS] == CONVERSION_GOAL_ATTRIBUTED_TRACKED_FIELD_NAMES-- def test_hash_inputs_change_when_tracked_fields_change(self):- from products.marketing_analytics.backend.hogql_queries import conversion_goal_processor as cgp-- processor = self._processor()- baseline = processor.get_precompute_hash_inputs()-- original = cgp.TRACKED_FIELDS- try:- cgp.TRACKED_FIELDS = [*original, cgp.TrackedField("test_field", "utm_test")]- mutated = self._processor().get_precompute_hash_inputs()- finally:- cgp.TRACKED_FIELDS = original-- assert baseline != mutated- assert baseline["tracked_fields"] != mutated["tracked_fields"]-- @pytest.mark.usefixtures("unittest_snapshot")- def test_precompute_insert_template_sql_snapshot(self):- processor = self._processor()- parsed = _resolve_precompute_select(processor.get_attributed_query_for_precomputation())- assert pretty_print_in_tests(to_printed_hogql(parsed, team=self.team), self.team.pk) == self.snapshot-- @pytest.mark.usefixtures("unittest_snapshot")- def test_precompute_read_query_sql_snapshot(self):- processor = self._processor()- read = processor.build_attributed_source_from_precomputed(- job_ids=["00000000-0000-0000-0000-000000000001"],- date_from=datetime(2025, 1, 1, tzinfo=UTC),- date_to=datetime(2025, 1, 31, tzinfo=UTC),- )- final = processor._build_final_aggregation_query(read)- assert pretty_print_in_tests(to_printed_hogql(final, team=self.team), self.team.pk) == self.snapshot+ assert [f.name for f in TRACKED_FIELDS] == MARKETING_TOUCHPOINTS_TRACKED_FIELD_NAMES@parameterized.expand([diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.pyindex b8f89b983aba..5cf236b34228 100644--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py@@ -20,9 +20,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_in_testsfrom posthog.clickhouse.client.execute import sync_execute-from posthog.clickhouse.preaggregation.conversion_goal_attributed_sql import (- TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,-)+from posthog.clickhouse.preaggregation.marketing_touchpoints_sql import TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQLfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.actions.backend.models.action import Action@@ -67,7 +65,7 @@ def _normalize_job_uuids(hogql: str) -> str:class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):def setUp(self):super().setUp()- sync_execute(TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL())+ sync_execute(TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL())PreaggregationJob.objects.all().delete()# Force deterministic job_ids so the precompute snapshots are stable in CI.self._job_uuid_patcher = patch.object(