: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(marketing-analytics): lazy-computed conversion goal attribution (#55005)
Javier Bahamondes23ee22582a72
diff --git a/posthog/clickhouse/migrations/0261_conversion_goal_attributed_preaggregated.py b/posthog/clickhouse/migrations/0261_conversion_goal_attributed_preaggregated.pynew file mode 100644index 000000000000..f9048a91875b--- /dev/null+++ b/posthog/clickhouse/migrations/0261_conversion_goal_attributed_preaggregated.py@@ -0,0 +1,17 @@+from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from posthog.clickhouse.preaggregation.conversion_goal_attributed_sql import (+ DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,+ SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,+)++operations = [+ run_sql_with_exceptions(+ SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ ),+ run_sql_with_exceptions(+ DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL(),+ node_roles=[NodeRole.AUX, NodeRole.DATA],+ ),+]diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txtindex b5ebd205cc04..263d0bb811c0 100644--- a/posthog/clickhouse/migrations/max_migration.txt+++ b/posthog/clickhouse/migrations/max_migration.txt@@ -1 +1 @@-0260_web_stats_paths_preaggregated+0261_conversion_goal_attributed_preaggregateddiff --git a/posthog/clickhouse/preaggregation/conversion_goal_attributed_sql.py b/posthog/clickhouse/preaggregation/conversion_goal_attributed_sql.pynew file mode 100644index 000000000000..27073bd6ece7--- /dev/null+++ b/posthog/clickhouse/preaggregation/conversion_goal_attributed_sql.py@@ -0,0 +1,101 @@+# Pre-attributed output of the conversion-goal pipeline: one row per+# (team, job, person, conversion_timestamp, touchpoint_timestamp) with the+# attribution weight for that touchpoint. Single-touch emits weight=1.0 and one+# row per conversion; multi-touch emits N rows per conversion with fractional+# weights that sum to 1.++from django.conf import settings++from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree++TABLE_BASE_NAME = "conversion_goal_attributed_preaggregated"++# Keep in lockstep with TRACKED_FIELDS in conversion_goal_processor.py.+# test_conversion_goal_processor_refactor.py enforces this.+CONVERSION_GOAL_ATTRIBUTED_TRACKED_FIELD_NAMES: list[str] = [+ "campaign",+ "source",+ "medium",+ "content",+ "term",+ "referring_domain",+ "gclid",+ "fbclid",+ "gad_source",+]+++def DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE():+ return TABLE_BASE_NAME+++def SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE():+ return f"sharded_{TABLE_BASE_NAME}"+++def SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_ENGINE():+ return ReplacingMergeTree(TABLE_BASE_NAME, ver="computed_at")+++def _attributed_field_columns() -> str:+ """Render one ``{name}_name String,`` per tracked field."""+ return "\n ".join(f"{name}_name String," for name in CONVERSION_GOAL_ATTRIBUTED_TRACKED_FIELD_NAMES)+++CONVERSION_GOAL_ATTRIBUTED_TABLE_BASE_SQL = f"""+CREATE TABLE IF NOT EXISTS {{table_name}}+(+ team_id Int64,+ job_id UUID,++ person_id UUID,+ conversion_timestamp DateTime64(6, 'UTC'),+ conversion_value Float64,++ touchpoint_timestamp DateTime64(6, 'UTC'),+ touchpoint_weight Float64,++ {_attributed_field_columns()}++ computed_at DateTime64(6, 'UTC') DEFAULT now(),+ expires_at Date DEFAULT today() + INTERVAL 7 DAY+) ENGINE = {{engine}}+"""+++def SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL():+ return (+ CONVERSION_GOAL_ATTRIBUTED_TABLE_BASE_SQL+ + """+PARTITION BY toYYYYMMDD(expires_at)+ORDER BY (team_id, job_id, person_id, conversion_timestamp, touchpoint_timestamp)+TTL expires_at+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1+"""+ ).format(+ table_name=SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE(),+ engine=SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_ENGINE(),+ )+++def DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL():+ return CONVERSION_GOAL_ATTRIBUTED_TABLE_BASE_SQL.format(+ table_name=DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE(),+ engine=Distributed(+ data_table=SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE(),+ sharding_key="cityHash64(person_id)",+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,+ ),+ )+++def DROP_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE()}"+++def DROP_SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE()} SYNC"+++def TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL():+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE()}"diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex dd1f437ef7f3..026f387ed5ca 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -33,6 +33,10 @@ from posthog.clickhouse.plugin_log_entries import (PLUGIN_LOG_ENTRIES_TABLE_SQL,PLUGIN_LOG_ENTRIES_WRITABLE_TABLE_SQL,)+from posthog.clickhouse.preaggregation.conversion_goal_attributed_sql import (+ DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,+ SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,+)from posthog.clickhouse.preaggregation.experiment_exposures_sql import (DISTRIBUTED_EXPERIMENT_EXPOSURES_TABLE_SQL,SHARDED_EXPERIMENT_EXPOSURES_TABLE_SQL,@@ -306,6 +310,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (SHARDED_PREAGGREGATION_RESULTS_TABLE_SQL,SHARDED_EXPERIMENT_EXPOSURES_TABLE_SQL,SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE_SQL,+ SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL,DISTINCT_ID_USAGE_DATA_TABLE_SQL,@@ -364,6 +369,7 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (DISTRIBUTED_PREAGGREGATION_RESULTS_TABLE_SQL,DISTRIBUTED_EXPERIMENT_EXPOSURES_TABLE_SQL,DISTRIBUTED_EXPERIMENT_METRIC_EVENTS_TABLE_SQL,+ DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL,DOCUMENT_EMBEDDINGS_BUFFER_WRITABLE_TABLE_SQL,diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex 7f05d7e042bb..071c0e5d8002 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -1046,6 +1046,37 @@Order By (team_id, cohort_id, person_id, version)+ '''+# ---+# name: test_create_table_query[conversion_goal_attributed_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS conversion_goal_attributed_preaggregated+ (+ team_id Int64,+ job_id UUID,++ person_id UUID,+ conversion_timestamp DateTime64(6, 'UTC'),+ conversion_value Float64,++ touchpoint_timestamp DateTime64(6, 'UTC'),+ touchpoint_weight Float64,++ campaign_name String,+ source_name String,+ medium_name String,+ content_name String,+ term_name String,+ referring_domain_name String,+ gclid_name String,+ fbclid_name String,+ gad_source_name String,++ computed_at DateTime64(6, 'UTC') DEFAULT now(),+ expires_at Date DEFAULT today() + INTERVAL 7 DAY+ ) ENGINE = Distributed('aux', 'posthog_test', 'sharded_conversion_goal_attributed_preaggregated', cityHash64(person_id))+'''# ---# name: test_create_table_query[distinct_id_usage]@@ -5168,6 +5199,42 @@'''# ---+# name: test_create_table_query[sharded_conversion_goal_attributed_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS sharded_conversion_goal_attributed_preaggregated+ (+ team_id Int64,+ job_id UUID,++ person_id UUID,+ conversion_timestamp DateTime64(6, 'UTC'),+ conversion_value Float64,++ touchpoint_timestamp DateTime64(6, 'UTC'),+ touchpoint_weight Float64,++ campaign_name String,+ source_name String,+ medium_name String,+ content_name String,+ term_name String,+ referring_domain_name String,+ gclid_name String,+ fbclid_name String,+ gad_source_name String,++ computed_at DateTime64(6, 'UTC') DEFAULT now(),+ expires_at Date DEFAULT today() + INTERVAL 7 DAY+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.conversion_goal_attributed_preaggregated', '{replica}-{shard}', computed_at)++ PARTITION BY toYYYYMMDD(expires_at)+ ORDER BY (team_id, job_id, person_id, conversion_timestamp, touchpoint_timestamp)+ TTL expires_at+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1++ '''+# ---# name: test_create_table_query[sharded_distinct_id_usage]'''@@ -8524,6 +8591,42 @@'''# ---+# name: test_create_table_query_replicated_and_storage[sharded_conversion_goal_attributed_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS sharded_conversion_goal_attributed_preaggregated+ (+ team_id Int64,+ job_id UUID,++ person_id UUID,+ conversion_timestamp DateTime64(6, 'UTC'),+ conversion_value Float64,++ touchpoint_timestamp DateTime64(6, 'UTC'),+ touchpoint_weight Float64,++ campaign_name String,+ source_name String,+ medium_name String,+ content_name String,+ term_name String,+ referring_domain_name String,+ gclid_name String,+ fbclid_name String,+ gad_source_name String,++ computed_at DateTime64(6, 'UTC') DEFAULT now(),+ expires_at Date DEFAULT today() + INTERVAL 7 DAY+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.conversion_goal_attributed_preaggregated', '{replica}-{shard}', computed_at)++ PARTITION BY toYYYYMMDD(expires_at)+ ORDER BY (team_id, job_id, person_id, conversion_timestamp, touchpoint_timestamp)+ TTL expires_at+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1++ '''+# ---# name: test_create_table_query_replicated_and_storage[sharded_distinct_id_usage]'''diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex e71747697730..91b8993f7a0e 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -62,6 +62,9 @@ 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,@@ -293,6 +296,10 @@ def build_database_root_node(*, include_posthog_tables: bool = True) -> TableNod"web_overview_preaggregated": TableNode(name="web_overview_preaggregated", table=WebOverviewPreaggregatedTable()),+ "conversion_goal_attributed_preaggregated": TableNode(+ name="conversion_goal_attributed_preaggregated",+ table=ConversionGoalAttributedPreaggregatedTable(),+ ),"web_stats_paths_preaggregated": TableNode(name="web_stats_paths_preaggregated", table=WebStatsPathsPreaggregatedTable()),diff --git a/posthog/hogql/database/schema/conversion_goal_attributed_preaggregated.py b/posthog/hogql/database/schema/conversion_goal_attributed_preaggregated.pynew file mode 100644index 000000000000..4483c836c2a3--- /dev/null+++ b/posthog/hogql/database/schema/conversion_goal_attributed_preaggregated.py@@ -0,0 +1,49 @@+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"),+ "person_id": StringDatabaseField(name="person_id"),+ "conversion_timestamp": DateTimeDatabaseField(name="conversion_timestamp"),+ "conversion_value": FloatDatabaseField(name="conversion_value"),+ "touchpoint_timestamp": DateTimeDatabaseField(name="touchpoint_timestamp"),+ "touchpoint_weight": FloatDatabaseField(name="touchpoint_weight"),+ }+ for tracked_name in CONVERSION_GOAL_ATTRIBUTED_TRACKED_FIELD_NAMES:+ col = f"{tracked_name}_name"+ fields[col] = StringDatabaseField(name=col)+ fields["computed_at"] = DateTimeDatabaseField(name="computed_at")+ fields["expires_at"] = DateDatabaseField(name="expires_at")+ return fields+++class ConversionGoalAttributedPreaggregatedTable(Table):+ 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 6c6f49920924..bd122df21b84 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -276,6 +276,7 @@ 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"WEB_OVERVIEW_PREAGGREGATED = "web_overview_preaggregated"WEB_STATS_PREAGGREGATED = "web_stats_preaggregated"WEB_STATS_PATHS_PREAGGREGATED = "web_stats_paths_preaggregated"@@ -287,6 +288,7 @@ class LazyComputationTable(StrEnum):_DATE_EXPIRES_AT_TABLES: set[LazyComputationTable] = {LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,LazyComputationTable.EXPERIMENT_METRIC_EVENTS_PREAGGREGATED,+ LazyComputationTable.CONVERSION_GOAL_ATTRIBUTED_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 9c55dfd8d566..a9e0c4467166 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,4 +1,131 @@# 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']), '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/__snapshots__/test_conversion_goals_aggregator.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goals_aggregator.ambrindex b35a777fa8e9..7ac5977fc6cd 100644--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goals_aggregator.ambr+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_conversion_goals_aggregator.ambr@@ -21,82 +21,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'purchase'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,@@ -133,82 +74,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'purchase'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,@@ -245,82 +127,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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, 'conversion'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,- arrayFilter(x -> greater(x, 0), groupArray(if(equals(events.event, 'conversion'), toFloat(1), 0))) AS conversion_math_values,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'conversion'), 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'conversion'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,@@ -357,82 +180,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'purchase'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,@@ -473,82 +237,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'purchase'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,@@ -568,82 +273,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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, 'sign_up'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,- arrayFilter(x -> greater(x, 0), groupArray(if(equals(events.event, 'sign_up'), toFloat(1), 0))) AS conversion_math_values,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'sign_up'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,@@ -663,82 +309,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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, 'login'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,- arrayFilter(x -> greater(x, 0), groupArray(if(equals(events.event, 'login'), toFloat(1), 0))) AS conversion_math_values,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'login'), 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'login'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000003')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,@@ -777,82 +364,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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, 'sign_up'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,- arrayFilter(x -> greater(x, 0), groupArray(if(equals(events.event, 'sign_up'), toFloat(1), 0))) AS conversion_math_values,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(events.event, 'sign_up'), 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'sign_up'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000001')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,@@ -871,82 +399,23 @@(SELECTperson_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,+ campaign_name,+ source_name,+ medium_name,+ content_name,+ term_name,+ referring_domain_name,+ gclid_name,+ fbclid_name,+ gad_source_name,'-' AS campaign_id,- 1 AS conversion_value+ multiply(conversion_value, touchpoint_weight) AS conversion_valueFROM- (- 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-+ conversion_goal_attributed_preaggregated+WHERE- or(and(equals(events.event, 'purchase'), greaterOrEquals(events.timestamp, toDateTime('2023-01-01')), less(events.timestamp, toDateTime('2023-02-01'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2023-01-01'), toIntervalSecond(7776000)))))-- GROUP BY- events.person_id-- HAVING- greater(length(conversion_timestamps), 0))- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions+ and(in(job_id, tuple('00000000-0000-0000-0000-000000000002')), equals(team_id, 420), greaterOrEquals(conversion_timestamp, toDateTime('2023-01-01 00:00:00.000000')), lessOrEquals(conversion_timestamp, toDateTime('2023-01-31 23:59:59.999999')))) AS attributed_conversionsGROUP BYcampaign,diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.pyindex 50b2ed26e050..3d31d7077646 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py@@ -1,8 +1,13 @@+import reimport math+import uuidfrom collections.abc import Sequencefrom dataclasses import dataclass+from datetime import UTC, datetimefrom typing import ClassVar, Optional, Union+import structlog+from posthog.schema import (AttributionMode,BaseMathType,@@ -16,14 +21,17 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_exprfrom posthog.hogql.modifiers import create_default_modifiers_for_team+from posthog.hogql.printer import to_printed_hogqlfrom posthog.hogql.property import action_to_expr, property_to_expr-from posthog.models import Team+from posthog.models import PropertyDefinition, Team, User+from products.access_control.backend.property_access_control import get_restricted_property_namesfrom products.actions.backend.models.action import Actionfrom .adapters.factory import MarketingSourceFactoryfrom .marketing_analytics_config import MarketingAnalyticsConfig+from .metrics import CONVERSION_GOAL_PRECOMPUTE_FALLBACK_COUNTERDAY_IN_SECONDS = 86400LN2 = math.log(2) # ≈ 0.693, used in half-life formula: weight = exp(-ln(2) * t / half_life)@@ -32,6 +40,12 @@ LN2 = math.log(2) # ≈ 0.693, used in half-life formula: weight = exp(-ln(2) *# This follows the industry standard (Google Analytics, Adobe, Mixpanel all use 7-day half-life).TIME_DECAY_HALF_LIFE_DIVISOR = 4+# Sentinel datetimes swapped for {time_window_min/max} placeholders after HogQL printing.+_PRECOMPUTE_TIME_WINDOW_MIN_SENTINEL = datetime(2099, 12, 31, 23, 59, 58, 123456, tzinfo=UTC)+_PRECOMPUTE_TIME_WINDOW_MAX_SENTINEL = datetime(2099, 12, 31, 23, 59, 59, 654321, tzinfo=UTC)++logger = structlog.get_logger(__name__)+@dataclassclass TrackedField:@@ -92,6 +106,8 @@ class ConversionGoalProcessor:index: intteam: Teamconfig: MarketingAnalyticsConfig+ # Requesting user, threaded through to enforce per-user property access on the precompute path.+ user: Optional[User] = None_UTM_LEVEL_FIELD_MAP: ClassVar[dict[MarketingAnalyticsDrillDownLevel, str]] = {MarketingAnalyticsDrillDownLevel.MEDIUM: "medium",@@ -203,14 +219,15 @@ class ConversionGoalProcessor:return schema_map.get("timestamp_field", "timestamp")return "events.timestamp"- def generate_cte_query(self, additional_conditions: Sequence[ast.Expr]) -> ast.SelectQuery:- """- Generate main CTE query for conversion goal.-- Routes to appropriate query type based on goal configuration.- """+ def generate_cte_query(+ self,+ additional_conditions: Sequence[ast.Expr],+ date_from: Optional[datetime] = None,+ date_to: Optional[datetime] = None,+ ) -> ast.SelectQuery:+ """Generate main CTE query for conversion goal."""if self.goal.kind in ["EventsNode", "ActionsNode"]:- return self._generate_array_based_query(additional_conditions)+ return self._generate_array_based_query(additional_conditions, date_from, date_to)return self._generate_direct_query(additional_conditions)def build_array_collection_query(self, additional_conditions: Sequence[ast.Expr]) -> ast.SelectQuery:@@ -240,17 +257,253 @@ class ConversionGoalProcessor:return self._build_final_aggregation_query(attribution)- def _generate_array_based_query(self, additional_conditions: Sequence[ast.Expr]) -> ast.SelectQuery:+ def _generate_array_based_query(+ self,+ additional_conditions: Sequence[ast.Expr],+ date_from: Optional[datetime] = None,+ date_to: Optional[datetime] = None,+ ) -> ast.SelectQuery:"""Generate array-based query with attribution logic for Events/Actions"""if self.config.attribution_window_days > 0:- return self._generate_funnel_query(additional_conditions)+ return self._generate_funnel_query(additional_conditions, date_from, date_to)return self._generate_direct_query(additional_conditions)- def _generate_funnel_query(self, additional_conditions: Sequence[ast.Expr]) -> ast.SelectQuery:- """Generate multi-step funnel query with attribution window"""+ 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],+ date_from: Optional[datetime] = None,+ date_to: Optional[datetime] = None,+ ) -> ast.SelectQuery:+ """Generate multi-step funnel query with attribution window.++ Reads the preagg table when eligible, falls back to events scan on any failure.+ """+ if self._should_use_precompute(date_from, date_to):+ # `_should_use_precompute` returns False unless both dates are set; narrow for mypy.+ assert date_from is not None and date_to is not None+ try:+ precomputed_attribution = self._build_attributed_source_from_precompute(date_from, date_to)+ if precomputed_attribution is not None:+ return self._build_final_aggregation_query(precomputed_attribution)+ except Exception:+ CONVERSION_GOAL_PRECOMPUTE_FALLBACK_COUNTER.inc()+ logger.exception(+ "conversion_goal_precompute_failed",+ goal_id=self.goal.conversion_goal_id,+ team_id=self.team.pk,+ )+array_collection = self.build_array_collection_query(additional_conditions)return self.build_attribution_pipeline(array_collection)+ def _should_use_precompute(self, date_from: Optional[datetime], date_to: Optional[datetime]) -> bool:+ """Eligibility check: flag on, explicit date range, Events/Actions goal, no person/cohort filters."""+ if not self.config.conversion_goal_precomputation_enabled:+ return False+ if date_from is None or date_to is None:+ return False+ if self.goal.kind not in ("EventsNode", "ActionsNode"):+ return False+ if self.goal.kind == "EventsNode" and not self.goal.event:+ return False+ # Only ConversionGoalFilter2 (ActionsNode) has `id` — guard with getattr.+ if self.goal.kind == "ActionsNode" and not getattr(self.goal, "id", None):+ return False+ if self.config.attribution_window_days <= 0:+ return False+ for prop in self.goal.properties or []:+ if prop.type in ("person", "cohort"):+ return False+ if self._precompute_properties_restricted_for_user():+ return False+ return True++ def _precompute_materialized_event_properties(self) -> set[str]:+ """Event property names the precompute path resolves into scalar columns of the preagg table."""+ props = {self._resolve_field_name(field) for field in TRACKED_FIELDS}+ math_property = getattr(self.goal, "math_property", None)+ if math_property:+ props.add(math_property)+ return props++ def _precompute_properties_restricted_for_user(self) -> bool:+ """True if any property the precompute would materialize is restricted for the requesting user.++ The precompute path resolves these ``events.properties`` reads server-side and stores them as+ plain scalar columns, which bypasses the per-user property masking HogQL applies to+ ``events.properties`` at print time. When any such property is restricted, skip precompute so+ the direct events query — which enforces masking via ``JSONDropKeys`` — is used instead.+ """+ restricted = get_restricted_property_names(+ team_id=self.team.pk,+ user=self.user,+ property_type=PropertyDefinition.Type.EVENT,+ )+ 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.+ """+ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ LazyComputationTable,+ ensure_precomputed,+ )++ query_string, placeholders = self.get_attributed_query_for_precomputation()++ result = ensure_precomputed(+ team=self.team,+ insert_query=query_string,+ 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,+ placeholders=placeholders,+ )++ 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) -> tuple[str, dict[str, ast.Expr]]:+ """Build the INSERT template that materialises one job's pre-attributed rows.++ Uses {time_window_min}/{time_window_max} placeholders resolved by the framework.+ 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.Constant(value=_PRECOMPUTE_TIME_WINDOW_MIN_SENTINEL),+ ),+ ast.CompareOperation(+ left=ast.Field(chain=["events", "timestamp"]),+ op=ast.CompareOperationOp.LtEq,+ right=ast.Constant(value=_PRECOMPUTE_TIME_WINDOW_MAX_SENTINEL),+ ),+ ]+ 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)+ insert_select = self._build_multi_touch_attribution_subquery(array_join, for_precompute=True)+ else:+ array_join = self._build_single_touch_array_join_subquery(array_collection, attribution_window_seconds)+ insert_select = self._build_single_touch_attribution_subquery(array_join, for_precompute=True)++ printed = to_printed_hogql(insert_select, team=self.team)+ for sentinel, placeholder in (+ (_PRECOMPUTE_TIME_WINDOW_MIN_SENTINEL, "{time_window_min}"),+ (_PRECOMPUTE_TIME_WINDOW_MAX_SENTINEL, "{time_window_max}"),+ ):+ printed = _replace_sentinel_datetime(printed, sentinel, placeholder)++ if _PRECOMPUTE_SENTINEL_LITERAL_RE.search(printed):+ raise RuntimeError(+ "Failed to substitute precompute time-window sentinels — printer format may have changed"+ )++ return printed, {}++ 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:@@ -1197,23 +1450,31 @@ class ConversionGoalProcessor:],)- def _build_multi_touch_attribution_subquery(self, array_join_query: ast.SelectQuery) -> ast.SelectQuery:+ 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 row per touchpoint, each with weighted conversion value.+ Takes one row per conversion (from array_join_query) and produces one row+ per 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."""# 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"]))- # Add conversion fields for each tracked field (for direct attribution)for field in TRACKED_FIELDS:touchpoint_select.append(ast.Field(chain=[field.conversion_value]))- # Extract individual touchpoint UTM values via array join indexfor field in TRACKED_FIELDS:touchpoint_select.append(ast.Alias(@@ -1225,7 +1486,6 @@ class ConversionGoalProcessor:))- # Extract weight for this touchpointtouchpoint_select.append(ast.Alias(alias="attribution_weight",@@ -1236,6 +1496,17 @@ 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),@@ -1251,9 +1522,10 @@ class ConversionGoalProcessor:],)- # Outer subquery: apply attribution logic (direct vs fallback) and weight+ # 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.Field(chain=["person_id"]),+ ast.Alias(alias="person_id", expr=person_id_field) if for_precompute else person_id_field,]for field in TRACKED_FIELDS:@@ -1264,35 +1536,58 @@ class ConversionGoalProcessor:))- 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"]),+ 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"]),+ ),+ ),+ ]+ )return ast.SelectQuery(select=outer_select,select_from=ast.JoinExpr(table=touchpoint_exploded),)- def _build_single_touch_attribution_subquery(self, array_join_query: ast.SelectQuery) -> ast.SelectQuery:- """Build subquery that applies attribution logic"""+ 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.+ person_id_field = ast.Field(chain=["person_id"])select_columns: list[ast.Expr] = [- ast.Field(chain=["person_id"]),+ ast.Alias(alias="person_id", expr=person_id_field) if for_precompute else person_id_field,]- # Add attributed value for each tracked fieldfor field in TRACKED_FIELDS:select_columns.append(ast.Alias(@@ -1301,20 +1596,57 @@ class ConversionGoalProcessor:))- select_columns.extend(- [+ if not for_precompute:+ select_columns.append(ast.Alias(alias="campaign_id",# Campaign IDs don't exist in event data, only in marketing platform dataexpr=ast.Constant(value="-"),- ),- ast.Alias(- alias="conversion_value",- expr=self._get_final_conversion_value_expr(),- ),- ]+ )+ )++ select_columns.append(+ ast.Alias(+ alias="conversion_value",+ expr=self._get_final_conversion_value_expr(),+ ))+ 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),@@ -1756,6 +2088,16 @@ class ConversionGoalProcessor:return False+# Matches both HogQL toDateTime and ClickHouse toDateTime64 forms.+_PRECOMPUTE_SENTINEL_LITERAL_RE = re.compile(r"toDateTime(?:64)?\(\s*'2099-12-31 23:59:5[89]\.\d+'")+++def _replace_sentinel_datetime(printed: str, sentinel: datetime, replacement: str) -> str:+ literal = re.escape(sentinel.strftime("%Y-%m-%d %H:%M:%S.%f"))+ pattern = re.compile(rf"toDateTime(?:64)?\(\s*'{literal}'(?:\s*,\s*6(?:\s*,\s*'[^']+')?)?\s*\)")+ return pattern.sub(replacement, printed)++def add_conversion_goal_property_filters(conditions: list[ast.Expr],conversion_goal: ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3,diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.pyindex ccd53bb41e5c..8619cc54741b 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py@@ -1,8 +1,11 @@+from concurrent.futures import ThreadPoolExecutor+from posthog.schema import MarketingAnalyticsBaseColumns, MarketingAnalyticsDrillDownLevelfrom posthog.hogql import astfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.settings import TESTfrom products.marketing_analytics.backend.hogql_queries.constants import UNIFIED_CONVERSION_GOALS_CTE_ALIAS@@ -10,6 +13,12 @@ from .adapters.factory import MarketingSourceFactoryfrom .conversion_goal_processor import ConversionGoalProcessorfrom .marketing_analytics_config import MarketingAnalyticsConfig+# Cap on parallel per-goal ensure_precomputed workers.+# Each worker holds a Postgres connection during the round-trip; 8 keeps us comfortably+# below the per-process pool while still collapsing wall time for the common 1–4 goal+# case. Bump only after measuring PG/Redis pressure under realistic concurrency.+_GOAL_PARALLELISM_LIMIT = 8+class ConversionGoalsAggregator:"""@@ -26,11 +35,9 @@ class ConversionGoalsAggregator:if not self.processors:raise ValueError("Cannot create unified CTE without conversion goal processors")- # Step 1: Generate individual conversion goal queries- conversion_subqueries = []-- for processor in self.processors:- # Build additional conditions for this processor+ # Step 1: Generate individual conversion goal queries, parallelised across goals+ # so ensure_precomputed's PG+Redis+ClickHouse round-trips collapse to max(overhead).+ def _build_base_query(processor: ConversionGoalProcessor) -> ast.SelectQuery:date_field = processor.get_date_field()additional_conditions = additional_conditions_getter(date_range=date_range,@@ -38,10 +45,25 @@ class ConversionGoalsAggregator:date_field=date_field,use_date_not_datetime=True,)+ return processor.generate_cte_query(+ additional_conditions,+ date_from=date_range.date_from(),+ date_to=date_range.date_to(),+ )- # Generate the base conversion goal query- base_query = processor.generate_cte_query(additional_conditions)+ # Skip the pool in TEST: Django's per-thread DB connections don't see+ # fixtures created in the main test thread.+ if not TEST and len(self.processors) > 1:+ with ThreadPoolExecutor(+ max_workers=min(len(self.processors), _GOAL_PARALLELISM_LIMIT),+ thread_name_prefix="ma_cte",+ ) as pool:+ base_queries = list(pool.map(_build_base_query, self.processors))+ else:+ base_queries = [_build_base_query(p) for p in self.processors]+ conversion_subqueries = []+ for processor, base_query in zip(self.processors, base_queries):# Transform the query to include a column for this specific conversion goal# and zero columns for all other conversion goals# Note: base_query schema is: [0]=match_key, [1]=campaign, [2]=id, [3]=source, [4]=conversiondiff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.pyindex 93c070a97a23..b4e947d08839 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py@@ -425,7 +425,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,)if should_create:processor = ConversionGoalProcessor(- goal=conversion_goal, index=index, team=self.team, config=self.config+ goal=conversion_goal, index=index, team=self.team, config=self.config, user=self.user)processors.append(processor)return processorsdiff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.pyindex afab197ef8a7..74fdad436419 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py@@ -103,6 +103,8 @@ class MarketingAnalyticsConfig:attribution_window_days: int = 90attribution_mode: AttributionMode = AttributionMode.LAST_TOUCH+ conversion_goal_precomputation_enabled: bool = False+@classmethoddef from_team(cls, team: "Team") -> "MarketingAnalyticsConfig":"""Create config instance with team-specific attribution settings"""@@ -112,6 +114,14 @@ class MarketingAnalyticsConfig:config.attribution_window_days = ma_config.attribution_window_daysconfig.attribution_mode = AttributionMode(ma_config.attribution_mode)+ # Gate precomputation behind feature flag+ config.conversion_goal_precomputation_enabled = posthoganalytics.feature_enabled(+ "marketing-analytics-precomputation",+ str(team.uuid),+ groups={"organization": str(team.organization.id)},+ group_properties={"organization": {"id": str(team.organization.id)}},+ )+# Gate multi-touch attribution behind feature flagif config.attribution_mode in MULTI_TOUCH_MODES:has_multi_touch = posthoganalytics.feature_enabled(diff --git a/products/marketing_analytics/backend/hogql_queries/metrics.py b/products/marketing_analytics/backend/hogql_queries/metrics.pynew file mode 100644index 000000000000..7b0a41204daa--- /dev/null+++ b/products/marketing_analytics/backend/hogql_queries/metrics.py@@ -0,0 +1,6 @@+from prometheus_client import Counter++CONVERSION_GOAL_PRECOMPUTE_FALLBACK_COUNTER = Counter(+ "marketing_analytics_conversion_goal_precompute_fallback_total",+ "Conversion goal queries that fell back to the events scan after the precompute path raised",+)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.pynew file mode 100644index 000000000000..3eb89e0ed8a9--- /dev/null+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py@@ -0,0 +1,221 @@+from datetime import UTC, datetime++from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events++from django.test import override_settings++from parameterized import parameterized++from posthog.schema import AttributionMode, BaseMathType, ConversionGoalFilter1++from posthog.hogql import ast+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.execute import sync_execute+from posthog.clickhouse.preaggregation.conversion_goal_attributed_sql import (+ TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,+)++from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import ConversionGoalProcessor+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig+++@override_settings(IN_UNIT_TESTING=True)+class TestConversionGoalPrecomputeEquivalence(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self._clean_preaggregation_data()++ def tearDown(self):+ self._clean_preaggregation_data()+ super().tearDown()++ def _clean_preaggregation_data(self):+ sync_execute(TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL())+ PreaggregationJob.objects.all().delete()++ def _seed_events(self):+ """Seed a realistic mix that exercises every multi-touch branch.++ - user_a: 3 distinct touchpoints + 1 conversion → multi-touch distributes weight+ across spring, summer, fall (LINEAR = 1/3 each, POSITION_BASED puts 40% on+ spring and 40% on fall, TIME_DECAY favours fall).+ - user_b: 2 same-UTM touchpoints + 1 conversion → tests aggregation when multi-touch+ assigns fractional weight to the same (campaign, source) key twice.+ - user_c: 3 touchpoints + 2 conversions at different times → each conversion gets its+ own attribution window; mode is applied per-conversion.+ - user_d: 1 touchpoint inside window + 1 touchpoint OUTSIDE (60 days prior, window=30)+ + 1 conversion → the out-of-window pageview must be excluded identically in both+ paths.+ - user_e: conversion with no touchpoint → organic row; weight logic must not blow up.+ - user_f: pageview only, no conversion → must not appear anywhere.+ """+ for distinct_id in ("user_a", "user_b", "user_c", "user_d", "user_e", "user_f"):+ _create_person(distinct_ids=[distinct_id], team=self.team)++ # user_a: 3 distinct campaigns in order → spring, summer, fall.+ for day, (campaign, source, medium) in [+ (3, ("spring", "google", "cpc")),+ (6, ("summer", "facebook", "social")),+ (9, ("fall", "bing", "cpc")),+ ]:+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="user_a",+ timestamp=datetime(2025, 1, day, 10, 0, tzinfo=UTC),+ properties={"utm_campaign": campaign, "utm_source": source, "utm_medium": medium},+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id="user_a",+ timestamp=datetime(2025, 1, 12, 10, 0, tzinfo=UTC),+ properties={"value": 100},+ )++ # user_b: same (campaign, source) twice → multi-touch should aggregate into one row.+ for day in (4, 8):+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="user_b",+ timestamp=datetime(2025, 1, day, 10, 0, tzinfo=UTC),+ properties={"utm_campaign": "winter", "utm_source": "twitter", "utm_medium": "social"},+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id="user_b",+ timestamp=datetime(2025, 1, 11, 10, 0, tzinfo=UTC),+ properties={"value": 50},+ )++ # user_c: 3 touchpoints, 2 conversions (each should see a different attribution state).+ for day, (campaign, source) in [+ (2, ("newyear", "google")),+ (6, ("spring", "google")),+ (13, ("fall", "facebook")),+ ]:+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="user_c",+ timestamp=datetime(2025, 1, day, 10, 0, tzinfo=UTC),+ properties={"utm_campaign": campaign, "utm_source": source, "utm_medium": "cpc"},+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id="user_c",+ timestamp=datetime(2025, 1, 7, 10, 0, tzinfo=UTC),+ properties={"value": 30},+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id="user_c",+ timestamp=datetime(2025, 1, 15, 10, 0, tzinfo=UTC),+ properties={"value": 40},+ )++ # user_d: one touchpoint INSIDE window, one OUTSIDE (60 days prior with window=30).+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="user_d",+ timestamp=datetime(2024, 11, 10, 10, 0, tzinfo=UTC), # ~63 days before conversion+ properties={"utm_campaign": "stale", "utm_source": "google", "utm_medium": "cpc"},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="user_d",+ timestamp=datetime(2025, 1, 5, 10, 0, tzinfo=UTC),+ properties={"utm_campaign": "fresh", "utm_source": "google", "utm_medium": "cpc"},+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id="user_d",+ timestamp=datetime(2025, 1, 12, 10, 0, tzinfo=UTC),+ properties={"value": 20},+ )++ # user_e: conversion with no touchpoint (organic).+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id="user_e",+ timestamp=datetime(2025, 1, 14, 10, 0, tzinfo=UTC),+ properties={"value": 10},+ )++ # user_f: pageview only, no purchase.+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="user_f",+ timestamp=datetime(2025, 1, 9, 10, 0, tzinfo=UTC),+ properties={"utm_campaign": "spring", "utm_source": "bing", "utm_medium": "cpc"},+ )++ flush_persons_and_events()++ def _make_processor(+ self, *, precompute: bool, attribution_mode: AttributionMode = AttributionMode.LAST_TOUCH+ ) -> ConversionGoalProcessor:+ goal = ConversionGoalFilter1(+ kind="EventsNode",+ event="purchase",+ conversion_goal_id="goal_e2e",+ conversion_goal_name="E2E Goal",+ math=BaseMathType.TOTAL,+ schema_map={"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},+ properties=[],+ )+ config = MarketingAnalyticsConfig()+ config.attribution_window_days = 30+ config.attribution_mode = attribution_mode+ config.conversion_goal_precomputation_enabled = precompute+ return ConversionGoalProcessor(goal=goal, index=0, team=self.team, config=config)++ def _execute(self, query: ast.SelectQuery) -> list[tuple]:+ return execute_hogql_query(query, team=self.team).results or []++ @parameterized.expand(+ [+ (AttributionMode.LAST_TOUCH,),+ (AttributionMode.FIRST_TOUCH,),+ (AttributionMode.LINEAR,),+ (AttributionMode.TIME_DECAY,),+ (AttributionMode.POSITION_BASED,),+ ]+ )+ def test_direct_and_precomputed_paths_return_equivalent_rows(self, attribution_mode: AttributionMode):+ self._seed_events()++ date_from = datetime(2025, 1, 1, tzinfo=UTC)+ date_to = datetime(2025, 1, 31, tzinfo=UTC)++ direct_processor = self._make_processor(precompute=False, attribution_mode=attribution_mode)+ direct_query = direct_processor.generate_cte_query(additional_conditions=[])+ direct_rows = sorted(self._execute(direct_query))++ preagg_processor = self._make_processor(precompute=True, attribution_mode=attribution_mode)+ preagg_query = preagg_processor.generate_cte_query(+ additional_conditions=[],+ date_from=date_from,+ date_to=date_to,+ )+ preagg_rows = sorted(self._execute(preagg_query))++ assert _round_rows(direct_rows) == _round_rows(preagg_rows), (+ f"{attribution_mode}: precompute diverged from direct path.\ndirect: {direct_rows}\npreagg: {preagg_rows}"+ )+++def _round_rows(rows: list[tuple]) -> list[tuple]:+ """Round floats to avoid weight-multiplication rounding noise between paths."""+ return [tuple(round(v, 6) if isinstance(v, float) else v for v in row) for row in rows]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 253e9af14a99..76928c133183 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@@ -1,15 +1,25 @@+from datetime import UTC, datetimefrom typing import Anyimport pytestfrom posthog.test.base import BaseTest+from unittest.mock import patchfrom parameterized import parameterized-from posthog.schema import AttributionMode, BaseMathType, ConversionGoalFilter1, EventPropertyFilter, PropertyOperator+from posthog.schema import (+ AttributionMode,+ BaseMathType,+ ConversionGoalFilter1,+ ConversionGoalFilter3,+ EventPropertyFilter,+ PropertyOperator,+)from posthog.hogql import astfrom posthog.hogql.context import HogQLContext-from posthog.hogql.printer import prepare_and_print_ast+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import prepare_and_print_ast, to_printed_hogqlfrom posthog.hogql.test.utils import pretty_print_in_testsfrom products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import ConversionGoalProcessor@@ -32,6 +42,20 @@ 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"},+ )++class TestConversionGoalProcessorRefactor(BaseTest):"""Tests for the public refactor surface.@@ -67,7 +91,9 @@ class TestConversionGoalProcessorRefactor(BaseTest):result = processor.build_array_collection_query(additional_conditions=[])assert isinstance(result, ast.SelectQuery)assert result.group_by is not None- assert any(isinstance(g, ast.Field) and g.chain == ["events", "person_id"] for g in result.group_by)+ assert any(isinstance(g, ast.Field) and g.chain == ["events", "person_id"] for g in result.group_by), (+ "array collection must group by events.person_id"+ )def test_build_attribution_pipeline_accepts_collection_output(self):processor = self._processor()@@ -84,6 +110,199 @@ 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++ multi_touch_processor = self._processor()+ multi_touch_processor.config.attribution_mode = AttributionMode.LINEAR++ collection = single_touch_processor.build_array_collection_query(additional_conditions=[])+ single = single_touch_processor.build_attribution_pipeline(collection)+ multi = multi_touch_processor.build_attribution_pipeline(collection)++ 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_template_contains_time_window_placeholders(self):+ processor = self._processor()+ template, _ = processor.get_attributed_query_for_precomputation()+ assert "{time_window_min}" in template+ assert "{time_window_max}" in template++ def test_precompute_template_parses_with_framework_placeholders(self):+ processor = self._processor()+ template, custom_placeholders = processor.get_attributed_query_for_precomputation()+ placeholders = {+ **custom_placeholders,+ "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),+ "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),+ }+ parsed = parse_select(template, placeholders=placeholders)+ assert isinstance(parsed, ast.SelectQuery)++ def test_precompute_template_matches_preagg_table_columns(self):+ processor = self._processor()+ template, _ = processor.get_attributed_query_for_precomputation()+ placeholders: dict[str, ast.Expr] = {+ "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),+ "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),+ }+ write_template = parse_select(template, placeholders=placeholders)+ assert isinstance(write_template, ast.SelectQuery)+ 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.+ processor = self._processor()+ processor.config.conversion_goal_precomputation_enabled = True+ date_from = datetime(2025, 1, 1, tzinfo=UTC)+ date_to = datetime(2025, 1, 31, tzinfo=UTC)+ target = (+ "products.marketing_analytics.backend.hogql_queries.conversion_goal_processor.get_restricted_property_names"+ )++ with patch(target, return_value=set()):+ assert processor._should_use_precompute(date_from, date_to) is True++ # utm_source is one of the tracked attribution properties resolved from the goal's schema_map.+ with patch(target, return_value={"utm_source"}):+ assert processor._should_use_precompute(date_from, date_to) is False++ def test_precompute_template_supports_multi_touch(self):+ processor = self._processor()+ processor.config.attribution_mode = AttributionMode.LINEAR+ template, _ = processor.get_attributed_query_for_precomputation()+ placeholders: dict[str, ast.Expr] = {+ "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),+ "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),+ }+ parsed = parse_select(template, placeholders=placeholders)+ assert isinstance(parsed, ast.SelectQuery)+ 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,+ )++ 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()+ template, _ = processor.get_attributed_query_for_precomputation()+ placeholders: dict[str, ast.Expr] = {+ "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),+ "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),+ }+ parsed = parse_select(template, placeholders=placeholders)+ 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+@parameterized.expand([(AttributionMode.FIRST_TOUCH,),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 4e87486a4e24..b8f89b983aba 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@@ -1,7 +1,11 @@+import re+import uuid+import itertoolsfrom datetime import datetimeimport pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest.mock import patchfrom posthog.schema import (BaseMathType,@@ -9,26 +13,71 @@ from posthog.schema import (ConversionGoalFilter2,DateRange,MarketingAnalyticsBaseColumns,- NodeKind,)from posthog.hogql import astfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_in_tests+from posthog.clickhouse.client.execute import sync_execute+from posthog.clickhouse.preaggregation.conversion_goal_attributed_sql import (+ TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,+)from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.actions.backend.models.action import Action+from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJobfrom .conversion_goal_processor import ConversionGoalProcessorfrom .conversion_goals_aggregator import ConversionGoalsAggregatorfrom .marketing_analytics_config import MarketingAnalyticsConfig+def _deterministic_job_uuid_factory():+ """Monotonic 00000000-0000-0000-0000-0000000000XX so snapshots are stable."""+ counter = itertools.count(1)++ def _next() -> uuid.UUID:+ return uuid.UUID(f"00000000-0000-0000-0000-{next(counter):012d}")++ return _next+++_JOB_UUID_RE = re.compile(r"'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'")+++def _normalize_job_uuids(hogql: str) -> str:+ """Rewrite each distinct job UUID to 001, 002, ... in order of appearance.++ Job ids are generated per run (UUIDv7, time-based), so we normalise any UUID+ to a clean 001/002/... view that's stable across runs, without losing the+ distinction when multiple jobs appear.+ """+ seen: dict[str, int] = {}++ def _repl(match: re.Match) -> str:+ raw = match.group(0)+ if raw not in seen:+ seen[raw] = len(seen) + 1+ return f"'00000000-0000-0000-0000-{seen[raw]:012d}'"++ return _JOB_UUID_RE.sub(_repl, hogql)++class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):def setUp(self):super().setUp()+ sync_execute(TRUNCATE_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL())+ PreaggregationJob.objects.all().delete()+ # Force deterministic job_ids so the precompute snapshots are stable in CI.+ self._job_uuid_patcher = patch.object(+ PreaggregationJob._meta.get_field("id"),+ "default",+ _deterministic_job_uuid_factory(),+ )+ self._job_uuid_patcher.start()self.config = MarketingAnalyticsConfig.from_team(self.team)+ self.config.conversion_goal_precomputation_enabled = Trueself.date_range = QueryDateRange(date_range=DateRange(date_from="2023-01-01", date_to="2023-01-31"),team=self.team,@@ -36,6 +85,10 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):now=datetime(2023, 1, 31, 23, 59, 59),)+ def tearDown(self):+ self._job_uuid_patcher.stop()+ super().tearDown()+def _create_test_conversion_goal(self,goal_id: str,@@ -45,7 +98,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):math_property: str | None = None,) -> ConversionGoalFilter1:return ConversionGoalFilter1(- kind=NodeKind.EVENTS_NODE,+ kind="EventsNode",event=event_name or goal_name.lower().replace(" ", "_"),conversion_goal_id=goal_id,conversion_goal_name=goal_name,@@ -56,8 +109,8 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):def _create_test_action_goal(self, action: Action, goal_id: str, goal_name: str) -> ConversionGoalFilter2:return ConversionGoalFilter2(- kind=NodeKind.ACTIONS_NODE,- id=str(action.id),+ kind="ActionsNode",+ id=action.pk,conversion_goal_id=goal_id,conversion_goal_name=goal_name,math=BaseMathType.TOTAL,@@ -182,7 +235,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):cte = aggregator.generate_unified_cte(self.date_range, additional_conditions_getter)response = execute_hogql_query(query=cte.expr, team=self.team)- assert pretty_print_in_tests(response.hogql, self.team.pk) == self.snapshot+ assert _normalize_job_uuids(pretty_print_in_tests(response.hogql, self.team.pk)) == self.snapshotdef test_unified_cte_ast_structure(self):goal1 = self._create_test_conversion_goal("ast_goal1", "AST Goal 1", "sign_up")@@ -361,7 +414,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):cte = aggregator.generate_unified_cte(self.date_range, additional_conditions_getter)response = execute_hogql_query(query=cte.expr, team=self.team)- assert pretty_print_in_tests(response.hogql, self.team.pk) == self.snapshot+ assert _normalize_job_uuids(pretty_print_in_tests(response.hogql, self.team.pk)) == self.snapshotdef test_aggregation_ast_validation(self):events_goal1 = self._create_test_conversion_goal("simple_events1", "Simple Events 1", "purchase")@@ -393,7 +446,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):def test_empty_goal_name(self):goal = ConversionGoalFilter1(- kind=NodeKind.EVENTS_NODE,+ kind="EventsNode",event="test_event",conversion_goal_id="empty_name_test",conversion_goal_name="",@@ -498,7 +551,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):# Execute to get the SQL stringresponse = execute_hogql_query(query=cte.expr, team=self.team)- assert pretty_print_in_tests(response.hogql, self.team.pk) == self.snapshot+ assert _normalize_job_uuids(pretty_print_in_tests(response.hogql, self.team.pk)) == self.snapshot@pytest.mark.usefixtures("unittest_snapshot")def test_campaign_name_mapping_single_source_sql(self):@@ -519,7 +572,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):response = execute_hogql_query(query=cte.expr, team=self.team)- assert pretty_print_in_tests(response.hogql, self.team.pk) == self.snapshot+ assert _normalize_job_uuids(pretty_print_in_tests(response.hogql, self.team.pk)) == self.snapshot@pytest.mark.usefixtures("unittest_snapshot")def test_campaign_name_mapping_no_mappings(self):@@ -536,7 +589,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):response = execute_hogql_query(query=cte.expr, team=self.team)- assert pretty_print_in_tests(response.hogql, self.team.pk) == self.snapshot+ assert _normalize_job_uuids(pretty_print_in_tests(response.hogql, self.team.pk)) == self.snapshot@pytest.mark.usefixtures("unittest_snapshot")def test_campaign_name_mapping_integration_with_events(self):@@ -562,7 +615,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):response = execute_hogql_query(query=cte.expr, team=self.team)# Verify the SQL contains campaign name mapping logic- assert pretty_print_in_tests(response.hogql, self.team.pk) == self.snapshot+ assert _normalize_job_uuids(pretty_print_in_tests(response.hogql, self.team.pk)) == self.snapshot# Verify that the SQL contains the expected campaign name mapping logicsql_string = pretty_print_in_tests(response.hogql, self.team.pk)diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_config.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_config.pyindex 70178bf704b4..450b63fec22a 100644--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_config.py+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_config.py@@ -10,8 +10,16 @@ from products.marketing_analytics.backend.hogql_queries.marketing_analytics_confMarketingAnalyticsConfig,)+_MULTI_TOUCH_FLAG = "marketing-analytics-multi-touch-attribution"+class TestMarketingAnalyticsConfig(BaseTest):+ @staticmethod+ def _multi_touch_flag_calls(mock_ff) -> list:+ # from_team also checks the precomputation flag unconditionally, so assert on the+ # multi-touch flag specifically rather than the total feature_enabled call count.+ return [call for call in mock_ff.call_args_list if call.args and call.args[0] == _MULTI_TOUCH_FLAG]+def _set_attribution_mode(self, mode: AttributionMode) -> None:# Access the cached_property to ensure the config exists, then update itma_config = self.team.marketing_analytics_config@@ -39,7 +47,7 @@ class TestMarketingAnalyticsConfig(BaseTest):assert config.attribution_mode == AttributionMode.LINEARassert config.is_multi_touch- mock_ff.assert_called_once()+ assert len(self._multi_touch_flag_calls(mock_ff)) == 1@patch("products.marketing_analytics.backend.hogql_queries.marketing_analytics_config.posthoganalytics.feature_enabled",@@ -74,7 +82,7 @@ class TestMarketingAnalyticsConfig(BaseTest):config = MarketingAnalyticsConfig.from_team(self.team)assert config.attribution_mode == AttributionMode.FIRST_TOUCH- mock_ff.assert_not_called()+ assert self._multi_touch_flag_calls(mock_ff) == []def test_is_multi_touch_property(self):config = MarketingAnalyticsConfig()diff --git a/tach.toml b/tach.tomlindex 015ad476e9b3..900252171e20 100644--- a/tach.toml+++ b/tach.toml@@ -337,7 +337,9 @@ layer = "modules"path = "products.marketing_analytics"depends_on = ["posthog",+ "products.access_control","products.actions",+ "products.analytics_platform","products.data_warehouse", "products.warehouse_sources",]layer = "modules"