:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(funnels): remove unused legacy clickhouse funnel correlation and experiment queries (#61218)
Sandy Spicera587861014c7
diff --git a/ee/benchmarks/benchmarks.py b/ee/benchmarks/benchmarks.pyindex da72eb1b028e..b26eff95e0c3 100644--- a/ee/benchmarks/benchmarks.py+++ b/ee/benchmarks/benchmarks.py@@ -7,7 +7,6 @@ from ee.clickhouse.materialized_columns.analyze import (materialize,)from ee.clickhouse.materialized_columns.columns import MaterializedColumn-from ee.clickhouse.queries.funnels.funnel_correlation import FunnelCorrelationfrom posthog.queries.funnels import ClickhouseFunnelfrom posthog.queries.property_values import (get_property_values_for_key,@@ -23,7 +22,6 @@ from products.actions.backend.models.action import Actionfrom posthog.models.filters.session_recordings_filter import SessionRecordingsFilterfrom posthog.models.filters.filter import Filterfrom posthog.models.property import PropertyName, TableWithProperties-from posthog.constants import FunnelCorrelationTypeMATERIALIZED_PROPERTIES: dict[TableWithProperties, list[PropertyName]] = {"events": [@@ -362,72 +360,6 @@ class QuerySuite:)ClickhouseFunnel(filter, self.team).run()- @benchmark_clickhouse- def track_correlations_by_events(self):- filter = Filter(- data={- "events": [{"id": "user signed up"}, {"id": "insight analyzed"}],- **SHORT_DATE_RANGE,- },- team=self.team,- )-- FunnelCorrelation(filter, self.team).run()-- @benchmark_clickhouse- def track_correlations_by_properties_materialized(self):- filter = Filter(- data={- "events": [{"id": "user signed up"}, {"id": "insight analyzed"}],- **SHORT_DATE_RANGE,- "funnel_correlation_type": FunnelCorrelationType.PROPERTIES,- "funnel_correlation_names": ["$browser"],- },- team=self.team,- )- FunnelCorrelation(filter, self.team).run()-- @benchmark_clickhouse- def track_correlations_by_properties(self):- filter = Filter(- data={- "events": [{"id": "user signed up"}, {"id": "insight analyzed"}],- **SHORT_DATE_RANGE,- "funnel_correlation_type": FunnelCorrelationType.PROPERTIES,- "funnel_correlation_names": ["$browser"],- },- team=self.team,- )- with no_materialized_columns():- FunnelCorrelation(filter, self.team).run()-- @benchmark_clickhouse- def track_correlations_by_event_properties(self):- filter = Filter(- data={- "events": [{"id": "user signed up"}, {"id": "insight analyzed"}],- **SHORT_DATE_RANGE,- "funnel_correlation_type": FunnelCorrelationType.EVENT_WITH_PROPERTIES,- "funnel_correlation_event_names": ["$autocapture"],- },- team=self.team,- )- with no_materialized_columns():- FunnelCorrelation(filter, self.team).run()-- @benchmark_clickhouse- def track_correlations_by_event_properties_materialized(self):- filter = Filter(- data={- "events": [{"id": "user signed up"}, {"id": "insight analyzed"}],- **SHORT_DATE_RANGE,- "funnel_correlation_type": FunnelCorrelationType.EVENT_WITH_PROPERTIES,- "funnel_correlation_event_names": ["$autocapture"],- },- team=self.team,- )- FunnelCorrelation(filter, self.team).run()-@benchmark_clickhousedef track_session_recordings_list(self):filter = SessionRecordingsFilter(data=SESSIONS_DATE_RANGE, team=self.team)diff --git a/ee/clickhouse/queries/experiments/secondary_experiment_result.py b/ee/clickhouse/queries/experiments/secondary_experiment_result.pydeleted file mode 100644index 083584962de1..000000000000--- a/ee/clickhouse/queries/experiments/secondary_experiment_result.py+++ /dev/null@@ -1,86 +0,0 @@-from datetime import datetime-from typing import Optional--from rest_framework.exceptions import ValidationError--from posthog.constants import INSIGHT_FUNNELS, INSIGHT_TRENDS-from posthog.models.filters.filter import Filter-from posthog.models.team import Team--from products.feature_flags.backend.models.feature_flag import FeatureFlag--from ee.clickhouse.queries.experiments.funnel_experiment_result import ClickhouseFunnelExperimentResult-from ee.clickhouse.queries.experiments.trend_experiment_result import (- ClickhouseTrendExperimentResult,- uses_math_aggregation_by_user_or_property_value,-)---class ClickhouseSecondaryExperimentResult:- """- This class calculates secondary metric values for Experiments.- It returns value of metric for each variant.-- We adjust the metric filter based on Experiment parameters.- """-- def __init__(- self,- filter: Filter,- team: Team,- feature_flag: FeatureFlag,- experiment_start_date: datetime,- experiment_end_date: Optional[datetime] = None,- ):- self.variants = [variant["key"] for variant in feature_flag.variants]- self.team = team- self.feature_flag = feature_flag- self.filter = filter- self.experiment_start_date = experiment_start_date- self.experiment_end_date = experiment_end_date-- def get_results(self):- if self.filter.insight == INSIGHT_TRENDS:- significance_results = ClickhouseTrendExperimentResult(- self.filter, self.team, self.feature_flag, self.experiment_start_date, self.experiment_end_date- ).get_results(validate=False)- variants = self.get_trend_count_data_for_variants(significance_results["insight"])-- elif self.filter.insight == INSIGHT_FUNNELS:- significance_results = ClickhouseFunnelExperimentResult(- self.filter, self.team, self.feature_flag, self.experiment_start_date, self.experiment_end_date- ).get_results(validate=False)- variants = self.get_funnel_conversion_rate_for_variants(significance_results["insight"])-- else:- raise ValidationError("Secondary metrics need to be funnel or trend insights")-- return {"result": variants, **significance_results}-- def get_funnel_conversion_rate_for_variants(self, insight_results) -> dict[str, float]:- variants = {}- for result in insight_results:- total = result[0]["count"]- success = result[-1]["count"]- breakdown_value = result[0]["breakdown_value"][0]-- if breakdown_value in self.variants:- variants[breakdown_value] = round(int(success) / int(total), 3)-- return variants-- def get_trend_count_data_for_variants(self, insight_results) -> dict[str, float]:- # this assumes the Trend insight is Cumulative, unless using count per user- variants = {}-- for result in insight_results:- count = result["count"]- breakdown_value = result["breakdown_value"]-- if uses_math_aggregation_by_user_or_property_value(self.filter):- count = result["count"] / len(result.get("data", [0]))-- if breakdown_value in self.variants:- variants[breakdown_value] = count-- return variantsdiff --git a/ee/clickhouse/queries/experiments/trend_experiment_result.py b/ee/clickhouse/queries/experiments/trend_experiment_result.pydeleted file mode 100644index 7774c9583737..000000000000--- a/ee/clickhouse/queries/experiments/trend_experiment_result.py+++ /dev/null@@ -1,363 +0,0 @@-import json-from dataclasses import asdict, dataclass-from datetime import datetime-from typing import Optional-from zoneinfo import ZoneInfo--from rest_framework.exceptions import ValidationError--from posthog.schema import ExperimentSignificanceCode--from posthog.constants import (- ACTIONS,- EVENTS,- TRENDS_CUMULATIVE,- TRENDS_LINEAR,- UNIQUE_USERS,- ExperimentNoResultsErrorKeys,-)-from posthog.hogql_queries.experiments.trends_statistics import (- are_results_significant,- calculate_credible_intervals,- calculate_probabilities,-)-from posthog.models.filters.filter import Filter-from posthog.models.team import Team-from posthog.queries.trends.trends import Trends-from posthog.queries.trends.util import ALL_SUPPORTED_MATH_FUNCTIONS--from products.experiments.backend.models.experiment import ExperimentHoldout-from products.feature_flags.backend.models.feature_flag import FeatureFlag--from ee.clickhouse.queries.experiments import CONTROL_VARIANT_KEY--Probability = float---@dataclass(frozen=True)-class Variant:- key: str- count: int- # a fractional value, representing the proportion of the variant's exposure events relative to *control* exposure events- # default: the proportion of unique users relative to the *control* unique users- exposure: float- # count of total exposure events exposed for a variant- # default: total number of unique users exposed to the variant (via "Feature flag called" event)- absolute_exposure: int---def uses_math_aggregation_by_user_or_property_value(filter: Filter):- # sync with frontend: https://github.com/PostHog/posthog/blob/master/frontend/src/scenes/experiments/experimentLogic.tsx#L662- # the selector experimentCountPerUserMath-- entities = filter.entities- math_keys = ALL_SUPPORTED_MATH_FUNCTIONS-- # 'sum' doesn't need special handling, we can have custom exposure for sum filters- if "sum" in math_keys:- math_keys.remove("sum")-- return any(entity.math in math_keys for entity in entities)---class ClickhouseTrendExperimentResult:- """- This class calculates Experiment Results.- It returns two things:- 1. A trend Breakdown based on Feature Flag values- 2. Probability that Feature Flag value 1 has better conversion rate then FeatureFlag value 2-- Currently, it only supports two feature flag values: control and test-- The passed in Filter determines which trend to create, along with the experiment start & end date values-- Calculating (2) uses the formula here: https://www.evanmiller.org/bayesian-ab-testing.html#count_ab- """-- def __init__(- self,- filter: Filter,- team: Team,- feature_flag: FeatureFlag,- experiment_start_date: datetime,- experiment_end_date: Optional[datetime] = None,- trend_class: type[Trends] = Trends,- custom_exposure_filter: Optional[Filter] = None,- holdout: Optional[ExperimentHoldout] = None,- ):- breakdown_key = f"$feature/{feature_flag.key}"- self.variants = [variant["key"] for variant in feature_flag.variants]- if holdout:- self.variants.append(f"holdout-{holdout.id}")-- # our filters assume that the given time ranges are in the project timezone.- # while start and end date are in UTC.- # so we need to convert them to the project timezone- if team.timezone:- start_date_in_project_timezone = experiment_start_date.astimezone(ZoneInfo(team.timezone))- end_date_in_project_timezone = (- experiment_end_date.astimezone(ZoneInfo(team.timezone)) if experiment_end_date else None- )-- uses_math_aggregation = uses_math_aggregation_by_user_or_property_value(filter)-- # Keep in sync with https://github.com/PostHog/posthog/blob/master/frontend/src/scenes/experiments/ExperimentView/components.tsx#L91- query_filter = filter.shallow_clone(- {- "display": TRENDS_CUMULATIVE if not uses_math_aggregation else TRENDS_LINEAR,- "date_from": start_date_in_project_timezone,- "date_to": end_date_in_project_timezone,- "explicit_date": True,- "breakdown": breakdown_key,- "breakdown_type": "event",- "properties": [- {- "key": breakdown_key,- "value": self.variants,- "operator": "exact",- "type": "event",- }- ],- # :TRICKY: We don't use properties set on filters, instead using experiment variant options- # :TRICKY: We don't use properties set on filters, as these- # correspond to feature flag properties, not the trend properties.- # This is also why we simplify only right now so new properties (from test account filters)- # are added appropriately.- "is_simplified": False,- }- )-- if uses_math_aggregation:- # A trend experiment can have only one metric, so take the first one to calculate exposure- # We copy the entity to avoid mutating the original filter- entity = query_filter.shallow_clone({}).entities[0]- # :TRICKY: With count per user aggregation, our exposure filter is implicit:- # (1) We calculate the unique users for this event -> this is the exposure- # (2) We calculate the total count of this event -> this is the trend goal metric / arrival rate for probability calculation- # TODO: When we support group aggregation per user, change this.- entity.math = None- exposure_entity = entity.to_dict()- entity.math = UNIQUE_USERS- count_entity = entity.to_dict()-- target_entities = [exposure_entity, count_entity]- query_filter_actions = []- query_filter_events = []- if entity.type == ACTIONS:- query_filter_actions = target_entities- else:- query_filter_events = target_entities-- # two entities in exposure, one for count, the other for result- exposure_filter = query_filter.shallow_clone(- {- "display": TRENDS_CUMULATIVE,- ACTIONS: query_filter_actions,- EVENTS: query_filter_events,- }- )-- else:- # TODO: Exposure doesn't need to compute daily values, so instead of- # using TRENDS_CUMULATIVE, we can use TRENDS_TABLE to just get the total.- if custom_exposure_filter:- exposure_filter = custom_exposure_filter.shallow_clone(- {- "display": TRENDS_CUMULATIVE,- "date_from": experiment_start_date,- "date_to": experiment_end_date,- "explicit_date": True,- "breakdown": breakdown_key,- "breakdown_type": "event",- "properties": [- {- "key": breakdown_key,- "value": self.variants,- "operator": "exact",- "type": "event",- }- ],- # :TRICKY: We don't use properties set on filters, as these- # correspond to feature flag properties, not the trend-exposure properties.- # This is also why we simplify only right now so new properties (from test account filters)- # are added appropriately.- "is_simplified": False,- }- )- else:- exposure_filter = filter.shallow_clone(- {- "display": TRENDS_CUMULATIVE,- "date_from": experiment_start_date,- "date_to": experiment_end_date,- "explicit_date": True,- ACTIONS: [],- EVENTS: [- {- "id": "$feature_flag_called",- "name": "$feature_flag_called",- "order": 0,- "type": "events",- "math": "dau",- }- ],- "breakdown_type": "event",- "breakdown": "$feature_flag_response",- "properties": [- {- "key": "$feature_flag_response",- "value": self.variants,- "operator": "exact",- "type": "event",- },- {- "key": "$feature_flag",- "value": [feature_flag.key],- "operator": "exact",- "type": "event",- },- ],- # :TRICKY: We don't use properties set on filters, as these- # correspond to feature flag properties, not the trend-exposure properties.- # This is also why we simplify only right now so new properties (from test account filters)- # are added appropriately.- "is_simplified": False,- }- )-- self.query_filter = query_filter- self.exposure_filter = exposure_filter- self.team = team- self.insight = trend_class()-- def get_results(self, validate: bool = True):- insight_results = self.insight.run(self.query_filter, self.team)- exposure_results = self.insight.run(self.exposure_filter, self.team)-- basic_result_props = {- "insight": insight_results,- "filters": self.query_filter.to_dict(),- "exposure_filters": self.exposure_filter.to_dict(),- }-- try:- validate_event_variants(insight_results, self.variants)-- control_variant, test_variants = self.get_variants(insight_results, exposure_results)-- probabilities = calculate_probabilities(control_variant, test_variants)-- mapping = {- variant.key: probability- for variant, probability in zip([control_variant, *test_variants], probabilities)- }-- significance_code, p_value = are_results_significant(control_variant, test_variants, probabilities)-- credible_intervals = calculate_credible_intervals([control_variant, *test_variants])- except ValidationError:- if validate:- raise- else:- return basic_result_props-- return {- **basic_result_props,- "probability": mapping,- "significant": significance_code == ExperimentSignificanceCode.SIGNIFICANT,- "significance_code": significance_code,- "p_value": p_value,- "variants": [asdict(variant) for variant in [control_variant, *test_variants]],- "credible_intervals": credible_intervals,- }-- def get_variants(self, insight_results, exposure_results):- # this assumes the Trend insight is Cumulative- control_variant = None- test_variants = []- exposure_counts = {}- exposure_ratios = {}-- # :TRICKY: With count per user aggregation, our exposure filter is implicit:- # (1) We calculate the unique users for this event -> this is the exposure- # (2) We calculate the total count of this event -> this is the trend goal metric / arrival rate for probability calculation- # TODO: When we support group aggregation per user, change this.- if uses_math_aggregation_by_user_or_property_value(self.query_filter):- filtered_exposure_results = [- result for result in exposure_results if result["action"]["math"] == UNIQUE_USERS- ]- filtered_insight_results = [- result for result in exposure_results if result["action"]["math"] != UNIQUE_USERS- ]- else:- filtered_exposure_results = exposure_results- filtered_insight_results = insight_results-- for result in filtered_exposure_results:- count = result["count"]- breakdown_value = result["breakdown_value"]- exposure_counts[breakdown_value] = count-- control_exposure = exposure_counts.get(CONTROL_VARIANT_KEY, 0)-- if control_exposure != 0:- for key, count in exposure_counts.items():- exposure_ratios[key] = count / control_exposure-- for result in filtered_insight_results:- count = result["count"]- breakdown_value = result["breakdown_value"]- if breakdown_value == CONTROL_VARIANT_KEY:- # count exposure value is always 1, the baseline- control_variant = Variant(- key=breakdown_value,- count=int(count),- exposure=1,- absolute_exposure=exposure_counts.get(breakdown_value, 1),- )- else:- test_variants.append(- Variant(- breakdown_value,- int(count),- exposure_ratios.get(breakdown_value, 1),- exposure_counts.get(breakdown_value, 1),- )- )-- return control_variant, test_variants---def validate_event_variants(trend_results, variants):- errors = {- ExperimentNoResultsErrorKeys.NO_EVENTS: True,- ExperimentNoResultsErrorKeys.NO_FLAG_INFO: True,- ExperimentNoResultsErrorKeys.NO_CONTROL_VARIANT: True,- ExperimentNoResultsErrorKeys.NO_TEST_VARIANT: True,- }-- if not trend_results or not trend_results[0]:- raise ValidationError(code="no-results", detail=json.dumps(errors))-- errors[ExperimentNoResultsErrorKeys.NO_EVENTS] = False-- # Check if "control" is present- for event in trend_results:- event_variant = event.get("breakdown_value")- if event_variant == "control":- errors[ExperimentNoResultsErrorKeys.NO_CONTROL_VARIANT] = False- errors[ExperimentNoResultsErrorKeys.NO_FLAG_INFO] = False- break-- # Check if at least one of the test variants is present- test_variants = [variant for variant in variants if variant != "control"]- for event in trend_results:- event_variant = event.get("breakdown_value")- if event_variant in test_variants:- errors[ExperimentNoResultsErrorKeys.NO_TEST_VARIANT] = False- errors[ExperimentNoResultsErrorKeys.NO_FLAG_INFO] = False- break-- has_errors = any(errors.values())- if has_errors:- raise ValidationError(detail=json.dumps(errors))diff --git a/ee/clickhouse/queries/funnels/funnel_correlation.py b/ee/clickhouse/queries/funnels/funnel_correlation.pydeleted file mode 100644index 27b51280c929..000000000000--- a/ee/clickhouse/queries/funnels/funnel_correlation.py+++ /dev/null@@ -1,962 +0,0 @@-import dataclasses-import urllib.parse-from typing import Any, Literal, Optional, TypedDict, Union, cast--from rest_framework.exceptions import ValidationError--from posthog.schema import PersonsOnEventsMode--from posthog.clickhouse.materialized_columns import get_materialized_column_for_property-from posthog.constants import AUTOCAPTURE_EVENT, TREND_FILTER_TYPE_ACTIONS, FunnelCorrelationType-from posthog.models.element.element import chain_to_elements-from posthog.models.event.util import ElementSerializer-from posthog.models.filters import Filter-from posthog.models.property.util import get_property_string_expr-from posthog.models.team import Team-from posthog.queries.funnels.utils import get_funnel_order_actor_class-from posthog.queries.insight import insight_sync_execute-from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query-from posthog.queries.person_query import PersonQuery-from posthog.queries.util import alias_poe_mode_for_legacy, correct_result_for_sampling-from posthog.utils import generate_short_id--from ee.clickhouse.queries.column_optimizer import EnterpriseColumnOptimizer-from ee.clickhouse.queries.groups_join_query import GroupsJoinQuery---class EventDefinition(TypedDict):- event: str- properties: dict[str, Any]- elements: list---class EventOddsRatio(TypedDict):- event: str-- success_count: int- failure_count: int-- odds_ratio: float- correlation_type: Literal["success", "failure"]---class EventOddsRatioSerialized(TypedDict):- event: EventDefinition-- success_count: int- success_people_url: Optional[str]-- failure_count: int- failure_people_url: Optional[str]-- odds_ratio: float- correlation_type: Literal["success", "failure"]---class FunnelCorrelationResponse(TypedDict):- """- The structure that the diagnose response will be returned in.- NOTE: TypedDict is used here to comply with existing formats from other- queries, but we could use, for example, a dataclass- """-- events: list[EventOddsRatioSerialized]- skewed: bool---class EventStats:- success_count: int- failure_count: int---class EventContingencyTable:- """- Represents a contingency table for a single event. Note that this isn't a- complete contingency table, but rather only includes totals for- failure/success as opposed to including the number of successes for cases- that a persons _doesn't_ visit an event.- """-- event: str- visited: EventStats-- success_total: int- failure_total: int---class FunnelCorrelation:- TOTAL_IDENTIFIER = "Total_Values_In_Query"- ELEMENTS_DIVIDER = "__~~__"- AUTOCAPTURE_EVENT_TYPE = "$event_type"- MIN_PERSON_COUNT = 25- MIN_PERSON_PERCENTAGE = 0.02- PRIOR_COUNT = 1-- def __init__(- self,- filter: Filter, # Used to filter people- team: Team, # Used to partition by team- base_uri: str = "/", # Used to generate absolute urls- ) -> None:- self._filter = filter- self._team = team- self._base_uri = base_uri-- if self._filter.funnel_step is None:- self._filter = self._filter.shallow_clone({"funnel_step": 1})- # Funnel Step by default set to 1, to give us all people who entered the funnel-- # Used for generating the funnel persons cte-- filter_data = {- key: value- for key, value in self._filter.to_dict().items()- # NOTE: we want to filter anything about correlation, as the- # funnel persons endpoint does not understand or need these- # params.- if not key.startswith("funnel_correlation_")- }- # NOTE: we always use the final matching event for the recording because this- # is the the right event for both drop off and successful funnels- filter_data.update({"include_final_matching_events": self._filter.include_recordings})- filter = Filter(data=filter_data, hogql_context=self._filter.hogql_context)-- funnel_order_actor_class = get_funnel_order_actor_class(filter)-- self._funnel_actors_generator = funnel_order_actor_class(- filter,- self._team,- # NOTE: we want to include the latest timestamp of the `target_step`,- # from this we can deduce if the person reached the end of the funnel,- # i.e. successful- include_timestamp=True,- # NOTE: we don't need these as we have all the information we need to- # deduce if the person was successful or not- include_preceding_timestamp=False,- include_properties=self.properties_to_include,- )-- @property- def properties_to_include(self) -> list[str]:- props_to_include = []- if (- alias_poe_mode_for_legacy(self._team.person_on_events_mode) != PersonsOnEventsMode.DISABLED- and self._filter.correlation_type == FunnelCorrelationType.PROPERTIES- ):- # When dealing with properties, make sure funnel response comes with properties- # so we don't have to join on persons/groups to get these properties again- for property_name in cast(list, self._filter.correlation_property_names):- if self._filter.aggregation_group_type_index is not None:- continue # We don't support group properties on events at this time- else:- if "$all" == property_name:- return [f"person_properties"]-- possible_mat_col = get_materialized_column_for_property(- "events", "person_properties", property_name- )- if possible_mat_col is not None and not possible_mat_col.is_nullable:- props_to_include.append(possible_mat_col.name)- else:- props_to_include.append(f"person_properties")-- return props_to_include-- def support_autocapture_elements(self) -> bool:- if (- self._filter.correlation_type == FunnelCorrelationType.EVENT_WITH_PROPERTIES- and AUTOCAPTURE_EVENT in self._filter.correlation_event_names- ):- return True- return False-- def get_contingency_table_query(self) -> tuple[str, dict[str, Any]]:- """- Returns a query string and params, which are used to generate the contingency table.- The query returns success and failure count for event / property values, along with total success and failure counts.- """- if self._filter.correlation_type == FunnelCorrelationType.PROPERTIES:- return self.get_properties_query()-- if self._filter.correlation_type == FunnelCorrelationType.EVENT_WITH_PROPERTIES:- return self.get_event_property_query()-- return self.get_event_query()-- def get_event_query(self) -> tuple[str, dict[str, Any]]:- funnel_persons_query, funnel_persons_params = self.get_funnel_actors_cte()-- event_join_query = self._get_events_join_query()-- query = f"""- WITH- funnel_actors as ({funnel_persons_query}),- toDateTime(%(date_to)s, %(timezone)s) AS date_to,- toDateTime(%(date_from)s, %(timezone)s) AS date_from,- %(target_step)s AS target_step,- %(funnel_step_names)s as funnel_step_names-- SELECT- event.event AS name,-- -- If we have a `person.steps = target_step`, we know the person- -- reached the end of the funnel- countDistinctIf(- actors.actor_id,- actors.steps = target_step- ) AS success_count,-- -- And the converse being for failures- countDistinctIf(- actors.actor_id,- actors.steps <> target_step- ) AS failure_count-- FROM events AS event- {event_join_query}- AND event.event NOT IN %(exclude_event_names)s- GROUP BY name-- -- To get the total success/failure numbers, we do an aggregation on- -- the funnel people CTE and count distinct actor_ids- UNION ALL-- SELECT- -- We're not using WITH TOTALS because the resulting queries are- -- not runnable in Metabase- '{self.TOTAL_IDENTIFIER}' as name,-- countDistinctIf(- actors.actor_id,- actors.steps = target_step- ) AS success_count,-- countDistinctIf(- actors.actor_id,- actors.steps <> target_step- ) AS failure_count- FROM funnel_actors AS actors- """- params = {- **funnel_persons_params,- "funnel_step_names": self._get_funnel_step_names(),- "target_step": len(self._filter.entities),- "exclude_event_names": self._filter.correlation_event_exclude_names,- }-- return query, params-- def get_event_property_query(self) -> tuple[str, dict[str, Any]]:- if not self._filter.correlation_event_names:- raise ValidationError("Event Property Correlation expects atleast one event name to run correlation on")-- funnel_persons_query, funnel_persons_params = self.get_funnel_actors_cte()-- event_join_query = self._get_events_join_query()-- if self.support_autocapture_elements():- event_type_expression, _ = get_property_string_expr(- "events",- self.AUTOCAPTURE_EVENT_TYPE,- f"'{self.AUTOCAPTURE_EVENT_TYPE}'",- "properties",- )- array_join_query = f"""- 'elements_chain' as prop_key,- concat({event_type_expression}, '{self.ELEMENTS_DIVIDER}', elements_chain) as prop_value,- tuple(prop_key, prop_value) as prop- """- else:- array_join_query = f"""- arrayJoin(JSONExtractKeysAndValues(properties, 'String')) as prop- """-- query = f"""- WITH- funnel_actors as ({funnel_persons_query}),- toDateTime(%(date_to)s, %(timezone)s) AS date_to,- toDateTime(%(date_from)s, %(timezone)s) AS date_from,- %(target_step)s AS target_step,- %(funnel_step_names)s as funnel_step_names-- SELECT concat(event_name, '::', prop.1, '::', prop.2) as name,- countDistinctIf(actor_id, steps = target_step) as success_count,- countDistinctIf(actor_id, steps <> target_step) as failure_count- FROM (- SELECT- actors.actor_id as actor_id,- actors.steps as steps,- events.event as event_name,- -- Same as what we do in $all property queries- {array_join_query}- FROM events AS event- {event_join_query}- AND event.event IN %(event_names)s- )- GROUP BY name, prop- -- Discard high cardinality / low hits properties- -- This removes the long tail of random properties with empty, null, or very small values- HAVING (success_count + failure_count) > 2- AND prop.1 NOT IN %(exclude_property_names)s-- UNION ALL- -- To get the total success/failure numbers, we do an aggregation on- -- the funnel people CTE and count distinct actor_ids- SELECT- '{self.TOTAL_IDENTIFIER}' as name,-- countDistinctIf(- actors.actor_id,- actors.steps = target_step- ) AS success_count,-- countDistinctIf(- actors.actor_id,- actors.steps <> target_step- ) AS failure_count- FROM funnel_actors AS actors- """- params = {- **funnel_persons_params,- "funnel_step_names": self._get_funnel_step_names(),- "target_step": len(self._filter.entities),- "event_names": self._filter.correlation_event_names,- "exclude_property_names": self._filter.correlation_event_exclude_property_names,- }-- return query, params-- def get_properties_query(self) -> tuple[str, dict[str, Any]]:- if not self._filter.correlation_property_names:- raise ValidationError("Property Correlation expects atleast one Property to run correlation on")-- funnel_actors_query, funnel_actors_params = self.get_funnel_actors_cte()-- person_prop_query, person_prop_params = self._get_properties_prop_clause()-- (- aggregation_join_query,- aggregation_join_params,- ) = self._get_aggregation_join_query()-- query = f"""- WITH- funnel_actors as ({funnel_actors_query}),- %(target_step)s AS target_step- SELECT- concat(prop.1, '::', prop.2) as name,- -- We generate a unique identifier for each property value as: PropertyName::Value- countDistinctIf(actor_id, steps = target_step) AS success_count,- countDistinctIf(actor_id, steps <> target_step) AS failure_count- FROM (- SELECT- actor_id,- funnel_actors.steps as steps,- /*- We can extract multiple property values at the same time, since we're- already querying the person table.- This gives us something like:- --------------------- person1, steps, [property_value_0, property_value_1, property_value_2]- person2, steps, [property_value_0, property_value_1, property_value_2]-- To group by property name, we need to extract the property from the array. ArrayJoin helps us do that.- It transforms the above into:-- ---------------------- person1, steps, property_value_0- person1, steps, property_value_1- person1, steps, property_value_2-- person2, steps, property_value_0- person2, steps, property_value_1- person2, steps, property_value_2-- To avoid clashes and clarify the values, we also zip with the property name, to generate- tuples like: (property_name, property_value), which we then group by- */- {person_prop_query}- FROM funnel_actors- {aggregation_join_query}-- ) aggregation_target_with_props- -- Group by the tuple items: (property_name, property_value) generated by zip- GROUP BY prop.1, prop.2- HAVING prop.1 NOT IN %(exclude_property_names)s- UNION ALL- SELECT- '{self.TOTAL_IDENTIFIER}' as name,- countDistinctIf(actor_id, steps = target_step) AS success_count,- countDistinctIf(actor_id, steps <> target_step) AS failure_count- FROM funnel_actors- """- params = {- **funnel_actors_params,- **person_prop_params,- **aggregation_join_params,- "target_step": len(self._filter.entities),- "property_names": self._filter.correlation_property_names,- "exclude_property_names": self._filter.correlation_property_exclude_names,- }-- return query, params-- def _get_aggregation_target_join_query(self) -> str:- if self._team.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:- aggregation_person_join = f"""- JOIN funnel_actors as actors- ON event.person_id = actors.actor_id- """-- else:- aggregation_person_join = f"""- JOIN ({get_team_distinct_ids_query(self._team.pk)}) AS pdi- ON pdi.distinct_id = events.distinct_id-- -- NOTE: I would love to right join here, so we count get total- -- success/failure numbers in one pass, but this causes out of memory- -- error mentioning issues with right filling. I'm sure there's a way- -- to do it but lifes too short.- JOIN funnel_actors AS actors- ON pdi.person_id = actors.actor_id- """-- aggregation_group_join = f"""- JOIN funnel_actors AS actors- ON actors.actor_id = events.$group_{self._filter.aggregation_group_type_index}- """-- return (- aggregation_group_join if self._filter.aggregation_group_type_index is not None else aggregation_person_join- )-- def _get_events_join_query(self) -> str:- """- This query is used to join and filter the events table corresponding to the funnel_actors CTE.- It expects the following variables to be present in the CTE expression:- - funnel_actors- - date_to- - date_from- - funnel_step_names- """-- return f"""- {self._get_aggregation_target_join_query()}-- -- Make sure we're only looking at events before the final step, or- -- failing that, date_to- WHERE- -- add this condition in to ensure we can filter events before- -- joining funnel_actors- toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to-- AND event.team_id = {self._team.pk}-- -- Add in per actor filtering on event time range. We just want- -- to include events that happened within the bounds of the- -- actors time in the funnel.- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(- actors.final_timestamp,- actors.first_timestamp + INTERVAL {self._funnel_actors_generator._filter.funnel_window_interval} {self._funnel_actors_generator._filter.funnel_window_interval_unit_ch()},- date_to)- -- Ensure that the event is not outside the bounds of the funnel conversion window-- -- Exclude funnel steps- AND event.event NOT IN funnel_step_names- """-- def _get_aggregation_join_query(self):- if self._filter.aggregation_group_type_index is None:- person_query, person_query_params = PersonQuery(- self._filter,- self._team.pk,- EnterpriseColumnOptimizer(self._filter, self._team.pk),- ).get_query()-- return (- f"""- JOIN ({person_query}) person- ON person.id = funnel_actors.actor_id- """,- person_query_params,- )- else:- return GroupsJoinQuery(self._filter, self._team.pk, join_key="funnel_actors.actor_id").get_join_query()-- def _get_properties_prop_clause(self):- if (- alias_poe_mode_for_legacy(self._team.person_on_events_mode) != PersonsOnEventsMode.DISABLED- and self._filter.aggregation_group_type_index is None- ):- aggregation_properties_alias = "person_properties"- else:- group_properties_field = f"groups_{self._filter.aggregation_group_type_index}.group_properties_{self._filter.aggregation_group_type_index}"- aggregation_properties_alias = (- PersonQuery.PERSON_PROPERTIES_ALIAS- if self._filter.aggregation_group_type_index is None- else group_properties_field- )-- if "$all" in cast(list, self._filter.correlation_property_names):- return (- f"""- arrayJoin(JSONExtractKeysAndValues({aggregation_properties_alias}, 'String')) as prop- """,- {},- )- else:- person_property_expressions = []- person_property_params = {}- for index, property_name in enumerate(cast(list, self._filter.correlation_property_names)):- param_name = f"property_name_{index}"- if self._filter.aggregation_group_type_index is not None:- expression, _ = get_property_string_expr(- "groups"- if alias_poe_mode_for_legacy(self._team.person_on_events_mode) == PersonsOnEventsMode.DISABLED- else "events",- property_name,- f"%({param_name})s",- aggregation_properties_alias,- materialised_table_column=aggregation_properties_alias,- )- else:- expression, _ = get_property_string_expr(- "person"- if alias_poe_mode_for_legacy(self._team.person_on_events_mode) == PersonsOnEventsMode.DISABLED- else "events",- property_name,- f"%({param_name})s",- aggregation_properties_alias,- materialised_table_column=(- aggregation_properties_alias- if alias_poe_mode_for_legacy(self._team.person_on_events_mode)- != PersonsOnEventsMode.DISABLED- else "properties"- ),- )- person_property_params[param_name] = property_name- person_property_expressions.append(expression)-- return (- f"""- arrayJoin(arrayZip(- %(property_names)s,- [{",".join(person_property_expressions)}]- )) as prop- """,- person_property_params,- )-- def _get_funnel_step_names(self):- events: set[Union[int, str]] = set()- for entity in self._filter.entities:- if entity.type == TREND_FILTER_TYPE_ACTIONS:- action = entity.get_action(self._team.pk)- events.update([x for x in action.get_step_events() if x])- elif entity.id is not None:- events.add(entity.id)-- return sorted(events)-- def _run(self) -> tuple[list[EventOddsRatio], bool]:- """- Run the diagnose query.-- Funnel Correlation queries take as input the same as the funnel query,- and returns the correlation of person events with a person successfully- getting to the end of the funnel. We use Odds Ratios as the correlation- metric. See https://en.wikipedia.org/wiki/Odds_ratio for more details.-- Roughly speaking, to calculate the odds ratio, we build a contingency- table https://en.wikipedia.org/wiki/Contingency_table for each- dimension, then calculate the odds ratio for each.-- For example, take for simplicity the cohort of all people, and the- success criteria of having a "signed up" event. First we would build a- contingency table like:-- | | success | failure | total |- | -----------------: | :-----: | :-----: | :---: |- | watched video | 5 | 1 | 6 |- | didn't watch video | 2 | 10 | 12 |--- Then the odds that a person signs up given they watched the video is 5 /- 1.-- And the odds that a person signs up given they didn't watch the video is- 2 / 10.-- So we say the odds ratio is 5 / 1 over 2 / 10 = 25 . The further away the- odds ratio is from 1, the greater the correlation.-- Requirements:-- - Intitially we only need to consider the names of events that a cohort- person has emitted. So we explicitly are not interested in e.g.- correlating properties, although this will be a follow-up.-- Non-functional requirements:-- - there can be perhaps millions of people in a cohort, so we should- consider this when writing the algorithm. e.g. we should probably- avoid pulling all people into across the wire.- - there can be an order of magnitude more events than people, so we- should avoid pulling all events across the wire.- - there may be a large but not huge number of distinct events, let's say- 100 different names for events. We should avoid n+1 queries for the- event names dimension-- Contincency tables are something we can pull out of the db, so we can- have a query that:-- 1. filters people by the cohort criteria- 2. groups these people by the success criteria- 3. groups people by our criterion with which we want to test- correlation, e.g. "watched video"-- """- self._filter.team = self._team-- (- event_contingency_tables,- success_total,- failure_total,- ) = self.get_partial_event_contingency_tables()-- success_total = int(correct_result_for_sampling(success_total, self._filter.sampling_factor))- failure_total = int(correct_result_for_sampling(failure_total, self._filter.sampling_factor))-- if not success_total or not failure_total:- return [], True-- skewed_totals = False-- # If the ratio is greater than 1:10, then we have a skewed result, so we should- # warn the user.- if success_total / failure_total > 10 or failure_total / success_total > 10:- skewed_totals = True-- odds_ratios = [- get_entity_odds_ratio(event_stats, FunnelCorrelation.PRIOR_COUNT)- for event_stats in event_contingency_tables- if not FunnelCorrelation.are_results_insignificant(event_stats)- ]-- positively_correlated_events = sorted(- [odds_ratio for odds_ratio in odds_ratios if odds_ratio["correlation_type"] == "success"],- key=lambda x: x["odds_ratio"],- reverse=True,- )-- negatively_correlated_events = sorted(- [odds_ratio for odds_ratio in odds_ratios if odds_ratio["correlation_type"] == "failure"],- key=lambda x: x["odds_ratio"],- reverse=False,- )-- # Return the top ten positively correlated events, and top then negatively correlated events- events = positively_correlated_events[:10] + negatively_correlated_events[:10]- return events, skewed_totals-- def construct_people_url(- self,- success: bool,- event_definition: EventDefinition,- cache_invalidation_key: str,- ) -> Optional[str]:- """- Given an event_definition and success/failure flag, returns a url that- get be used to GET the associated people for the event/sucess pair. The- primary purpose of this is to reduce the risk of clients of the API- fetching incorrect people, given an event definition.- """- if not self._filter.correlation_type or self._filter.correlation_type == FunnelCorrelationType.EVENTS:- return self.construct_event_correlation_people_url(- success=success,- event_definition=event_definition,- cache_invalidation_key=cache_invalidation_key,- )-- elif self._filter.correlation_type == FunnelCorrelationType.EVENT_WITH_PROPERTIES:- return self.construct_event_with_properties_people_url(- success=success,- event_definition=event_definition,- cache_invalidation_key=cache_invalidation_key,- )-- elif self._filter.correlation_type == FunnelCorrelationType.PROPERTIES:- return self.construct_person_properties_people_url(- success=success,- event_definition=event_definition,- cache_invalidation_key=cache_invalidation_key,- )-- raise ValueError(f"Unsupported correlation type: {self._filter.correlation_type}")-- def construct_event_correlation_people_url(- self,- success: bool,- event_definition: EventDefinition,- cache_invalidation_key: str,- ) -> str:- # NOTE: we need to convert certain params to strings. I don't think this- # class should need to know these details, but shallow_clone is- # expecting the values as they are serialized in the url- # TODO: remove url serialization details from this class, it likely- # belongs in the application layer, or perhaps `FunnelCorrelationPeople`- params = self._filter.shallow_clone(- {- "funnel_correlation_person_converted": "true" if success else "false",- "funnel_correlation_person_entity": {- "id": event_definition["event"],- "type": "events",- },- }- ).to_params()- return f"{self._base_uri}api/person/funnel/correlation/?{urllib.parse.urlencode(params)}&cache_invalidation_key={cache_invalidation_key}"-- def construct_event_with_properties_people_url(- self,- success: bool,- event_definition: EventDefinition,- cache_invalidation_key: str,- ) -> str:- if self.support_autocapture_elements():- # If we have an $autocapture event, we need to special case the- # url by converting the `elements` chain into an `Action`- event_name, _, _ = event_definition["event"].split("::")- elements = event_definition["elements"]- first_element = elements[0]- elements_as_action = {- "tag_name": first_element["tag_name"],- "href": first_element["href"],- "text": first_element["text"],- "selector": build_selector(elements),- }- params = self._filter.shallow_clone(- {- "funnel_correlation_person_converted": "true" if success else "false",- "funnel_correlation_person_entity": {- "id": event_name,- "type": "events",- "properties": [- {- "key": property_key,- "value": [property_value],- "type": "element",- "operator": "exact",- }- for property_key, property_value in elements_as_action.items()- if property_value is not None- ],- },- }- ).to_params()- return f"{self._base_uri}api/person/funnel/correlation/?{urllib.parse.urlencode(params)}&cache_invalidation_key={cache_invalidation_key}"-- event_name, property_name, property_value = event_definition["event"].split("::")- params = self._filter.shallow_clone(- {- "funnel_correlation_person_converted": "true" if success else "false",- "funnel_correlation_person_entity": {- "id": event_name,- "type": "events",- "properties": [- {- "key": property_name,- "value": property_value,- "type": "event",- "operator": "exact",- }- ],- },- }- ).to_params()- return f"{self._base_uri}api/person/funnel/correlation/?{urllib.parse.urlencode(params)}"-- def construct_person_properties_people_url(- self,- success: bool,- event_definition: EventDefinition,- cache_invalidation_key: str,- ) -> str:- # NOTE: for property correlations, we just use the regular funnel- # persons endpoint, with the breakdown value set, and we assume that- # event.event will be of the format "{property_name}::{property_value}"- property_name, property_value = event_definition["event"].split("::")- prop_type = "group" if self._filter.aggregation_group_type_index else "person"- params = self._filter.shallow_clone(- {- "funnel_correlation_person_converted": "true" if success else "false",- "funnel_correlation_property_values": [- {- "key": property_name,- "value": property_value,- "type": prop_type,- "operator": "exact",- "group_type_index": self._filter.aggregation_group_type_index,- }- ],- }- ).to_params()- return f"{self._base_uri}api/person/funnel/correlation?{urllib.parse.urlencode(params)}&cache_invalidation_key={cache_invalidation_key}"-- def format_results(self, results: tuple[list[EventOddsRatio], bool]) -> FunnelCorrelationResponse:- odds_ratios, skewed_totals = results- return {- "events": [self.serialize_event_odds_ratio(odds_ratio=odds_ratio) for odds_ratio in odds_ratios],- "skewed": skewed_totals,- }-- def run(self) -> FunnelCorrelationResponse:- if not self._filter.entities:- return FunnelCorrelationResponse(events=[], skewed=False)-- return self.format_results(self._run())-- def get_partial_event_contingency_tables(self) -> tuple[list[EventContingencyTable], int, int]:- """- For each event a person that started going through the funnel, gets stats- for how many of these users are sucessful and how many are unsuccessful.-- It's a partial table as it doesn't include numbers of the negation of the- event, but does include the total success/failure numbers, which is enough- for us to calculate the odds ratio.- """-- query, params = self.get_contingency_table_query()- results_with_total = insight_sync_execute(- query,- {**params, **self._filter.hogql_context.values},- query_type="funnel_correlation",- filter=self._filter,- team_id=self._team.pk,- )-- # Get the total success/failure counts from the results- results = [result for result in results_with_total if result[0] != self.TOTAL_IDENTIFIER]- _, success_total, failure_total = next(- result for result in results_with_total if result[0] == self.TOTAL_IDENTIFIER- )-- # Add a little structure, and keep it close to the query definition so it's- # obvious what's going on with result indices.- return (- [- EventContingencyTable(- event=result[0],- visited=EventStats(success_count=result[1], failure_count=result[2]),- success_total=success_total,- failure_total=failure_total,- )- for result in results- ],- success_total,- failure_total,- )-- def get_funnel_actors_cte(self) -> tuple[str, dict[str, Any]]:- extra_fields = ["steps", "final_timestamp", "first_timestamp"]-- for prop in self.properties_to_include:- extra_fields.append(prop)-- return self._funnel_actors_generator.actor_query(limit_actors=False, extra_fields=extra_fields)-- @staticmethod- def are_results_insignificant(event_contingency_table: EventContingencyTable) -> bool:- """- Check if the results are insignificant, i.e. if the success/failure counts are- significantly different from the total counts- """-- total_count = event_contingency_table.success_total + event_contingency_table.failure_total-- if event_contingency_table.visited.success_count + event_contingency_table.visited.failure_count < min(- FunnelCorrelation.MIN_PERSON_COUNT,- FunnelCorrelation.MIN_PERSON_PERCENTAGE * total_count,- ):- return True-- return False-- def serialize_event_odds_ratio(self, odds_ratio: EventOddsRatio) -> EventOddsRatioSerialized:- event_definition = self.serialize_event_with_property(event=odds_ratio["event"])- cache_invalidation_key = generate_short_id()- return {- "success_count": odds_ratio["success_count"],- "success_people_url": self.construct_people_url(- success=True,- event_definition=event_definition,- cache_invalidation_key=cache_invalidation_key,- ),- "failure_count": odds_ratio["failure_count"],- "failure_people_url": self.construct_people_url(- success=False,- event_definition=event_definition,- cache_invalidation_key=cache_invalidation_key,- ),- "odds_ratio": odds_ratio["odds_ratio"],- "correlation_type": odds_ratio["correlation_type"],- "event": event_definition,- }-- def serialize_event_with_property(self, event: str) -> EventDefinition:- """- Format the event name for display.- """- if not self.support_autocapture_elements():- return EventDefinition(event=event, properties={}, elements=[])-- event_name, property_name, property_value = event.split("::")- if event_name == AUTOCAPTURE_EVENT and property_name == "elements_chain":- event_type, elements_chain = property_value.split(self.ELEMENTS_DIVIDER)- return EventDefinition(- event=event,- properties={self.AUTOCAPTURE_EVENT_TYPE: event_type},- elements=cast(- list,- ElementSerializer(chain_to_elements(elements_chain), many=True).data,- ),- )-- return EventDefinition(event=event, properties={}, elements=[])---def get_entity_odds_ratio(event_contingency_table: EventContingencyTable, prior_counts: int) -> EventOddsRatio:- # Add 1 to all values to prevent divide by zero errors, and introduce a [prior](https://en.wikipedia.org/wiki/Prior_probability)- odds_ratio = (- (event_contingency_table.visited.success_count + prior_counts)- * (event_contingency_table.failure_total - event_contingency_table.visited.failure_count + prior_counts)- ) / (- (event_contingency_table.success_total - event_contingency_table.visited.success_count + prior_counts)- * (event_contingency_table.visited.failure_count + prior_counts)- )-- return EventOddsRatio(- event=event_contingency_table.event,- success_count=event_contingency_table.visited.success_count,- failure_count=event_contingency_table.visited.failure_count,- odds_ratio=odds_ratio,- correlation_type="success" if odds_ratio > 1 else "failure",- )---def build_selector(elements: list[dict[str, Any]]) -> str:- # build a CSS select given an "elements_chain"- # NOTE: my source of what this should be doing is- # https://github.com/PostHog/posthog/blob/cc054930a47fb59940531e99a856add49a348ee5/frontend/src/scenes/events/createActionFromEvent.tsx#L36:L36- #- def element_to_selector(element: dict[str, Any]) -> str:- if attr_id := element.get("attr_id"):- return f'[id="{attr_id}"]'-- return element["tag_name"]-- return " > ".join([element_to_selector(element) for element in elements])diff --git a/ee/clickhouse/queries/funnels/funnel_correlation_persons.py b/ee/clickhouse/queries/funnels/funnel_correlation_persons.pydeleted file mode 100644index 23868ac21bdf..000000000000--- a/ee/clickhouse/queries/funnels/funnel_correlation_persons.py+++ /dev/null@@ -1,205 +0,0 @@-from typing import Optional, Union--from django.db.models.query import QuerySet--from rest_framework.exceptions import ValidationError--from posthog.constants import FUNNEL_CORRELATION_PERSON_LIMIT, FunnelCorrelationType, PropertyOperatorType-from posthog.models import Person-from posthog.models.entity import Entity-from posthog.models.filters.filter import Filter-from posthog.models.filters.mixins.utils import cached_property-from posthog.models.group import Group-from posthog.models.team import Team-from posthog.queries.actor_base_query import ActorBaseQuery, SerializedGroup, SerializedPerson-from posthog.queries.funnels.funnel_event_query import FunnelEventQuery-from posthog.queries.util import get_person_properties_mode--from ee.clickhouse.queries.funnels.funnel_correlation import FunnelCorrelation---class FunnelCorrelationActors(ActorBaseQuery):- _filter: Filter- QUERY_TYPE = "funnel_correlation_actors"-- def __init__(self, filter: Filter, team: Team, base_uri: str = "/", **kwargs) -> None:- self._base_uri = base_uri- self._filter = filter- self._team = team-- if not self._filter.correlation_person_limit:- self._filter = self._filter.shallow_clone({FUNNEL_CORRELATION_PERSON_LIMIT: 100})-- @cached_property- def aggregation_group_type_index(self):- return self._filter.aggregation_group_type_index-- def actor_query(self, limit_actors: Optional[bool] = True):- if self._filter.correlation_type == FunnelCorrelationType.PROPERTIES:- return _FunnelPropertyCorrelationActors(self._filter, self._team, self._base_uri).actor_query(- limit_actors=limit_actors- )- else:- return _FunnelEventsCorrelationActors(self._filter, self._team, self._base_uri).actor_query(- limit_actors=limit_actors- )-- def get_actors(- self,- ) -> tuple[- Union[QuerySet[Person], QuerySet[Group], list[Person], list[Group]],- Union[list[SerializedGroup], list[SerializedPerson]],- int,- ]:- if self._filter.correlation_type == FunnelCorrelationType.PROPERTIES:- return _FunnelPropertyCorrelationActors(self._filter, self._team, self._base_uri).get_actors()- else:- return _FunnelEventsCorrelationActors(self._filter, self._team, self._base_uri).get_actors()---class _FunnelEventsCorrelationActors(ActorBaseQuery):- _filter: Filter- QUERY_TYPE = "funnel_events_correlation_actors"-- def __init__(self, filter: Filter, team: Team, base_uri: str = "/") -> None:- self._funnel_correlation = FunnelCorrelation(filter, team, base_uri=base_uri)- super().__init__(team, filter)-- @cached_property- def aggregation_group_type_index(self):- return self._filter.aggregation_group_type_index-- def actor_query(self, limit_actors: Optional[bool] = True):- if not self._filter.correlation_person_entity:- raise ValidationError("No entity for persons specified")-- assert isinstance(self._filter.correlation_person_entity, Entity)-- (- funnel_persons_query,- funnel_persons_params,- ) = self._funnel_correlation.get_funnel_actors_cte()-- prop_filters = self._filter.correlation_person_entity.property_groups-- # TRICKY: We use "events" as an alias here while the eventquery uses "e" by default- event_query = FunnelEventQuery(self._filter, self._team)- event_query.EVENT_TABLE_ALIAS = "events"-- prop_query, prop_params = event_query._get_prop_groups(- prop_filters,- person_properties_mode=get_person_properties_mode(self._team),- person_id_joined_alias=event_query._get_person_id_alias(self._team.person_on_events_mode),- )-- conversion_filter = (- f"AND actors.steps {'=' if self._filter.correlation_persons_converted else '<>'} target_step"- if self._filter.correlation_persons_converted is not None- else ""- )-- event_join_query = self._funnel_correlation._get_events_join_query()-- recording_event_select_statement = (- ", any(actors.matching_events) AS matching_events" if self._filter.include_recordings else ""- )-- query = f"""- WITH- funnel_actors as ({funnel_persons_query}),- toDateTime(%(date_to)s, %(timezone)s) AS date_to,- toDateTime(%(date_from)s, %(timezone)s) AS date_from,- %(target_step)s AS target_step,- %(funnel_step_names)s as funnel_step_names- SELECT- actors.actor_id AS actor_id- {recording_event_select_statement}- FROM events AS event- {event_join_query}- AND event.event = %(target_event)s- {conversion_filter}- {prop_query}- GROUP BY actor_id- ORDER BY actor_id- {"LIMIT %(limit)s" if limit_actors else ""}- {"OFFSET %(offset)s" if limit_actors else ""}- """-- params = {- **funnel_persons_params,- **prop_params,- "target_event": self._filter.correlation_person_entity.id,- "funnel_step_names": [entity.id for entity in self._filter.events],- "target_step": len(self._filter.entities),- "limit": self._filter.correlation_person_limit,- "offset": self._filter.correlation_person_offset,- }-- return query, params---class _FunnelPropertyCorrelationActors(ActorBaseQuery):- _filter: Filter- QUERY_TYPE = "funnel_property_correlation_actors"-- def __init__(self, filter: Filter, team: Team, base_uri: str = "/") -> None:- # Filtering on persons / groups properties can be pushed down to funnel_actors CTE- new_correlation_filter = filter.shallow_clone(- {- "properties": filter.property_groups.combine_properties(- PropertyOperatorType.AND, filter.correlation_property_values or []- ).to_dict()- }- )- self._funnel_correlation = FunnelCorrelation(new_correlation_filter, team, base_uri=base_uri)- super().__init__(team, filter)-- @cached_property- def aggregation_group_type_index(self):- return self._filter.aggregation_group_type_index-- def actor_query(- self,- limit_actors: Optional[bool] = True,- extra_fields: Optional[list[str]] = None,- ):- if not self._filter.correlation_property_values:- raise ValidationError("Property Correlation expects atleast one Property to get persons for")-- (- funnel_persons_query,- funnel_persons_params,- ) = self._funnel_correlation.get_funnel_actors_cte()-- conversion_filter = (- f"funnel_actors.steps {'=' if self._filter.correlation_persons_converted else '<>'} target_step"- if self._filter.correlation_persons_converted is not None- else ""- )-- recording_event_select_statement = (- ", any(funnel_actors.matching_events) AS matching_events" if self._filter.include_recordings else ""- )-- query = f"""- WITH- funnel_actors AS ({funnel_persons_query}),- %(target_step)s AS target_step- SELECT- funnel_actors.actor_id AS actor_id- {recording_event_select_statement}- FROM funnel_actors- WHERE {conversion_filter}- GROUP BY funnel_actors.actor_id- ORDER BY actor_id- {"LIMIT %(limit)s" if limit_actors else ""}- {"OFFSET %(offset)s" if limit_actors else ""}- """- params = {- **funnel_persons_params,- "target_step": len(self._filter.entities),- "limit": self._filter.correlation_person_limit,- "offset": self._filter.correlation_person_offset,- }-- return query, paramsdiff --git a/ee/clickhouse/queries/funnels/test/test_funnel_correlation.py b/ee/clickhouse/queries/funnels/test/test_funnel_correlation.pydeleted file mode 100644index 0e9fea164e18..000000000000--- a/ee/clickhouse/queries/funnels/test/test_funnel_correlation.py+++ /dev/null@@ -1,2075 +0,0 @@-import unittest-from posthog.test.base import (- APIBaseTest,- ClickhouseTestMixin,- _create_action,- _create_event,- _create_person,- also_test_with_materialized_columns,- also_test_with_person_on_events_v2,- flush_persons_and_events,- snapshot_clickhouse_queries,-)--from rest_framework.exceptions import ValidationError--from posthog.constants import INSIGHT_FUNNELS-from posthog.models.element import Element-from posthog.models.filters import Filter-from posthog.models.group.util import create_group-from posthog.models.instance_setting import override_instance_config-from posthog.test.test_journeys import journeys_for-from posthog.test.test_utils import create_group_type_mapping_without_created_at--from ee.clickhouse.queries.funnels.funnel_correlation import EventContingencyTable, EventStats, FunnelCorrelation-from ee.clickhouse.queries.funnels.funnel_correlation_persons import FunnelCorrelationActors---class TestClickhouseFunnelCorrelation(ClickhouseTestMixin, APIBaseTest):- maxDiff = None-- def _get_actors_for_event(self, filter: Filter, event_name: str, properties=None, success=True):- actor_filter = filter.shallow_clone(- {- "funnel_correlation_person_entity": {- "id": event_name,- "type": "events",- "properties": properties,- },- "funnel_correlation_person_converted": "TrUe" if success else "falSE",- }- )-- _, serialized_actors, _ = FunnelCorrelationActors(actor_filter, self.team).get_actors()- return [str(row["id"]) for row in serialized_actors]-- def _get_actors_for_property(self, filter: Filter, property_values: list, success=True):- actor_filter = filter.shallow_clone(- {- "funnel_correlation_property_values": [- {- "key": prop,- "value": value,- "type": type,- "group_type_index": group_type_index,- }- for prop, value, type, group_type_index in property_values- ],- "funnel_correlation_person_converted": "TrUe" if success else "falSE",- }- )- _, serialized_actors, _ = FunnelCorrelationActors(actor_filter, self.team).get_actors()- return [str(row["id"]) for row in serialized_actors]-- def test_basic_funnel_correlation_with_events(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "events",- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- for i in range(10):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- _create_event(- team=self.team,- event="positively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- for i in range(10, 20):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )-- result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore- expected_odds_ratios = [11, 1 / 11]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "positively_related",- "success_count": 5,- "failure_count": 0,- # "odds_ratio": 11.0,- "correlation_type": "success",- },- {- "event": "negatively_related",- "success_count": 0,- "failure_count": 5,- # "odds_ratio": 1 / 11,- "correlation_type": "failure",- },- ],- )-- self.assertEqual(len(self._get_actors_for_event(filter, "positively_related")), 5)- self.assertEqual(- len(self._get_actors_for_event(filter, "positively_related", success=False)),- 0,- )- self.assertEqual(- len(self._get_actors_for_event(filter, "negatively_related", success=False)),- 5,- )- self.assertEqual(len(self._get_actors_for_event(filter, "negatively_related")), 0)-- # Now exclude positively_related- filter = filter.shallow_clone({"funnel_correlation_exclude_event_names": ["positively_related"]})- correlation = FunnelCorrelation(filter, self.team)-- result = correlation._run()[0]-- odds_ratio = result[0].pop("odds_ratio") # type: ignore- expected_odds_ratio = 1 / 11-- self.assertAlmostEqual(odds_ratio, expected_odds_ratio)-- self.assertEqual(- result,- [- {- "event": "negatively_related",- "success_count": 0,- "failure_count": 5,- # "odds_ratio": 1 / 11,- "correlation_type": "failure",- }- ],- )- # Getting specific people isn't affected by exclude_events- self.assertEqual(len(self._get_actors_for_event(filter, "positively_related")), 5)- self.assertEqual(- len(self._get_actors_for_event(filter, "positively_related", success=False)),- 0,- )- self.assertEqual(- len(self._get_actors_for_event(filter, "negatively_related", success=False)),- 5,- )- self.assertEqual(len(self._get_actors_for_event(filter, "negatively_related")), 0)-- @snapshot_clickhouse_queries- def test_action_events_are_excluded_from_correlations(self):- journey = {}-- for i in range(3):- person_id = f"user_{i}"- events = [- {- "event": "user signed up",- "timestamp": "2020-01-02T14:00:00",- "properties": {"key": "val"},- },- # same event, but missing property, so not part of action.- {"event": "user signed up", "timestamp": "2020-01-02T14:10:00"},- ]- if i % 2 == 0:- events.append({"event": "positively_related", "timestamp": "2020-01-03T14:00:00"})- events.append(- {- "event": "paid",- "timestamp": "2020-01-04T14:00:00",- "properties": {"key": "val"},- }- )-- journey[person_id] = events-- # one failure needed- journey["failure"] = [- {- "event": "user signed up",- "timestamp": "2020-01-02T14:00:00",- "properties": {"key": "val"},- }- ]-- journeys_for(events_by_person=journey, team=self.team) # type: ignore-- sign_up_action = _create_action(- name="user signed up",- team=self.team,- properties=[{"key": "key", "type": "event", "value": ["val"], "operator": "exact"}],- )-- paid_action = _create_action(- name="paid",- team=self.team,- properties=[{"key": "key", "type": "event", "value": ["val"], "operator": "exact"}],- )- filters = {- "events": [],- "actions": [- {"id": sign_up_action.id, "order": 0},- {"id": paid_action.id, "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "events",- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)- result = correlation._run()[0]-- # missing user signed up and paid from result set, as expected- self.assertEqual(- result,- [- {- "event": "positively_related",- "success_count": 2,- "failure_count": 0,- "odds_ratio": 3,- "correlation_type": "success",- }- ],- )-- @also_test_with_person_on_events_v2- @snapshot_clickhouse_queries- def test_funnel_correlation_with_events_and_groups(self):- create_group_type_mapping_without_created_at(- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0- )- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key="org:5",- properties={"industry": "finance"},- )- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key="org:7",- properties={"industry": "finance"},- )-- for i in range(10, 20):- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:{i}",- properties={},- )- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )- if i % 2 == 0:- _create_event(- team=self.team,- event="positively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )- # this event shouldn't show up when dealing with groups- _create_event(- team=self.team,- event="positively_related_without_group",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )-- # one fail group- _create_person(distinct_ids=[f"user_fail"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_fail",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:5"},- )- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={"$group_0": f"org:5"},- )-- # one success group with same filter property- _create_person(distinct_ids=[f"user_succ"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_succ",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:7"},- )- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={"$group_0": f"org:7"},- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_succ",- timestamp="2020-01-04T14:00:00Z",- properties={"$group_0": f"org:7"},- )-- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "events",- "aggregation_group_type_index": 0,- }-- filter = Filter(data=filters)- result = FunnelCorrelation(filter, self.team)._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore- expected_odds_ratios = [12 / 7, 1 / 11]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "positively_related",- "success_count": 5,- "failure_count": 0,- # "odds_ratio": 12/7,- "correlation_type": "success",- },- {- "event": "negatively_related",- "success_count": 1,- "failure_count": 1,- # "odds_ratio": 1 / 11,- "correlation_type": "failure",- },- ],- )-- self.assertEqual(len(self._get_actors_for_event(filter, "positively_related")), 5)- self.assertEqual(- len(self._get_actors_for_event(filter, "positively_related", success=False)),- 0,- )- self.assertEqual(len(self._get_actors_for_event(filter, "negatively_related")), 1)- self.assertEqual(- len(self._get_actors_for_event(filter, "negatively_related", success=False)),- 1,- )-- # Now exclude all groups in positive- filter = filter.shallow_clone(- {- "properties": [- {- "key": "industry",- "value": "finance",- "type": "group",- "group_type_index": 0,- }- ]- }- )- result = FunnelCorrelation(filter, self.team)._run()[0]-- odds_ratio = result[0].pop("odds_ratio") # type: ignore- expected_odds_ratio = 1- # success total and failure totals remove other groups too-- self.assertAlmostEqual(odds_ratio, expected_odds_ratio)-- self.assertEqual(- result,- [- {- "event": "negatively_related",- "success_count": 1,- "failure_count": 1,- # "odds_ratio": 1,- "correlation_type": "failure",- }- ],- )-- self.assertEqual(len(self._get_actors_for_event(filter, "negatively_related")), 1)- self.assertEqual(- len(self._get_actors_for_event(filter, "negatively_related", success=False)),- 1,- )-- @also_test_with_materialized_columns(event_properties=[], person_properties=["$browser"])- @snapshot_clickhouse_queries- def test_basic_funnel_correlation_with_properties(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "properties",- "funnel_correlation_names": ["$browser"],- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- for i in range(10):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- for i in range(10, 20):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )-- # One Positive with failure- _create_person(- distinct_ids=[f"user_fail"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_fail",- timestamp="2020-01-02T14:00:00Z",- )-- # One Negative with success- _create_person(- distinct_ids=[f"user_succ"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_succ",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_succ",- timestamp="2020-01-04T14:00:00Z",- )-- result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore-- # Success Total = 11, Failure Total = 11- #- # Browser::Positive- # Success: 10- # Failure: 1-- # Browser::Negative- # Success: 1- # Failure: 10-- prior_count = 1- expected_odds_ratios = [- ((10 + prior_count) / (1 + prior_count)) * ((11 - 1 + prior_count) / (11 - 10 + prior_count)),- ((1 + prior_count) / (10 + prior_count)) * ((11 - 10 + prior_count) / (11 - 1 + prior_count)),- ]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "$browser::Positive",- "success_count": 10,- "failure_count": 1,- # "odds_ratio": 121/4,- "correlation_type": "success",- },- {- "event": "$browser::Negative",- "success_count": 1,- "failure_count": 10,- # "odds_ratio": 4/121,- "correlation_type": "failure",- },- ],- )-- self.assertEqual(- len(self._get_actors_for_property(filter, [("$browser", "Positive", "person", None)])),- 10,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("$browser", "Positive", "person", None)], False)),- 1,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("$browser", "Negative", "person", None)])),- 1,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("$browser", "Negative", "person", None)], False)),- 10,- )-- # TODO: Delete this test when moved to person-on-events- @also_test_with_materialized_columns(- event_properties=[], person_properties=["$browser"], verify_no_jsonextract=False- )- @snapshot_clickhouse_queries- def test_funnel_correlation_with_properties_and_groups(self):- create_group_type_mapping_without_created_at(- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0- )-- for i in range(10):- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:{i}",- properties={"industry": "positive"},- )- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )-- for i in range(10, 20):- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:{i}",- properties={"industry": "negative"},- )- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )- if i % 2 == 0:- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )-- # One Positive with failure- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:fail",- properties={"industry": "positive"},- )- _create_person(- distinct_ids=[f"user_fail"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_fail",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:fail"},- )-- # One Negative with success- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:succ",- properties={"industry": "negative"},- )- _create_person(- distinct_ids=[f"user_succ"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_succ",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:succ"},- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_succ",- timestamp="2020-01-04T14:00:00Z",- properties={"$group_0": f"org:succ"},- )-- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "properties",- "funnel_correlation_names": ["industry"],- "aggregation_group_type_index": 0,- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)- result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore-- # Success Total = 11, Failure Total = 11- #- # Industry::Positive- # Success: 10- # Failure: 1-- # Industry::Negative- # Success: 1- # Failure: 10-- prior_count = 1- expected_odds_ratios = [- ((10 + prior_count) / (1 + prior_count)) * ((11 - 1 + prior_count) / (11 - 10 + prior_count)),- ((1 + prior_count) / (10 + prior_count)) * ((11 - 10 + prior_count) / (11 - 1 + prior_count)),- ]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "industry::positive",- "success_count": 10,- "failure_count": 1,- # "odds_ratio": 121/4,- "correlation_type": "success",- },- {- "event": "industry::negative",- "success_count": 1,- "failure_count": 10,- # "odds_ratio": 4/121,- "correlation_type": "failure",- },- ],- )-- self.assertEqual(- len(self._get_actors_for_property(filter, [("industry", "positive", "group", 0)])),- 10,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("industry", "positive", "group", 0)], False)),- 1,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("industry", "negative", "group", 0)])),- 1,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("industry", "negative", "group", 0)], False)),- 10,- )-- # test with `$all` as property- # _run property correlation with filter on all properties- filter = filter.shallow_clone({"funnel_correlation_names": ["$all"]})- correlation = FunnelCorrelation(filter, self.team)-- new_result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in new_result] # type: ignore-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(new_result, result)-- @also_test_with_materialized_columns(- event_properties=[],- person_properties=["$browser"],- verify_no_jsonextract=False,- )- @also_test_with_person_on_events_v2- @snapshot_clickhouse_queries- def test_funnel_correlation_with_properties_and_groups_person_on_events(self):- create_group_type_mapping_without_created_at(- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0- )-- for i in range(10):- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:{i}",- properties={"industry": "positive"},- )- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )-- for i in range(10, 20):- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:{i}",- properties={"industry": "negative"},- )- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )- if i % 2 == 0:- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={"$group_0": f"org:{i}"},- )-- # One Positive with failure- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:fail",- properties={"industry": "positive"},- )- _create_person(- distinct_ids=[f"user_fail"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_fail",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:fail"},- )-- # One Negative with success- create_group(- team_id=self.team.pk,- group_type_index=0,- group_key=f"org:succ",- properties={"industry": "negative"},- )- _create_person(- distinct_ids=[f"user_succ"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_succ",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_0": f"org:succ"},- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_succ",- timestamp="2020-01-04T14:00:00Z",- properties={"$group_0": f"org:succ"},- )-- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "properties",- "funnel_correlation_names": ["industry"],- "aggregation_group_type_index": 0,- }-- with override_instance_config("PERSON_ON_EVENTS_ENABLED", True):- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)- result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore-- # Success Total = 11, Failure Total = 11- #- # Industry::Positive- # Success: 10- # Failure: 1-- # Industry::Negative- # Success: 1- # Failure: 10-- prior_count = 1- expected_odds_ratios = [- ((10 + prior_count) / (1 + prior_count)) * ((11 - 1 + prior_count) / (11 - 10 + prior_count)),- ((1 + prior_count) / (10 + prior_count)) * ((11 - 10 + prior_count) / (11 - 1 + prior_count)),- ]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "industry::positive",- "success_count": 10,- "failure_count": 1,- # "odds_ratio": 121/4,- "correlation_type": "success",- },- {- "event": "industry::negative",- "success_count": 1,- "failure_count": 10,- # "odds_ratio": 4/121,- "correlation_type": "failure",- },- ],- )-- self.assertEqual(- len(self._get_actors_for_property(filter, [("industry", "positive", "group", 0)])),- 10,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("industry", "positive", "group", 0)], False)),- 1,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("industry", "negative", "group", 0)])),- 1,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("industry", "negative", "group", 0)], False)),- 10,- )-- # test with `$all` as property- # _run property correlation with filter on all properties- filter = filter.shallow_clone({"funnel_correlation_names": ["$all"]})- correlation = FunnelCorrelation(filter, self.team)-- new_result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in new_result] # type: ignore-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(new_result, result)-- def test_no_divide_by_zero_errors(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- for i in range(2):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- # failure count for this event is 0- _create_event(- team=self.team,- event="positive",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- for i in range(2, 4):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- # success count for this event is 0- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )-- results = correlation._run()- self.assertFalse(results[1])-- result = results[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore- expected_odds_ratios = [9, 1 / 3]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "positive",- "success_count": 2,- "failure_count": 0,- # "odds_ratio": 9.0,- "correlation_type": "success",- },- {- "event": "negatively_related",- "success_count": 0,- "failure_count": 1,- # "odds_ratio": 1 / 3,- "correlation_type": "failure",- },- ],- )-- def test_correlation_with_properties_raises_validation_error(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "properties",- # "funnel_correlation_names": ["$browser"], missing value- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- _create_person(- distinct_ids=[f"user_1"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_1",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="rick",- distinct_id=f"user_1",- timestamp="2020-01-03T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_1",- timestamp="2020-01-04T14:00:00Z",- )- flush_persons_and_events()-- with self.assertRaises(ValidationError):- correlation._run()-- filter = filter.shallow_clone({"funnel_correlation_type": "event_with_properties"})- # missing "funnel_correlation_event_names": ["rick"],- with self.assertRaises(ValidationError):- FunnelCorrelation(filter, self.team)._run()-- @also_test_with_materialized_columns(- event_properties=[], person_properties=["$browser"], verify_no_jsonextract=False- )- def test_correlation_with_multiple_properties(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "properties",- "funnel_correlation_names": ["$browser", "$nice"],- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- # 5 successful people with both properties- for i in range(5):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Positive", "$nice": "very"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- # 10 successful people with some different properties- for i in range(5, 15):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Positive", "$nice": "not"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- # 5 Unsuccessful people with some common properties- for i in range(15, 20):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Negative", "$nice": "smh"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )-- # One Positive with failure, no $nice property- _create_person(- distinct_ids=[f"user_fail"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_fail",- timestamp="2020-01-02T14:00:00Z",- )-- # One Negative with success, no $nice property- _create_person(- distinct_ids=[f"user_succ"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_succ",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_succ",- timestamp="2020-01-04T14:00:00Z",- )-- result = correlation._run()[0]-- # Success Total = 5 + 10 + 1 = 16- # Failure Total = 5 + 1 = 6- # Add 1 for priors-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore- expected_odds_ratios = [- (16 / 2) * ((7 - 1) / (17 - 15)),- (11 / 1) * ((7 - 0) / (17 - 10)),- (6 / 1) * ((7 - 0) / (17 - 5)),- (1 / 6) * ((7 - 5) / (17 - 0)),- (2 / 6) * ((7 - 5) / (17 - 1)),- (2 / 2) * ((7 - 1) / (17 - 1)),- ]- # (success + 1) / (failure + 1)-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- expected_result = [- {- "event": "$browser::Positive",- "success_count": 15,- "failure_count": 1,- # "odds_ratio": 24,- "correlation_type": "success",- },- {- "event": "$nice::not",- "success_count": 10,- "failure_count": 0,- # "odds_ratio": 11,- "correlation_type": "success",- },- {- "event": "$nice::very",- "success_count": 5,- "failure_count": 0,- # "odds_ratio": 3.5,- "correlation_type": "success",- },- {- "event": "$nice::smh",- "success_count": 0,- "failure_count": 5,- # "odds_ratio": 0.0196078431372549,- "correlation_type": "failure",- },- {- "event": "$browser::Negative",- "success_count": 1,- "failure_count": 5,- # "odds_ratio": 0.041666666666666664,- "correlation_type": "failure",- },- {- "event": "$nice::",- "success_count": 1,- "failure_count": 1,- # "odds_ratio": 0.375,- "correlation_type": "failure",- },- ]-- self.assertEqual(result, expected_result)-- # _run property correlation with filter on all properties- filter = filter.shallow_clone({"funnel_correlation_names": ["$all"]})- correlation = FunnelCorrelation(filter, self.team)-- new_result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in new_result] # type: ignore-- new_expected_odds_ratios = expected_odds_ratios[:-1]- new_expected_result = expected_result[:-1]- # When querying all properties, we don't consider properties that don't exist for part of the data- # since users aren't explicitly asking for that property. Thus,- # We discard $nice:: because it's an empty result set-- for odds, expected_odds in zip(odds_ratios, new_expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(new_result, new_expected_result)-- filter = filter.shallow_clone({"funnel_correlation_exclude_names": ["$browser"]})- # search for $all but exclude $browser- correlation = FunnelCorrelation(filter, self.team)-- new_result = correlation._run()[0]- odds_ratios = [item.pop("odds_ratio") for item in new_result] # type: ignore-- new_expected_odds_ratios = expected_odds_ratios[1:4] # choosing the $nice property values- new_expected_result = expected_result[1:4]-- for odds, expected_odds in zip(odds_ratios, new_expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(new_result, new_expected_result)-- self.assertEqual(- len(self._get_actors_for_property(filter, [("$nice", "not", "person", None)])),- 10,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("$nice", "", "person", None)], False)),- 1,- )- self.assertEqual(- len(self._get_actors_for_property(filter, [("$nice", "very", "person", None)])),- 5,- )-- def test_discarding_insignificant_events(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "events",- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- for i in range(10):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- _create_event(- team=self.team,- event="positively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )- if i % 10 == 0:- _create_event(- team=self.team,- event="low_sig_positively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:20:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- for i in range(10, 20):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )- if i % 5 == 0:- _create_event(- team=self.team,- event="low_sig_negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )-- # Total 10 positive, 10 negative- # low sig count = 1 and 2, high sig count >= 5- # Thus, to discard the low sig count, % needs to be >= 10%, or count >= 2-- # Discard both due to %- FunnelCorrelation.MIN_PERSON_PERCENTAGE = 0.11- FunnelCorrelation.MIN_PERSON_COUNT = 25- result = correlation._run()[0]- self.assertEqual(len(result), 2)-- def test_events_within_conversion_window_for_correlation(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "funnel_window_interval": "10",- "funnel_window_interval_unit": "minute",- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "events",- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- _create_person(distinct_ids=["user_successful"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id="user_successful",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="positively_related",- distinct_id="user_successful",- timestamp="2020-01-02T14:02:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id="user_successful",- timestamp="2020-01-02T14:06:00Z",- )-- _create_person(distinct_ids=["user_dropoff"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id="user_dropoff",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="NOT_negatively_related",- distinct_id="user_dropoff",- timestamp="2020-01-02T14:15:00Z", # event happened outside conversion window- )-- result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore- expected_odds_ratios = [4]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "positively_related",- "success_count": 1,- "failure_count": 0,- # "odds_ratio": 4.0,- "correlation_type": "success",- }- ],- )-- @also_test_with_materialized_columns(["blah", "signup_source"], verify_no_jsonextract=False)- def test_funnel_correlation_with_event_properties(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "event_with_properties",- "funnel_correlation_event_names": [- "positively_related",- "negatively_related",- ],- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- for i in range(10):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- _create_event(- team=self.team,- event="positively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={- "signup_source": "facebook" if i % 4 == 0 else "email",- "blah": "value_bleh",- },- )- # source: email occurs only twice, so would be discarded from result set- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- for i in range(10, 20):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={"signup_source": "shazam" if i % 6 == 0 else "email"},- )- # source: shazam occurs only once, so would be discarded from result set-- result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore- expected_odds_ratios = [11, 5.5, 2 / 11]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "positively_related::blah::value_bleh",- "success_count": 5,- "failure_count": 0,- # "odds_ratio": 11.0,- "correlation_type": "success",- },- {- "event": "positively_related::signup_source::facebook",- "success_count": 3,- "failure_count": 0,- # "odds_ratio": 5.5,- "correlation_type": "success",- },- {- "event": "negatively_related::signup_source::email",- "success_count": 0,- "failure_count": 3,- # "odds_ratio": 0.18181818181818182,- "correlation_type": "failure",- },- ],- )-- self.assertEqual(- len(self._get_actors_for_event(filter, "positively_related", {"blah": "value_bleh"})),- 5,- )- self.assertEqual(- len(self._get_actors_for_event(filter, "positively_related", {"signup_source": "facebook"})),- 3,- )- self.assertEqual(- len(self._get_actors_for_event(filter, "positively_related", {"signup_source": "facebook"}, False)),- 0,- )- self.assertEqual(- len(self._get_actors_for_event(filter, "negatively_related", {"signup_source": "email"}, False)),- 3,- )-- @also_test_with_materialized_columns(["blah", "signup_source"], verify_no_jsonextract=False)- @snapshot_clickhouse_queries- def test_funnel_correlation_with_event_properties_and_groups(self):- # same test as test_funnel_correlation_with_event_properties but with events attached to groups- create_group_type_mapping_without_created_at(- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=1- )-- for i in range(10):- create_group(- team_id=self.team.pk,- group_type_index=1,- group_key=f"org:{i}",- properties={"industry": "positive"},- )- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_1": f"org:{i}"},- )- if i % 2 == 0:- _create_event(- team=self.team,- event="positively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={- "signup_source": "facebook" if i % 4 == 0 else "email",- "blah": "value_bleh",- "$group_1": f"org:{i}",- },- )- # source: email occurs only twice, so would be discarded from result set- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- properties={"$group_1": f"org:{i}"},- )-- for i in range(10, 20):- create_group(- team_id=self.team.pk,- group_type_index=1,- group_key=f"org:{i}",- properties={"industry": "positive"},- )- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- properties={"$group_1": f"org:{i}"},- )- if i % 2 == 0:- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={- "signup_source": "shazam" if i % 6 == 0 else "email",- "$group_1": f"org:{i}",- },- )- # source: shazam occurs only once, so would be discarded from result set-- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "aggregation_group_type_index": 1,- "funnel_correlation_type": "event_with_properties",- "funnel_correlation_event_names": [- "positively_related",- "negatively_related",- ],- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)- result = correlation._run()[0]-- odds_ratios = [item.pop("odds_ratio") for item in result] # type: ignore- expected_odds_ratios = [11, 5.5, 2 / 11]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": "positively_related::blah::value_bleh",- "success_count": 5,- "failure_count": 0,- # "odds_ratio": 11.0,- "correlation_type": "success",- },- {- "event": "positively_related::signup_source::facebook",- "success_count": 3,- "failure_count": 0,- # "odds_ratio": 5.5,- "correlation_type": "success",- },- {- "event": "negatively_related::signup_source::email",- "success_count": 0,- "failure_count": 3,- # "odds_ratio": 0.18181818181818182,- "correlation_type": "failure",- },- ],- )-- def test_funnel_correlation_with_event_properties_exclusions(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "event_with_properties",- "funnel_correlation_event_names": ["positively_related"],- "funnel_correlation_event_exclude_property_names": ["signup_source"],- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- # Need more than 2 events to get a correlation- for i in range(3):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="positively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- properties={"signup_source": "facebook", "blah": "value_bleh"},- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- # Atleast one person that fails, to ensure we get results- _create_person(distinct_ids=[f"user_fail"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_fail",- timestamp="2020-01-02T14:00:00Z",- )-- result = correlation._run()[0]- self.assertEqual(- result,- [- {- "event": "positively_related::blah::value_bleh",- "success_count": 3,- "failure_count": 0,- "odds_ratio": 8,- "correlation_type": "success",- },- # missing signup_source, as expected- ],- )-- self.assertEqual(- len(self._get_actors_for_event(filter, "positively_related", {"blah": "value_bleh"})),- 3,- )-- # If you search for persons with a specific property, even if excluded earlier, you should get them- self.assertEqual(- len(self._get_actors_for_event(filter, "positively_related", {"signup_source": "facebook"})),- 3,- )-- @also_test_with_materialized_columns(["$event_type", "signup_source"])- def test_funnel_correlation_with_event_properties_autocapture(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "event_with_properties",- "funnel_correlation_event_names": ["$autocapture"],- }-- filter = Filter(data=filters)- correlation = FunnelCorrelation(filter, self.team)-- # Need a minimum of 3 hits to get a correlation result- for i in range(6):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="$autocapture",- distinct_id=f"user_{i}",- elements=[Element(nth_of_type=1, nth_child=0, tag_name="a", href="/movie")],- timestamp="2020-01-03T14:00:00Z",- properties={"signup_source": "email", "$event_type": "click"},- )- # Test two different types of autocapture elements, with different counts, so we can accurately test results- if i % 2 == 0:- _create_event(- team=self.team,- event="$autocapture",- distinct_id=f"user_{i}",- elements=[- Element(- nth_of_type=1,- nth_child=0,- tag_name="button",- text="Pay $10",- )- ],- timestamp="2020-01-03T14:00:00Z",- properties={"signup_source": "facebook", "$event_type": "submit"},- )-- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- # Atleast one person that fails, to ensure we get results- _create_person(distinct_ids=[f"user_fail"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_fail",- timestamp="2020-01-02T14:00:00Z",- )-- result = correlation._run()[0]-- # $autocapture results only return elements chain- self.assertEqual(- result,- [- {- "event": '$autocapture::elements_chain::click__~~__a:href="/movie"nth-child="0"nth-of-type="1"',- "success_count": 6,- "failure_count": 0,- "odds_ratio": 14.0,- "correlation_type": "success",- },- {- "event": '$autocapture::elements_chain::submit__~~__button:nth-child="0"nth-of-type="1"text="Pay $10"',- "success_count": 3,- "failure_count": 0,- "odds_ratio": 2.0,- "correlation_type": "success",- },- ],- )-- self.assertEqual(- len(self._get_actors_for_event(filter, "$autocapture", {"signup_source": "facebook"})),- 3,- )- self.assertEqual(- len(self._get_actors_for_event(filter, "$autocapture", {"$event_type": "click"})),- 6,- )- self.assertEqual(- len(- self._get_actors_for_event(- filter,- "$autocapture",- [- {- "key": "tag_name",- "operator": "exact",- "type": "element",- "value": "button",- },- {- "key": "text",- "operator": "exact",- "type": "element",- "value": "Pay $10",- },- ],- )- ),- 3,- )- self.assertEqual(- len(- self._get_actors_for_event(- filter,- "$autocapture",- [- {- "key": "tag_name",- "operator": "exact",- "type": "element",- "value": "a",- },- {- "key": "href",- "operator": "exact",- "type": "element",- "value": "/movie",- },- ],- )- ),- 6,- )---class TestCorrelationFunctions(unittest.TestCase):- def test_are_results_insignificant(self):- # Same setup as above test: test_discarding_insignificant_events- contingency_tables = [- EventContingencyTable(- event="negatively_related",- visited=EventStats(success_count=0, failure_count=5),- success_total=10,- failure_total=10,- ),- EventContingencyTable(- event="positively_related",- visited=EventStats(success_count=5, failure_count=0),- success_total=10,- failure_total=10,- ),- EventContingencyTable(- event="low_sig_negatively_related",- visited=EventStats(success_count=0, failure_count=2),- success_total=10,- failure_total=10,- ),- EventContingencyTable(- event="low_sig_positively_related",- visited=EventStats(success_count=1, failure_count=0),- success_total=10,- failure_total=10,- ),- ]-- # Discard both low_sig due to %- FunnelCorrelation.MIN_PERSON_PERCENTAGE = 0.11- FunnelCorrelation.MIN_PERSON_COUNT = 25- result = [- 1- for contingency_table in contingency_tables- if not FunnelCorrelation.are_results_insignificant(contingency_table)- ]- self.assertEqual(len(result), 2)-- # Discard one low_sig due to %- FunnelCorrelation.MIN_PERSON_PERCENTAGE = 0.051- FunnelCorrelation.MIN_PERSON_COUNT = 25- result = [- 1- for contingency_table in contingency_tables- if not FunnelCorrelation.are_results_insignificant(contingency_table)- ]- self.assertEqual(len(result), 3)-- # Discard both due to count- FunnelCorrelation.MIN_PERSON_PERCENTAGE = 0.5- FunnelCorrelation.MIN_PERSON_COUNT = 3- result = [- 1- for contingency_table in contingency_tables- if not FunnelCorrelation.are_results_insignificant(contingency_table)- ]- self.assertEqual(len(result), 2)-- # Discard one due to count- FunnelCorrelation.MIN_PERSON_PERCENTAGE = 0.5- FunnelCorrelation.MIN_PERSON_COUNT = 2- result = [- 1- for contingency_table in contingency_tables- if not FunnelCorrelation.are_results_insignificant(contingency_table)- ]- self.assertEqual(len(result), 3)-- # Discard everything due to %- FunnelCorrelation.MIN_PERSON_PERCENTAGE = 0.5- FunnelCorrelation.MIN_PERSON_COUNT = 100- result = [- 1- for contingency_table in contingency_tables- if not FunnelCorrelation.are_results_insignificant(contingency_table)- ]- self.assertEqual(len(result), 0)-- # Discard everything due to count- FunnelCorrelation.MIN_PERSON_PERCENTAGE = 0.5- FunnelCorrelation.MIN_PERSON_COUNT = 6- result = [- 1- for contingency_table in contingency_tables- if not FunnelCorrelation.are_results_insignificant(contingency_table)- ]- self.assertEqual(len(result), 0)diff --git a/ee/clickhouse/queries/funnels/test/test_funnel_correlations_persons.py b/ee/clickhouse/queries/funnels/test/test_funnel_correlations_persons.pydeleted file mode 100644index b2007f72b774..000000000000--- a/ee/clickhouse/queries/funnels/test/test_funnel_correlations_persons.py+++ /dev/null@@ -1,590 +0,0 @@-from datetime import datetime, timedelta-from uuid import UUID--from freezegun import freeze_time-from posthog.test.base import (- APIBaseTest,- ClickhouseTestMixin,- _create_event,- _create_person,- snapshot_clickhouse_queries,-)--from django.utils import timezone--from posthog.constants import INSIGHT_FUNNELS-from posthog.models import Filter-from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary-from posthog.test.test_journeys import journeys_for--from ee.clickhouse.queries.funnels.funnel_correlation_persons import FunnelCorrelationActors--FORMAT_TIME = "%Y-%m-%d 00:00:00"-MAX_STEP_COLUMN = 0-COUNT_COLUMN = 1-PERSON_ID_COLUMN = 2---class TestClickhouseFunnelCorrelationsActors(ClickhouseTestMixin, APIBaseTest):- maxDiff = None-- def _setup_basic_test(self):- filters = {- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "events",- }-- filter = Filter(data=filters)-- success_target_persons = []- failure_target_persons = []- events_by_person = {}- for i in range(10):- person_id = f"user_{i}"- person = _create_person(distinct_ids=[person_id], team_id=self.team.pk)- events_by_person[person_id] = [{"event": "user signed up", "timestamp": datetime(2020, 1, 2, 14)}]-- if i % 2 == 0:- events_by_person[person_id].append(- {- "event": "positively_related",- "timestamp": datetime(2020, 1, 3, 14),- }- )-- success_target_persons.append(str(person.uuid))-- events_by_person[person_id].append({"event": "paid", "timestamp": datetime(2020, 1, 4, 14)})-- for i in range(10, 20):- person_id = f"user_{i}"- person = _create_person(distinct_ids=[person_id], team_id=self.team.pk)- events_by_person[person_id] = [{"event": "user signed up", "timestamp": datetime(2020, 1, 2, 14)}]- if i % 2 == 0:- events_by_person[person_id].append(- {- "event": "negatively_related",- "timestamp": datetime(2020, 1, 3, 14),- }- )- failure_target_persons.append(str(person.uuid))-- # One positively_related as failure- person_fail_id = f"user_fail"- person_fail = _create_person(distinct_ids=[person_fail_id], team_id=self.team.pk)- events_by_person[person_fail_id] = [- {"event": "user signed up", "timestamp": datetime(2020, 1, 2, 14)},- {"event": "positively_related", "timestamp": datetime(2020, 1, 3, 14)},- ]-- # One negatively_related as success- person_success_id = f"user_succ"- person_succ = _create_person(distinct_ids=[person_success_id], team_id=self.team.pk)- events_by_person[person_success_id] = [- {"event": "user signed up", "timestamp": datetime(2020, 1, 2, 14)},- {"event": "negatively_related", "timestamp": datetime(2020, 1, 3, 14)},- {"event": "paid", "timestamp": datetime(2020, 1, 4, 14)},- ]- journeys_for(events_by_person, self.team, create_people=False)-- return (- filter,- success_target_persons,- failure_target_persons,- person_fail,- person_succ,- )-- def test_basic_funnel_correlation_with_events(self):- (- filter,- success_target_persons,- failure_target_persons,- person_fail,- person_succ,- ) = self._setup_basic_test()-- # test positively_related successes- filter = filter.shallow_clone(- {- "funnel_correlation_person_entity": {- "id": "positively_related",- "type": "events",- },- "funnel_correlation_person_converted": "TrUe",- }- )- _, serialized_actors, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertCountEqual([str(val["id"]) for val in serialized_actors], success_target_persons)-- # test negatively_related failures- filter = filter.shallow_clone(- {- "funnel_correlation_person_entity": {- "id": "negatively_related",- "type": "events",- },- "funnel_correlation_person_converted": "falsE",- }- )-- _, serialized_actors, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertCountEqual([str(val["id"]) for val in serialized_actors], failure_target_persons)-- # test positively_related failures- filter = filter.shallow_clone(- {- "funnel_correlation_person_entity": {- "id": "positively_related",- "type": "events",- },- "funnel_correlation_person_converted": "False",- }- )- _, serialized_actors, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertCountEqual([str(val["id"]) for val in serialized_actors], [str(person_fail.uuid)])-- # test negatively_related successes- filter = filter.shallow_clone(- {- "funnel_correlation_person_entity": {- "id": "negatively_related",- "type": "events",- },- "funnel_correlation_person_converted": "trUE",- }- )- _, serialized_actors, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertCountEqual([str(val["id"]) for val in serialized_actors], [str(person_succ.uuid)])-- # test all positively_related- filter = filter.shallow_clone(- {- "funnel_correlation_person_entity": {- "id": "positively_related",- "type": "events",- },- "funnel_correlation_person_converted": None,- }- )- _, serialized_actors, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertCountEqual(- [str(val["id"]) for val in serialized_actors],- [*success_target_persons, str(person_fail.uuid)],- )-- # test all negatively_related- filter = filter.shallow_clone(- {- "funnel_correlation_person_entity": {- "id": "negatively_related",- "type": "events",- },- "funnel_correlation_person_converted": None,- }- )- _, serialized_actors, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertCountEqual(- [str(val["id"]) for val in serialized_actors],- [*failure_target_persons, str(person_succ.uuid)],- )-- def test_people_arent_returned_multiple_times(self):- people = journeys_for(- {- "user_1": [- {"event": "user signed up", "timestamp": datetime(2020, 1, 2, 14)},- {- "event": "positively_related",- "timestamp": datetime(2020, 1, 3, 14),- },- # duplicate event- {- "event": "positively_related",- "timestamp": datetime(2020, 1, 3, 14),- },- {"event": "paid", "timestamp": datetime(2020, 1, 4, 14)},- ]- },- self.team,- )-- filter = Filter(- data={- "events": [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ],- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "events",- "funnel_correlation_person_entity": {- "id": "positively_related",- "type": "events",- },- "funnel_correlation_person_converted": "TrUe",- }- )- _, serialized_actors, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertCountEqual([str(val["id"]) for val in serialized_actors], [str(people["user_1"].uuid)])-- @snapshot_clickhouse_queries- @freeze_time("2021-01-02 00:00:00.000Z")- def test_funnel_correlation_on_event_with_recordings(self):- p1 = _create_person(distinct_ids=["user_1"], team=self.team, properties={"foo": "bar"})- _create_event(- event="$pageview",- distinct_id="user_1",- team=self.team,- timestamp=timezone.now(),- properties={"$session_id": "s2", "$window_id": "w1"},- event_uuid="11111111-1111-1111-1111-111111111111",- )- _create_event(- event="insight loaded",- distinct_id="user_1",- team=self.team,- timestamp=(timezone.now() + timedelta(minutes=2)),- properties={"$session_id": "s2", "$window_id": "w2"},- event_uuid="31111111-1111-1111-1111-111111111111",- )- _create_event(- event="insight analyzed",- distinct_id="user_1",- team=self.team,- timestamp=(timezone.now() + timedelta(minutes=3)),- properties={"$session_id": "s2", "$window_id": "w2"},- event_uuid="21111111-1111-1111-1111-111111111111",- )-- timestamp = datetime(2021, 1, 2, 0, 0, 0)- produce_replay_summary(- team_id=self.team.pk,- session_id="s2",- distinct_id="user_1",- first_timestamp=timestamp,- last_timestamp=timestamp,- )-- # Success filter- filter = Filter(- data={- "insight": INSIGHT_FUNNELS,- "date_from": "2021-01-01",- "date_to": "2021-01-08",- "funnel_correlation_type": "events",- "events": [- {"id": "$pageview", "order": 0},- {"id": "insight analyzed", "order": 1},- ],- "include_recordings": "true",- "funnel_correlation_person_entity": {- "id": "insight loaded",- "type": "events",- },- "funnel_correlation_person_converted": "True",- }- )- _, results, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertEqual(results[0]["id"], p1.uuid)- self.assertEqual(- results[0]["matched_recordings"],- [- {- "events": [- {- "timestamp": timezone.now() + timedelta(minutes=3),- "uuid": UUID("21111111-1111-1111-1111-111111111111"),- "window_id": "w2",- }- ],- "session_id": "s2",- }- ],- )-- # Drop off filter- filter = Filter(- data={- "insight": INSIGHT_FUNNELS,- "date_from": "2021-01-01",- "date_to": "2021-01-08",- "funnel_correlation_type": "events",- "events": [- {"id": "$pageview", "order": 0},- {"id": "insight analyzed", "order": 1},- {"id": "insight updated", "order": 2},- ],- "include_recordings": "true",- "funnel_correlation_person_entity": {- "id": "insight loaded",- "type": "events",- },- "funnel_correlation_person_converted": "False",- }- )- _, results, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertEqual(results[0]["id"], p1.uuid)- self.assertEqual(- results[0]["matched_recordings"],- [- {- "events": [- {- "timestamp": timezone.now() + timedelta(minutes=3),- "uuid": UUID("21111111-1111-1111-1111-111111111111"),- "window_id": "w2",- }- ],- "session_id": "s2",- }- ],- )-- @snapshot_clickhouse_queries- @freeze_time("2021-01-02 00:00:00.000Z")- def test_funnel_correlation_on_properties_with_recordings(self):- p1 = _create_person(distinct_ids=["user_1"], team=self.team, properties={"foo": "bar"})- _create_event(- event="$pageview",- distinct_id="user_1",- team=self.team,- timestamp=timezone.now(),- properties={"$session_id": "s2", "$window_id": "w1"},- event_uuid="11111111-1111-1111-1111-111111111111",- )- _create_event(- event="insight analyzed",- distinct_id="user_1",- team=self.team,- timestamp=(timezone.now() + timedelta(minutes=3)),- properties={"$session_id": "s2", "$window_id": "w2"},- event_uuid="21111111-1111-1111-1111-111111111111",- )-- timestamp = datetime(2021, 1, 2, 0, 0, 0)- produce_replay_summary(- team_id=self.team.pk,- session_id="s2",- distinct_id="user_1",- first_timestamp=timestamp,- last_timestamp=timestamp,- )-- # Success filter- filter = Filter(- data={- "insight": INSIGHT_FUNNELS,- "date_from": "2021-01-01",- "date_to": "2021-01-08",- "funnel_correlation_type": "properties",- "events": [- {"id": "$pageview", "order": 0},- {"id": "insight analyzed", "order": 1},- ],- "include_recordings": "true",- "funnel_correlation_property_values": [- {- "key": "foo",- "value": "bar",- "operator": "exact",- "type": "person",- }- ],- "funnel_correlation_person_converted": "True",- }- )- _, results, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertEqual(results[0]["id"], p1.uuid)- self.assertEqual(- results[0]["matched_recordings"],- [- {- "events": [- {- "timestamp": timezone.now() + timedelta(minutes=3),- "uuid": UUID("21111111-1111-1111-1111-111111111111"),- "window_id": "w2",- }- ],- "session_id": "s2",- }- ],- )-- @snapshot_clickhouse_queries- @freeze_time("2021-01-02 00:00:00.000Z")- def test_strict_funnel_correlation_with_recordings(self):- # First use that successfully completes the strict funnel- p1 = _create_person(distinct_ids=["user_1"], team=self.team, properties={"foo": "bar"})- _create_event(- event="$pageview",- distinct_id="user_1",- team=self.team,- timestamp=timezone.now(),- properties={"$session_id": "s2", "$window_id": "w1"},- event_uuid="11111111-1111-1111-1111-111111111111",- )- _create_event(- event="insight analyzed",- distinct_id="user_1",- team=self.team,- timestamp=(timezone.now() + timedelta(minutes=3)),- properties={"$session_id": "s2", "$window_id": "w2"},- event_uuid="31111111-1111-1111-1111-111111111111",- )- _create_event(- event="insight analyzed", # Second event should not be returned- distinct_id="user_1",- team=self.team,- timestamp=(timezone.now() + timedelta(minutes=4)),- properties={"$session_id": "s2", "$window_id": "w2"},- event_uuid="41111111-1111-1111-1111-111111111111",- )- timestamp = datetime(2021, 1, 2, 0, 0, 0)- produce_replay_summary(- team_id=self.team.pk,- session_id="s2",- distinct_id="user_1",- first_timestamp=timestamp,- last_timestamp=timestamp,- )-- # Second user with strict funnel drop off, but completed the step events for a normal funnel- p2 = _create_person(distinct_ids=["user_2"], team=self.team, properties={"foo": "bar"})- _create_event(- event="$pageview",- distinct_id="user_2",- team=self.team,- timestamp=timezone.now(),- properties={"$session_id": "s3", "$window_id": "w1"},- event_uuid="51111111-1111-1111-1111-111111111111",- )- _create_event(- event="insight loaded", # Interupting event- distinct_id="user_2",- team=self.team,- timestamp=(timezone.now() + timedelta(minutes=3)),- properties={"$session_id": "s3", "$window_id": "w2"},- event_uuid="61111111-1111-1111-1111-111111111111",- )- _create_event(- event="insight analyzed",- distinct_id="user_2",- team=self.team,- timestamp=(timezone.now() + timedelta(minutes=4)),- properties={"$session_id": "s3", "$window_id": "w2"},- event_uuid="71111111-1111-1111-1111-111111111111",- )- timestamp1 = datetime(2021, 1, 2, 0, 0, 0)- produce_replay_summary(- team_id=self.team.pk,- session_id="s3",- distinct_id="user_2",- first_timestamp=timestamp1,- last_timestamp=timestamp1,- )-- # Success filter- filter = Filter(- data={- "insight": INSIGHT_FUNNELS,- "date_from": "2021-01-01",- "date_to": "2021-01-08",- "funnel_order_type": "strict",- "funnel_correlation_type": "properties",- "events": [- {"id": "$pageview", "order": 0},- {"id": "insight analyzed", "order": 1},- ],- "include_recordings": "true",- "funnel_correlation_property_values": [- {- "key": "foo",- "value": "bar",- "operator": "exact",- "type": "person",- }- ],- "funnel_correlation_person_converted": "True",- }- )- _, results, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertEqual(len(results), 1)- self.assertEqual(results[0]["id"], p1.uuid)- self.assertEqual(- results[0]["matched_recordings"],- [- {- "events": [- {- "timestamp": timezone.now() + timedelta(minutes=3),- "uuid": UUID("31111111-1111-1111-1111-111111111111"),- "window_id": "w2",- }- ],- "session_id": "s2",- }- ],- )-- # Drop off filter- filter = Filter(- data={- "insight": INSIGHT_FUNNELS,- "date_from": "2021-01-01",- "date_to": "2021-01-08",- "funnel_order_type": "strict",- "funnel_correlation_type": "properties",- "events": [- {"id": "$pageview", "order": 0},- {"id": "insight analyzed", "order": 1},- ],- "include_recordings": "true",- "funnel_correlation_property_values": [- {- "key": "foo",- "value": "bar",- "operator": "exact",- "type": "person",- }- ],- "funnel_correlation_person_converted": "False",- }- )- _, results, _ = FunnelCorrelationActors(filter, self.team).get_actors()-- self.assertEqual(results[0]["id"], p2.uuid)- self.assertEqual(- results[0]["matched_recordings"],- [- {- "events": [- {- "timestamp": timezone.now(),- "uuid": UUID("51111111-1111-1111-1111-111111111111"),- "window_id": "w1",- }- ],- "session_id": "s3",- }- ],- )diff --git a/ee/clickhouse/views/insights.py b/ee/clickhouse/views/insights.pyindex 890be1dddd18..ed5a837b1189 100644--- a/ee/clickhouse/views/insights.py+++ b/ee/clickhouse/views/insights.py@@ -1,20 +1,10 @@-from typing import Any-from rest_framework.permissions import SAFE_METHODS, BasePermissionfrom rest_framework.request import Request-from rest_framework.response import Response--from posthog.api.documentation import extend_schema-from posthog.api.utils import action-from posthog.decorators import cached_by_filters-from posthog.models.filters import Filterfrom products.dashboards.backend.models.dashboard import Dashboard-from products.product_analytics.backend.api.insight import InsightViewSet, capture_legacy_api_call+from products.product_analytics.backend.api.insight import InsightViewSetfrom products.product_analytics.backend.models.insight import Insight-from ee.clickhouse.queries.funnels.funnel_correlation import FunnelCorrelation-class CanEditInsight(BasePermission):message = "This insight is on a dashboard that can only be edited by its owner, team members invited to editing the dashboard, and project admins."@@ -28,30 +18,3 @@ class CanEditInsight(BasePermission):class EnterpriseInsightsViewSet(InsightViewSet):permission_classes = [CanEditInsight]-- # ******************************************- # /projects/:id/insights/funnel/correlation- #- # params:- # - params are the same as for funnel- #- # Returns significant events, i.e. those that are correlated with a person- # making it through a funnel- # ******************************************- @extend_schema(exclude=True)- @action(methods=["GET", "POST"], url_path="funnel/correlation", detail=False)- def funnel_correlation(self, request: Request, *args: Any, **kwargs: Any) -> Response:- capture_legacy_api_call(request, self.team)-- result = self.calculate_funnel_correlation(request)- return Response(result)-- @cached_by_filters- def calculate_funnel_correlation(self, request: Request) -> dict[str, Any]:- team = self.team- filter = Filter(request=request, team=team)-- base_uri = request.build_absolute_uri("/")- result = FunnelCorrelation(filter=filter, team=team, base_uri=base_uri).run()-- return {"result": result}diff --git a/ee/clickhouse/views/person.py b/ee/clickhouse/views/person.pyindex 03e226ae3745..23e7fc89e159 100644--- a/ee/clickhouse/views/person.py+++ b/ee/clickhouse/views/person.py@@ -1,63 +1,8 @@-from typing import Optional--from rest_framework import request, response-from posthog.api.person import PersonViewSet-from posthog.api.utils import action-from posthog.constants import FUNNEL_CORRELATION_PERSON_LIMIT, FUNNEL_CORRELATION_PERSON_OFFSET, INSIGHT_FUNNELS-from posthog.decorators import cached_by_filters-from posthog.models import Filter-from posthog.utils import format_query_params_absolute_url--from products.product_analytics.backend.api.insight import capture_legacy_api_call--from ee.clickhouse.queries.funnels.funnel_correlation_persons import FunnelCorrelationActorsclass EnterprisePersonViewSet(PersonViewSet):- @action(methods=["GET", "POST"], url_path="funnel/correlation", detail=False)- def funnel_correlation(self, request: request.Request, **kwargs) -> response.Response:- capture_legacy_api_call(request, self.team)-- if request.user.is_anonymous or not self.team:- return response.Response(data=[])-- return self._respond_with_cached_results(self.calculate_funnel_correlation_persons(request))-- @cached_by_filters- def calculate_funnel_correlation_persons(- self, request: request.Request- ) -> dict[str, tuple[list, Optional[str], Optional[str], int]]:- filter = Filter(request=request, data={"insight": INSIGHT_FUNNELS}, team=self.team)- if not filter.correlation_person_limit:- filter = filter.shallow_clone({FUNNEL_CORRELATION_PERSON_LIMIT: 100})- base_uri = request.build_absolute_uri("/")- actors, serialized_actors, raw_count = FunnelCorrelationActors(- filter=filter, team=self.team, base_uri=base_uri- ).get_actors()- _should_paginate = raw_count >= filter.correlation_person_limit-- next_url = (- format_query_params_absolute_url(- request,- filter.correlation_person_offset + filter.correlation_person_limit,- offset_alias=FUNNEL_CORRELATION_PERSON_OFFSET,- limit_alias=FUNNEL_CORRELATION_PERSON_LIMIT,- )- if _should_paginate- else None- )- initial_url = format_query_params_absolute_url(request, 0)-- # cached_function expects a dict with the key result- return {- "result": (- serialized_actors,- next_url,- initial_url,- raw_count - len(serialized_actors),- )- }+ passclass LegacyEnterprisePersonViewSet(EnterprisePersonViewSet):diff --git a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_correlation.py b/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_correlation.pydeleted file mode 100644index 6fee21a8ae94..000000000000--- a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_correlation.py+++ /dev/null@@ -1,706 +0,0 @@-import json-from datetime import datetime--import pytest-from freezegun import freeze_time-from posthog.test.base import BaseTest, _create_event, _create_person-from unittest.mock import ANY--from django.core.cache import cache--from posthog.constants import FunnelCorrelationType-from posthog.models.element import Element-from posthog.models.team import Team-from posthog.test.test_journeys import journeys_for--from ee.clickhouse.views.test.funnel.util import (- EventPattern,- FunnelCorrelationRequest,- get_funnel_correlation,- get_funnel_correlation_ok,- get_people_for_correlation_ok,-)--[email protected]_only-class FunnelCorrelationTest(BaseTest):- """- Tests for /api/projects/:project_id/funnel/correlation/- """-- CLASS_DATA_LEVEL_SETUP = False-- def test_requires_authn(self):- response = get_funnel_correlation(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(date_to="2020-04-04", events=json.dumps([])),- )- assert response.status_code == 403- assert response.json() == self.unauthenticated_response()-- def test_event_correlation_endpoint_picks_up_events_for_odds_ratios(self):- with freeze_time("2020-01-01"):- self.client.force_login(self.user)-- # Add in two people:- #- # Person 1 - a single signup event- # Person 2 - a signup event and a view insights event- #- # Both of them have a "watched video" event- #- # We then create Person 3, one successful, the other- # not. Both have not watched the video.- #- # So our contingency table for "watched video" should be- #- # | | success | failure | total |- # | ---------------- | -------- | -------- | -------- |- # | watched | 1 | 1 | 2 |- # | did not watched | 1 | 0 | 1 |- # | total | 2 | 1 | 3 |- #- # For Calculating Odds Ratio, we add a prior count of 1 to everything- #- # So our odds ratio should be- # (success + prior / failure + prior) * (failure_total - failure + prior / success_total - success + prior)- # = ( 1 + 1 / 1 + 1) * ( 1 - 1 + 1 / 2 - 1 + 1)- # = 1 / 2-- events = {- "Person 1": [- # Failure / watched- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "watched video", "timestamp": datetime(2020, 1, 2)},- ],- "Person 2": [- # Success / watched- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "watched video", "timestamp": datetime(2020, 1, 2)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- "Person 3": [- # Success / did not watched- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- }-- journeys_for(events_by_person=events, team=self.team)-- odds = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([EventPattern(id="signup"), EventPattern(id="view insights")]),- date_to="2020-04-04",- ),- )-- assert odds == {- "is_cached": False,- "last_refresh": "2020-01-01T00:00:00Z",- "result": {- "events": [- {- "event": {- "event": "watched video",- "elements": [],- "properties": {},- },- "failure_count": 1,- "success_count": 1,- "success_people_url": ANY,- "failure_people_url": ANY,- "odds_ratio": 1 / 2,- "correlation_type": "failure",- }- ],- "skewed": False,- },- "query_method": "hogql",- }-- def test_event_correlation_is_partitioned_by_team(self):- """- Ensure there's no crosstalk between teams-- We check this by:-- 1. loading events into team 1- 2. checking correlation for team 1- 3. loading events into team 2- 4. checking correlation for team 1 again, they should be the same-- """- with freeze_time("2020-01-01"):- self.client.force_login(self.user)-- events = {- "Person 1": [- {"event": "watched video", "timestamp": datetime(2019, 1, 2)},- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- ],- "Person 2": [- {"event": "watched video", "timestamp": datetime(2019, 1, 2)},- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- }-- journeys_for(events_by_person=events, team=self.team)-- odds_before = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([EventPattern(id="signup"), EventPattern(id="view insights")]),- date_to="2020-04-04",- ),- )-- other_team = create_team(organization=self.organization)- journeys_for(events_by_person=events, team=other_team)-- # We need to make sure we clear the cache so we get the same results again- cache.clear()-- odds_after = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([EventPattern(id="signup"), EventPattern(id="view insights")]),- date_to="2020-04-04",- ),- )-- assert odds_before == odds_after-- def test_event_correlation_endpoint_does_not_include_historical_events(self):- with freeze_time("2020-01-01"):- self.client.force_login(self.user)-- # Add in two people:- #- # Person 1 - a single signup event- # Person 2 - a signup event and a view insights event- #- # Both of them have a "watched video" event but they are before the- # signup event-- events = {- "Person 1": [- {"event": "watched video", "timestamp": datetime(2019, 1, 2)},- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- ],- "Person 2": [- {"event": "watched video", "timestamp": datetime(2019, 1, 2)},- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- }-- journeys_for(events_by_person=events, team=self.team)-- # We need to make sure we clear the cache other tests that have run- # done interfere with this test- cache.clear()-- odds = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([EventPattern(id="signup"), EventPattern(id="view insights")]),- date_to="2020-04-04",- ),- )-- assert odds == {- "is_cached": False,- "last_refresh": "2020-01-01T00:00:00Z",- "result": {"events": [], "skewed": False},- "query_method": "hogql",- }-- def test_event_correlation_endpoint_does_not_include_funnel_steps(self):- with freeze_time("2020-01-01"):- self.client.force_login(self.user)-- # Add Person1 with only the funnel steps involved-- events = {- "Person 1": [- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "some waypoint", "timestamp": datetime(2020, 1, 2)},- {"event": "", "timestamp": datetime(2020, 1, 3)},- ],- # We need atleast 1 success and failure to return a result- "Person 2": [- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "some waypoint", "timestamp": datetime(2020, 1, 2)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- }- # '' is a weird event name to have, but if it exists, our duty to report it-- journeys_for(events_by_person=events, team=self.team)-- # We need to make sure we clear the cache other tests that have run- # done interfere with this test- cache.clear()-- odds = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps(- [- EventPattern(id="signup"),- EventPattern(id="some waypoint"),- EventPattern(id="view insights"),- ]- ),- date_to="2020-04-04",- ),- )-- assert odds == {- "is_cached": False,- "last_refresh": "2020-01-01T00:00:00Z",- "result": {- "events": [- {- "correlation_type": "failure",- "event": {"event": "", "elements": [], "properties": {}},- "failure_count": 1,- "odds_ratio": 1 / 4,- "success_count": 0,- "success_people_url": ANY,- "failure_people_url": ANY,- }- ],- "skewed": False,- },- "query_method": "hogql",- }-- def test_events_correlation_endpoint_provides_people_drill_down_urls(self):- """- Here we are setting up three users, and looking to retrieve one- correlation for watched video, with a url we can use to retrieve people- that successfully completed the funnel AND watched the video, and- another for people that did not complete the funnel but also watched the- video.- """-- with freeze_time("2020-01-01"):- self.client.force_login(self.user)-- events = {- "Person 1": [- # Failure / watched- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "watched video", "timestamp": datetime(2020, 1, 2)},- ],- "Person 2": [- # Success / watched- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "watched video", "timestamp": datetime(2020, 1, 2)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- "Person 3": [- # Success / did not watched. We don't expect to retrieve- # this one as part of the- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- }-- journeys_for(events_by_person=events, team=self.team)-- odds = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([EventPattern(id="signup"), EventPattern(id="view insights")]),- date_to="2020-04-04",- ),- )-- assert odds["result"]["events"][0]["event"]["event"] == "watched video"- watched_video_correlation = odds["result"]["events"][0]-- assert get_people_for_correlation_ok(client=self.client, correlation=watched_video_correlation) == {- "success": ["Person 2"],- "failure": ["Person 1"],- }-- def test_events_with_properties_correlation_endpoint_provides_people_drill_down_urls(self):- with freeze_time("2020-01-01"):- self.client.force_login(self.user)-- events = {- "Person 1": [- # Failure / watched- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {- "event": "watched video",- "properties": {"$browser": "1"},- "timestamp": datetime(2020, 1, 2),- },- ],- "Person 2": [- # Success / watched- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {- "event": "watched video",- "properties": {"$browser": "1"},- "timestamp": datetime(2020, 1, 2),- },- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- "Person 3": [- # Success / watched. We need to have three event instances- # for this test otherwise the endpoint doesn't return results- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {- "event": "watched video",- "properties": {"$browser": "1"},- "timestamp": datetime(2020, 1, 2),- },- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- "Person 4": [- # Success / didn't watch. Want to use this user to verify- # that we don't pull in unrelated users erroneously- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- }-- journeys_for(events_by_person=events, team=self.team)-- odds = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- funnel_correlation_type=FunnelCorrelationType.EVENT_WITH_PROPERTIES,- funnel_correlation_event_names=json.dumps(["watched video"]),- events=json.dumps([EventPattern(id="signup"), EventPattern(id="view insights")]),- date_to="2020-04-04",- ),- )-- assert odds["result"]["events"][0]["event"]["event"] == "watched video::$browser::1"- watched_video_correlation = odds["result"]["events"][0]-- assert get_people_for_correlation_ok(client=self.client, correlation=watched_video_correlation) == {- "success": ["Person 2", "Person 3"],- "failure": ["Person 1"],- }-- def test_correlation_endpoint_with_properties(self):- self.client.force_login(self.user)-- for i in range(10):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Positive"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- for i in range(10, 20):- _create_person(- distinct_ids=[f"user_{i}"],- team_id=self.team.pk,- properties={"$browser": "Negative"},- )- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- if i % 2 == 0:- _create_event(- team=self.team,- event="negatively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )-- # We need to make sure we clear the cache other tests that have run- # done interfere with this test- cache.clear()-- api_response = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([EventPattern(id="user signed up"), EventPattern(id="paid")]),- date_to="2020-01-14",- date_from="2020-01-01",- funnel_correlation_type=FunnelCorrelationType.PROPERTIES,- funnel_correlation_names=json.dumps(["$browser"]),- ),- )-- self.assertFalse(api_response["result"]["skewed"])-- result = api_response["result"]["events"]-- odds_ratios = [item.pop("odds_ratio") for item in result]- expected_odds_ratios = [121, 1 / 121]-- for odds, expected_odds in zip(odds_ratios, expected_odds_ratios):- self.assertAlmostEqual(odds, expected_odds)-- self.assertEqual(- result,- [- {- "event": {- "event": "$browser::Positive",- "elements": [],- "properties": {},- },- "success_count": 10,- "failure_count": 0,- "success_people_url": ANY,- "failure_people_url": ANY,- # "odds_ratio": 121.0,- "correlation_type": "success",- },- {- "event": {- "event": "$browser::Negative",- "elements": [],- "properties": {},- },- "success_count": 0,- "failure_count": 10,- "success_people_url": ANY,- "failure_people_url": ANY,- # "odds_ratio": 1 / 121,- "correlation_type": "failure",- },- ],- )-- def test_properties_correlation_endpoint_provides_people_drill_down_urls(self):- """- Here we are setting up three users, two with a specified property but- differing values, and one with this property absent. We expect to be- able to use the correlation people drill down urls to retrieve the- associated people for each.- """-- with freeze_time("2020-01-01"):- self.client.force_login(self.user)-- _create_person(- distinct_ids=["Person 1"],- team_id=self.team.pk,- properties={"$browser": "1"},- )- _create_person(- distinct_ids=["Person 2"],- team_id=self.team.pk,- properties={"$browser": "1"},- )- _create_person(- distinct_ids=["Person 3"],- team_id=self.team.pk,- properties={},- )-- events = {- "Person 1": [- # Failure / $browser::1- {"event": "signup", "timestamp": datetime(2020, 1, 1)}- ],- "Person 2": [- # Success / $browser::1- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- "Person 3": [- # Success / $browser not set- {"event": "signup", "timestamp": datetime(2020, 1, 1)},- {"event": "view insights", "timestamp": datetime(2020, 1, 3)},- ],- }-- journeys_for(events_by_person=events, team=self.team, create_people=False)-- odds = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([EventPattern(id="signup"), EventPattern(id="view insights")]),- date_to="2020-04-04",- funnel_correlation_type=FunnelCorrelationType.PROPERTIES,- funnel_correlation_names=json.dumps(["$browser"]),- ),- )-- (browser_correlation,) = (- correlation- for correlation in odds["result"]["events"]- if correlation["event"]["event"] == "$browser::1"- )-- (notset_correlation,) = (- correlation for correlation in odds["result"]["events"] if correlation["event"]["event"] == "$browser::"- )-- assert get_people_for_correlation_ok(client=self.client, correlation=browser_correlation) == {- "success": ["Person 2"],- "failure": ["Person 1"],- }-- assert get_people_for_correlation_ok(client=self.client, correlation=notset_correlation) == {- "success": ["Person 3"],- "failure": [],- }-- def test_correlation_endpoint_request_with_no_steps_doesnt_fail(self):- """- This just checks that we get an empty result, this mimics what happens- with other insight endpoints. It's questionable that perhaps this whould- be a 400 instead.- """- self.client.force_login(self.user)-- with freeze_time("2020-01-01"):- response = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([]),- date_to="2020-01-14",- date_from="2020-01-01",- funnel_correlation_type=FunnelCorrelationType.PROPERTIES,- funnel_correlation_names=json.dumps(["$browser"]),- ),- )-- assert response == {- "is_cached": False,- "last_refresh": "2020-01-01T00:00:00Z",- "result": {"events": [], "skewed": False},- "query_method": "hogql",- }-- def test_funnel_correlation_with_event_properties_autocapture(self):- self.client.force_login(self.user)-- # Need a minimum of 3 hits to get a correlation result- for i in range(3):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="$autocapture",- distinct_id=f"user_{i}",- elements=[Element(nth_of_type=1, nth_child=0, tag_name="a", href="/movie")],- timestamp="2020-01-03T14:00:00Z",- properties={"signup_source": "email", "$event_type": "click"},- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- # Atleast one person that fails, to ensure we get results- _create_person(distinct_ids=[f"user_fail"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_fail",- timestamp="2020-01-02T14:00:00Z",- )-- with freeze_time("2020-01-01"):- response = get_funnel_correlation_ok(- client=self.client,- team_id=self.team.pk,- request=FunnelCorrelationRequest(- events=json.dumps([EventPattern(id="user signed up"), EventPattern(id="paid")]),- date_to="2020-01-14",- date_from="2020-01-01",- funnel_correlation_type=FunnelCorrelationType.EVENT_WITH_PROPERTIES,- funnel_correlation_event_names=json.dumps(["$autocapture"]),- ),- )-- assert response == {- "result": {- "events": [- {- "success_count": 3,- "failure_count": 0,- "success_people_url": ANY,- "failure_people_url": ANY,- "odds_ratio": 8.0,- "correlation_type": "success",- "event": {- "event": '$autocapture::elements_chain::click__~~__a:href="/movie"nth-child="0"nth-of-type="1"',- "properties": {"$event_type": "click"},- "elements": [- {- "event": None,- "text": None,- "tag_name": "a",- "attr_class": None,- "href": "/movie",- "attr_id": None,- "nth_child": 0,- "nth_of_type": 1,- "attributes": {},- "order": 0,- }- ],- },- }- ],- "skewed": False,- },- "last_refresh": "2020-01-01T00:00:00Z",- "is_cached": False,- "query_method": "hogql",- }-- assert get_people_for_correlation_ok(client=self.client, correlation=response["result"]["events"][0]) == {- "success": ["user_0", "user_1", "user_2"],- "failure": [],- }--[email protected](autouse=True)-def clear_django_cache():- cache.clear()---def create_team(organization):- return Team.objects.create(name="Test Team", organization=organization)diff --git a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py b/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.pyindex ee45bc1fa462..68d536e8bdfe 100644--- a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py+++ b/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py@@ -339,79 +339,3 @@ class TestFunnelPerson(ClickhouseTestMixin, APIBaseTest):people = j["results"][0]["people"]self.assertEqual(2, len(people))self.assertEqual(None, j["next"])---class TestFunnelCorrelationActors(ClickhouseTestMixin, APIBaseTest):- """- Tests for /api/projects/:project_id/persons/funnel/correlation/- """-- def test_pagination(self):- cache.clear()-- for i in range(10):- _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)- _create_event(- team=self.team,- event="user signed up",- distinct_id=f"user_{i}",- timestamp="2020-01-02T14:00:00Z",- )- _create_event(- team=self.team,- event="positively_related",- distinct_id=f"user_{i}",- timestamp="2020-01-03T14:00:00Z",- )- _create_event(- team=self.team,- event="paid",- distinct_id=f"user_{i}",- timestamp="2020-01-04T14:00:00Z",- )-- request_data = {- "events": json.dumps(- [- {"id": "user signed up", "type": "events", "order": 0},- {"id": "paid", "type": "events", "order": 1},- ]- ),- "insight": INSIGHT_FUNNELS,- "date_from": "2020-01-01",- "date_to": "2020-01-14",- "funnel_correlation_type": "events",- "funnel_correlation_person_converted": "true",- "funnel_correlation_person_limit": 4,- "funnel_correlation_person_entity": json.dumps({"id": "positively_related", "type": "events"}),- }-- response = self.client.get(- f"/api/projects/{self.team.pk}/persons/funnel/correlation",- data=cast(Any, request_data),- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- j = response.json()-- first_person = j["results"][0]["people"][0]- self.assertEqual(4, len(j["results"][0]["people"]))- self.assertTrue("id" in first_person and "name" in first_person and "distinct_ids" in first_person)- self.assertEqual(4, j["results"][0]["count"])-- next = j["next"]- response = self.client.get(next)- self.assertEqual(response.status_code, status.HTTP_200_OK)- j = response.json()-- people = j["results"][0]["people"]- next = j["next"]- self.assertEqual(4, len(people))- self.assertNotEqual(None, next)-- response = self.client.get(next)- self.assertEqual(response.status_code, status.HTTP_200_OK)- j = response.json()- people = j["results"][0]["people"]- next = j["next"]- self.assertEqual(2, len(people))- self.assertEqual(None, j["next"])diff --git a/ee/clickhouse/views/test/funnel/util.py b/ee/clickhouse/views/test/funnel/util.pyindex 677b833e6f8f..d82dc07e7634 100644--- a/ee/clickhouse/views/test/funnel/util.py+++ b/ee/clickhouse/views/test/funnel/util.py@@ -3,11 +3,8 @@ from typing import Any, Literal, Optional, TypedDict, Unionfrom django.test.client import Client-from posthog.constants import FunnelCorrelationTypefrom posthog.models.property import GroupTypeIndex-from ee.clickhouse.queries.funnels.funnel_correlation import EventOddsRatioSerialized-class EventPattern(TypedDict, total=False):id: str@@ -16,19 +13,6 @@ class EventPattern(TypedDict, total=False):properties: dict[str, Any]-class FunnelCorrelationRequest:- # Needs to be json encoded list of `EventPattern`s- events: str- date_to: str- funnel_step: Optional[int] = None- date_from: Optional[str] = None- funnel_correlation_type: Optional[FunnelCorrelationType] = None- # Needs to be json encoded list of `str`s- funnel_correlation_names: Optional[str] = None- funnel_correlation_event_names: Optional[str] = None--@dataclasses.dataclassclass FunnelRequest:events: str@@ -58,40 +42,3 @@ def get_funnel_ok(client: Client, team_id: int, request: FunnelRequest) -> dict[final[step["name"]] = stepreturn final---def get_funnel_correlation(client: Client, team_id: int, request: FunnelCorrelationRequest):- return client.get(- f"/api/projects/{team_id}/insights/funnel/correlation",- data={key: value for key, value in dataclasses.asdict(request).items() if value is not None},- )---def get_funnel_correlation_ok(client: Client, team_id: int, request: FunnelCorrelationRequest) -> dict[str, Any]:- response = get_funnel_correlation(client=client, team_id=team_id, request=request)-- assert response.status_code == 200, response.content- return response.json()---def get_people_for_correlation_ok(client: Client, correlation: EventOddsRatioSerialized) -> dict[str, Any]:- """- Helper for getting people for a correlation. Note we keep checking to just- inclusion of name, to make the stable to changes in other people props.- """- success_people_url = correlation["success_people_url"]- failure_people_url = correlation["failure_people_url"]-- if not success_people_url or not failure_people_url:- return {}-- success_people_response = client.get(success_people_url)- assert success_people_response.status_code == 200, success_people_response.content-- failure_people_response = client.get(failure_people_url)- assert failure_people_response.status_code == 200, failure_people_response.content-- return {- "success": sorted([person["name"] for person in success_people_response.json()["results"][0]["people"]]),- "failure": sorted([person["name"] for person in failure_people_response.json()["results"][0]["people"]]),- }diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 83b78c092191..1de529338c72 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -74,7 +74,6 @@ from posthog.queries.trends.lifecycle import Lifecyclefrom posthog.queries.trends.trends_actors import TrendsActorsfrom posthog.rate_limit import ClickHouseBurstRateThrottle, PersonalApiKeyRateThrottle, UserOrEmailRateThrottlefrom posthog.renderers import SafeJSONRenderer-from posthog.settings import EE_AVAILABLEfrom posthog.tasks.split_person import split_personfrom posthog.utils import format_query_params_absolute_url, is_anonymous_id, refresh_requested_by_client@@ -361,16 +360,7 @@ class PersonPropertiesAtTimeResponseSerializer(serializers.Serializer):def get_funnel_actor_class(filter: Filter) -> Callable:funnel_actor_class: type[ActorBaseQuery]- if filter.correlation_person_entity and EE_AVAILABLE:- if EE_AVAILABLE:- from ee.clickhouse.queries.funnels.funnel_correlation_persons import FunnelCorrelationActors-- funnel_actor_class = FunnelCorrelationActors- else:- raise ValueError(- "Funnel Correlations is not available without an enterprise license and enterprise supported deployment"- )- elif filter.funnel_viz_type == FunnelVizType.TRENDS:+ if filter.funnel_viz_type == FunnelVizType.TRENDS:funnel_actor_class = ClickhouseFunnelTrendsActorselse:if filter.funnel_order_type == "unordered":diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.tsindex d8198018ecb3..504bb4de4268 100644--- a/products/persons/frontend/generated/api.schemas.ts+++ b/products/persons/frontend/generated/api.schemas.ts@@ -596,30 +596,6 @@ export const PersonsFunnelCreateFormat = {Json: 'json',} as const-export type PersonsFunnelCorrelationRetrieveParams = {- format?: PersonsFunnelCorrelationRetrieveFormat-}--export type PersonsFunnelCorrelationRetrieveFormat =- (typeof PersonsFunnelCorrelationRetrieveFormat)[keyof typeof PersonsFunnelCorrelationRetrieveFormat]--export const PersonsFunnelCorrelationRetrieveFormat = {- Csv: 'csv',- Json: 'json',-} as const--export type PersonsFunnelCorrelationCreateParams = {- format?: PersonsFunnelCorrelationCreateFormat-}--export type PersonsFunnelCorrelationCreateFormat =- (typeof PersonsFunnelCorrelationCreateFormat)[keyof typeof PersonsFunnelCorrelationCreateFormat]--export const PersonsFunnelCorrelationCreateFormat = {- Csv: 'csv',- Json: 'json',-} as const-export type PersonsLifecycleRetrieveParams = {format?: PersonsLifecycleRetrieveFormat}diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.tsindex fa1f72f107fe..50ecf69b7f0d 100644--- a/products/persons/frontend/generated/api.ts+++ b/products/persons/frontend/generated/api.ts@@ -26,8 +26,6 @@ import type {PersonsCohortsRetrieveParams,PersonsDeletePropertyCreateParams,PersonsDeletionStatusListParams,- PersonsFunnelCorrelationCreateParams,- PersonsFunnelCorrelationRetrieveParams,PersonsFunnelCreateParams,PersonsFunnelRetrieveParams,PersonsLifecycleRetrieveParams,@@ -627,75 +625,6 @@ export const personsFunnelCreate = async (})}-export const getPersonsFunnelCorrelationRetrieveUrl = (- projectId: string,- params?: PersonsFunnelCorrelationRetrieveParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/persons/funnel/correlation/?${stringifiedParams}`- : `/api/projects/${projectId}/persons/funnel/correlation/`-}--/**- * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.- */-export const personsFunnelCorrelationRetrieve = async (- projectId: string,- params?: PersonsFunnelCorrelationRetrieveParams,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getPersonsFunnelCorrelationRetrieveUrl(projectId, params), {- ...options,- method: 'GET',- })-}--export const getPersonsFunnelCorrelationCreateUrl = (- projectId: string,- params?: PersonsFunnelCorrelationCreateParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/persons/funnel/correlation/?${stringifiedParams}`- : `/api/projects/${projectId}/persons/funnel/correlation/`-}--/**- * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.- */-export const personsFunnelCorrelationCreate = async (- projectId: string,- personRecordApi?: NonReadonly<PersonRecordApi>,- params?: PersonsFunnelCorrelationCreateParams,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getPersonsFunnelCorrelationCreateUrl(projectId, params), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(personRecordApi),- })-}-export const getPersonsLifecycleRetrieveUrl = (projectId: string, params?: PersonsLifecycleRetrieveParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/persons/frontend/generated/api.zod.ts b/products/persons/frontend/generated/api.zod.tsindex f3c5dcf71ed8..1c34487d7713 100644--- a/products/persons/frontend/generated/api.zod.ts+++ b/products/persons/frontend/generated/api.zod.ts@@ -113,16 +113,6 @@ export const PersonsFunnelCreateBody = /* @__PURE__ */ zod.object({.describe('Key-value map of person properties set via $set and $set_once operations.'),})-/**- * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.- */-export const PersonsFunnelCorrelationCreateBody = /* @__PURE__ */ zod.object({- properties: zod- .unknown()- .optional()- .describe('Key-value map of person properties set via $set and $set_once operations.'),-})-/*** Reset a distinct_id for a deleted person. This allows the distinct_id to be used again.*/diff --git a/products/persons/mcp/tools.yaml b/products/persons/mcp/tools.yamlindex 830db1f0e1e3..77b87a75b3a6 100644--- a/products/persons/mcp/tools.yaml+++ b/products/persons/mcp/tools.yaml@@ -58,12 +58,6 @@ tools:persons-deletion-status-list:operation: persons_deletion_status_listenabled: false- persons-funnel-correlation-create:- operation: persons_funnel_correlation_create- enabled: false- persons-funnel-correlation-retrieve:- operation: persons_funnel_correlation_retrieve- enabled: falsepersons-funnel-create:operation: persons_funnel_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1f52a187ab43..2b3828e7637a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -43117,30 +43117,6 @@ export namespace Schemas {Json: 'json',} as const;- export type EnvironmentsPersonsFunnelCorrelationRetrieveParams = {- format?: EnvironmentsPersonsFunnelCorrelationRetrieveFormat;- };-- export type EnvironmentsPersonsFunnelCorrelationRetrieveFormat = typeof EnvironmentsPersonsFunnelCorrelationRetrieveFormat[keyof typeof EnvironmentsPersonsFunnelCorrelationRetrieveFormat];--- export const EnvironmentsPersonsFunnelCorrelationRetrieveFormat = {- Csv: 'csv',- Json: 'json',- } as const;-- export type EnvironmentsPersonsFunnelCorrelationCreateParams = {- format?: EnvironmentsPersonsFunnelCorrelationCreateFormat;- };-- export type EnvironmentsPersonsFunnelCorrelationCreateFormat = typeof EnvironmentsPersonsFunnelCorrelationCreateFormat[keyof typeof EnvironmentsPersonsFunnelCorrelationCreateFormat];--- export const EnvironmentsPersonsFunnelCorrelationCreateFormat = {- Csv: 'csv',- Json: 'json',- } as const;-export type EnvironmentsPersonsLifecycleRetrieveParams = {format?: EnvironmentsPersonsLifecycleRetrieveFormat;};@@ -48677,30 +48653,6 @@ export namespace Schemas {Json: 'json',} as const;- export type PersonsFunnelCorrelationRetrieveParams = {- format?: PersonsFunnelCorrelationRetrieveFormat;- };-- export type PersonsFunnelCorrelationRetrieveFormat = typeof PersonsFunnelCorrelationRetrieveFormat[keyof typeof PersonsFunnelCorrelationRetrieveFormat];--- export const PersonsFunnelCorrelationRetrieveFormat = {- Csv: 'csv',- Json: 'json',- } as const;-- export type PersonsFunnelCorrelationCreateParams = {- format?: PersonsFunnelCorrelationCreateFormat;- };-- export type PersonsFunnelCorrelationCreateFormat = typeof PersonsFunnelCorrelationCreateFormat[keyof typeof PersonsFunnelCorrelationCreateFormat];--- export const PersonsFunnelCorrelationCreateFormat = {- Csv: 'csv',- Json: 'json',- } as const;-export type PersonsLifecycleRetrieveParams = {format?: PersonsLifecycleRetrieveFormat;};