Skip to content

: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.

feat(experiments): extend metric-events precomputation to retention metrics (#78699)

Juraj Majerik36d3ccc1027c
diff --git a/posthog/clickhouse/preaggregation/experiment_metric_events_sql.py b/posthog/clickhouse/preaggregation/experiment_metric_events_sql.py
index 2526acb2829b..06aa6274196f 100644
--- a/posthog/clickhouse/preaggregation/experiment_metric_events_sql.py
+++ b/posthog/clickhouse/preaggregation/experiment_metric_events_sql.py
@@ -13,9 +13,10 @@
# - Funnel: uses `steps` array for step indicators
# - Mean: uses `numeric_value` for the computed metric value
# - Ratio: two separate jobs (numerator + denominator), both use `numeric_value`
-#
-# Retention is not supported — it uses a different query structure
-# (separate start/completion CTEs) and will need its own approach.
+# - Retention: uses `steps` with exactly two flags — steps[1] = matched the
+# start_event predicate, steps[2] = matched the completion_event predicate
+# (an event can match both). Start anchoring, the per-user retention window,
+# and the maturity gate are all computed at read time from `timestamp`.
from django.conf import settings
diff --git a/posthog/constants.py b/posthog/constants.py
index 851deb6310c7..25a743c4c4a6 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -330,6 +330,9 @@ PRODUCT_TOUR_TARGETING_FLAG_PREFIX = "product-tour-targeting-"
SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY = "subscription-ai-summary-prompt-guide"
SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY = "ai-subscriptions"
EXPERIMENTS_SYNC_QUERIES_FEATURE_FLAG_KEY = "experiments-sync-queries"
+EXPERIMENTS_RETENTION_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY = (
+ "experiments-retention-metric-events-preaggregation"
+)
GENERATED_DASHBOARD_PREFIX = "Generated Dashboard"
ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER = "Feature Viewed"
diff --git a/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md b/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md
index 48d66ddb0e8a..4066182df1af 100644
--- a/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md
+++ b/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md
@@ -266,4 +266,4 @@ GROUP BY variant
6. **Future: GROUP BY (entity_id, variant)**: Currently the query groups by entity_id only and resolves the variant during precomputation (e.g., argMin for first-seen). This bakes the variant handling strategy into the stored data, so switching between "first seen" and "exclude multiple" requires recomputation. A better approach is to GROUP BY (entity_id, variant) so we store one row per user-variant pair, then resolve multiple variants at query time.
-7. **Metric events**: The same lazy computation system also precomputes the metric_events half into `experiment_metric_events_preaggregated`, for ordered funnel metrics (one row per matching event with step indicators in `steps`) and count/sum mean metrics (one row per matching event with its value in `numeric_value`). Eligibility is gated by `_metric_events_precompute_applicable()` in `experiment_query_runner.py`; breakdowns, CUPED, and data warehouse sources fall back to a direct scan of the metric_events CTE.
+7. **Metric events**: The same lazy computation system also precomputes the metric_events half into `experiment_metric_events_preaggregated`, for ordered funnel metrics (one row per matching event with step indicators in `steps`), count/sum mean metrics (one row per matching event with its value in `numeric_value`), and retention metrics (one row per event matching the start or completion predicate, flagged as `steps[1]`/`steps[2]`; start anchoring, the retention window, and maturity stay read-time). Eligibility is gated by `_metric_events_precompute_applicable()` in `experiment_query_runner.py`; breakdowns, CUPED, and data warehouse sources fall back to a direct scan of the metric_events CTE. Retention is additionally gated behind the default-off `experiments-retention-metric-events-preaggregation` flag so it can be disabled without turning off funnel/mean. The scan extends past the experiment end by the conversion window — plus, for retention, `retention_window_end`, since a completion can land that much after a start event.
diff --git a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
index 4e78d52df0fd..c1331ac2b786 100644
--- a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
+++ b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
@@ -200,7 +200,9 @@ The exposure precomputation does NOT need this extension — exposures only occu
## Scope
-Currently implemented for **ordered funnels only**. Unordered funnels, mean, ratio, and retention metrics are not yet precomputed.
+Implemented for **ordered funnels**, **count/sum mean metrics** (per-event value stored in `numeric_value`, deduplicated on read by event identity since replayed build rows would double sums), and **retention metrics**. Unordered funnels and ratio metrics are not yet precomputed; breakdowns, CUPED, and data warehouse sources always fall back to a direct scan.
+
+Retention stores one row per event matching the start or completion predicate, with two flags in `steps` (`steps[1]` = matched start_event, `steps[2]` = matched completion_event; one event can match both). The read path swaps the two raw-events CTE sources for flag-filtered reads of the precomputed table; start anchoring (FIRST_SEEN/LAST_SEEN), the per-user retention window, the maturity gate, and the same-event exclusion all stay read-time, so they behave identically on both paths. The scan extension past the experiment end is `conversion_window + retention_window_end` rather than the conversion window alone, and retention is gated behind the default-off `experiments-retention-metric-events-preaggregation` flag (fail-safe: absent or unevaluable means direct scan) so it can be disabled independently of funnel/mean.
## Key files
diff --git a/products/experiments/backend/hogql_queries/experiment_query_builder.py b/products/experiments/backend/hogql_queries/experiment_query_builder.py
index 3614c3428adc..fd7bce8a4994 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_builder.py
@@ -703,9 +703,21 @@ class ExperimentQueryBuilder:
return self._funnel_query_builder().get_funnel_metric_events_query_for_precomputation()
case ExperimentMeanMetric():
return self._mean_query_builder().get_mean_metric_events_query_for_precomputation()
+ case ExperimentRetentionMetric():
+ return self._retention_query_builder().get_retention_metric_events_query_for_precomputation()
case _:
raise NotImplementedError(f"Metric-events precomputation is not supported for {type(self.metric)}")
+ def get_metric_events_window_extension_seconds(self) -> int:
+ """
+ How far past the experiment end date the metric-events precompute scan must
+ extend. The conversion window for funnel/mean metrics; retention adds the
+ retention window on top (completions can land that much after a start event).
+ """
+ if isinstance(self.metric, ExperimentRetentionMetric):
+ return self._retention_query_builder().get_metric_events_window_extension_seconds()
+ return self._get_conversion_window_seconds()
+
def get_funnel_metric_events_query_for_precomputation(self) -> tuple[str, dict[str, ast.Expr]]:
"""Funnel-specific write query; prefer get_metric_events_query_for_precomputation()."""
return self._funnel_query_builder().get_funnel_metric_events_query_for_precomputation()
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 2455df328bdc..e1d915bf00cf 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -36,6 +36,7 @@ from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Product, tag_queries, tags_context
+from posthog.constants import EXPERIMENTS_RETENTION_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import QueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
@@ -52,12 +53,14 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY, get_baseline_variant_key
from products.experiments.backend.hogql_queries.base_query_utils import (
+ conversion_window_to_seconds,
experiment_window,
experiment_window_end,
is_session_property_metric,
)
from products.experiments.backend.hogql_queries.cuped_config import get_cuped_config
from products.experiments.backend.hogql_queries.error_handling import experiment_error_handler
+from products.experiments.backend.hogql_queries.experiment_metric_values import get_conversion_window_seconds
from products.experiments.backend.hogql_queries.experiment_query_builder import (
ExperimentQueryBuilder,
get_exposure_config_params_for_builder,
@@ -105,6 +108,12 @@ DEFAULT_EXPOSURE_TTL_SECONDS = {
# instead of failing atomically on every attempt.
PRECOMPUTE_MAX_WINDOW_DAYS = 7
+# Upper bound on how far past the experiment end a metric-events build may scan.
+# retention_window_end is an unrestricted user-supplied integer; without a cap, a huge
+# window would stretch the precompute horizon into thousands of daily jobs before the
+# executor's timeout check. Past the cap the metric falls back to the direct scan.
+METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS = 90 * 24 * 60 * 60 # 90 days
+
def experiment_precompute_ttl_schedule(team_timezone: str) -> TtlSchedule:
"""The experiment TTL schedule with job width capped at PRECOMPUTE_MAX_WINDOW_DAYS."""
@@ -370,10 +379,13 @@ class ExperimentQueryRunner(QueryRunner):
date_from = self.experiment.start_date
date_to = experiment_window_end(self.experiment, self.as_of)
- # Extend time range by conversion window — metric events can occur after experiment end
- conversion_window_seconds = builder._get_conversion_window_seconds()
- if conversion_window_seconds > 0:
- date_to = date_to + timedelta(seconds=conversion_window_seconds)
+ # Extend time range past experiment end — metric events can occur after it: within
+ # the conversion window, plus for retention the retention window (a completion can
+ # land up to retention_window_end after a start event that itself lands up to
+ # conversion_window after the last exposure).
+ extension_seconds = builder.get_metric_events_window_extension_seconds()
+ if extension_seconds > 0:
+ date_to = date_to + timedelta(seconds=extension_seconds)
return ensure_precomputed(
team=self.team,
@@ -430,10 +442,33 @@ class ExperimentQueryRunner(QueryRunner):
return "group_aggregation"
return None # precompute was attempted; a direct path means the build failed / wasn't ready
+ def _retention_metric_events_precomputation_enabled(self) -> bool:
+ """Kill switch for retention metric-events pre-aggregation, independent of funnel/mean.
+
+ Default-off and fail-safe: returns False unless the flag is explicitly enabled, so a
+ flag-eval failure (or the flag not existing yet) leaves retention metric events on the
+ direct-scan path while funnel/mean metric events and exposures keep using their
+ precomputed tables.
+ """
+ return bool(
+ posthoganalytics.feature_enabled(
+ EXPERIMENTS_RETENTION_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY,
+ str(self.team.uuid),
+ groups={"organization": str(self.team.organization_id), "project": str(self.team.id)},
+ group_properties={
+ "organization": {"id": str(self.team.organization_id)},
+ "project": {"id": str(self.team.id), "uuid": str(self.team.uuid)},
+ },
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+
def _metric_events_precompute_applicable(self) -> bool:
"""
- Metric-events precompute supports ordered funnels and count/sum-style mean
- metrics, in both cases without breakdowns, CUPED, or data warehouse sources.
+ Metric-events precompute supports ordered funnels, count/sum-style mean
+ metrics, and retention metrics, in all cases without breakdowns, CUPED,
+ or data warehouse sources.
"""
if self._get_breakdowns_for_builder() or self.cuped_config.enabled or self.is_data_warehouse_query:
return False
@@ -450,6 +485,17 @@ class ExperimentQueryRunner(QueryRunner):
return False
math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL
return math_type in (ExperimentMetricMathType.TOTAL, ExperimentMetricMathType.SUM)
+ if isinstance(self.metric, ExperimentRetentionMetric):
+ if not isinstance(self.metric.start_event, (EventsNode, ActionsNode)) or not isinstance(
+ self.metric.completion_event, (EventsNode, ActionsNode)
+ ):
+ return False
+ extension_seconds = get_conversion_window_seconds(self.metric) + conversion_window_to_seconds(
+ self.metric.retention_window_end, self.metric.retention_window_unit
+ )
+ if extension_seconds > METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS:
+ return False
+ return self._retention_metric_events_precomputation_enabled()
return False
def _get_experiment_query(self) -> ast.SelectQuery:
diff --git a/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py b/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py
index 85513da84e3e..00ef2ef47268 100644
--- a/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py
@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING, Optional
from django.utils import timezone
from posthog.schema import (
+ ActionsNode,
+ EventsNode,
ExperimentDataWarehouseNode,
ExperimentRetentionMetric,
FunnelConversionWindowTimeUnit,
@@ -52,6 +54,78 @@ class RetentionQueryBuilder:
self._b.metric.retention_window_unit,
)
+ def get_metric_events_window_extension_seconds(self) -> int:
+ """
+ How far past the experiment end date the metric-events scan must extend.
+ A completion event can land up to retention_window_end after a start event
+ that itself lands up to conversion_window after the last exposure, so the
+ extension is the sum — unlike funnel/mean, where the conversion window alone
+ bounds it.
+ """
+ assert isinstance(self._b.metric, ExperimentRetentionMetric)
+ return self._b._get_conversion_window_seconds() + conversion_window_to_seconds(
+ self._b.metric.retention_window_end,
+ self._b.metric.retention_window_unit,
+ )
+
+ def get_retention_metric_events_query_for_precomputation(self) -> tuple[str, dict[str, ast.Expr]]:
+ """
+ Returns the SELECT query that the lazy computation system wraps in an
+ INSERT INTO experiment_metric_events_preaggregated. This is the write
+ path — it stores one row per event matching the start predicate or the
+ completion predicate, flagged via the steps array (steps[1] = matched
+ start_event, steps[2] = matched completion_event; an event can match
+ both). Start anchoring (FIRST_SEEN/LAST_SEEN), the per-user retention
+ window, and the maturity gate are all read-time concerns computed from
+ the stored timestamps.
+
+ The query uses {time_window_min} and {time_window_max} placeholders filled
+ by the lazy computation system for each daily bucket. The experiment date
+ bounds must stay named placeholders (the caller declares experiment_date_to
+ a sentinel) rather than reusing the direct-scan predicates, which bake the
+ resolved dates into the AST — a running experiment's moving window end
+ would then change the job hash and defeat cache reuse. The window extension
+ stays a placeholder too, but as a hashed constant: it derives from
+ retention_window_end, so changing the window must invalidate jobs.
+
+ Returns:
+ Tuple of (query_string, placeholders_dict)
+ """
+ assert isinstance(self._b.metric, ExperimentRetentionMetric)
+ start_event = self._b.metric.start_event
+ completion_event = self._b.metric.completion_event
+ assert isinstance(start_event, (EventsNode, ActionsNode))
+ assert isinstance(completion_event, (EventsNode, ActionsNode))
+
+ query_string = """
+ SELECT
+ {entity_key} AS entity_id,
+ timestamp AS timestamp,
+ uuid AS event_uuid,
+ `$session_id` AS session_id,
+ [
+ _toUInt8(if({start_event_filter}, 1, 0)),
+ _toUInt8(if({completion_event_filter}, 1, 0))
+ ] AS steps
+ FROM events
+ WHERE timestamp >= {time_window_min}
+ AND timestamp < {time_window_max}
+ AND timestamp >= {experiment_date_from}
+ AND timestamp < {experiment_date_to} + toIntervalSecond({window_extension_seconds})
+ AND ({start_event_filter} OR {completion_event_filter})
+ """
+
+ placeholders: dict[str, ast.Expr] = {
+ "entity_key": parse_expr(self._b.entity_key),
+ "start_event_filter": event_or_action_to_filter(self._b.team, start_event),
+ "completion_event_filter": event_or_action_to_filter(self._b.team, completion_event),
+ "experiment_date_from": self._b.date_range_query.date_from_as_hogql(),
+ "experiment_date_to": self._b.date_range_query.date_to_as_hogql(),
+ "window_extension_seconds": ast.Constant(value=self.get_metric_events_window_extension_seconds()),
+ }
+
+ return query_string, placeholders
+
def build_retention_maturity_having_clause(self) -> Optional[ast.Expr]:
"""
Returns a HAVING clause for the retention query's start_events CTE that
@@ -121,34 +195,76 @@ class RetentionQueryBuilder:
"""
assert isinstance(self._b.metric, ExperimentRetentionMetric)
+ if self._b.metric_events_preaggregation_job_ids:
+ # Read start/completion events from the precomputed table instead of scanning
+ # events; the event predicates were applied at build time and survive as the
+ # steps flags (steps[1] = matched start_event, steps[2] = matched completion_event).
+ # Time bounds must mirror the direct-scan predicates exactly — jobs can cover
+ # broader ranges than the experiment for cache reusability — so start events are
+ # bounded by the exposure window + conversion window and completions additionally
+ # by retention_window_end. Everything downstream (start anchoring, window
+ # arithmetic, maturity, same-event exclusion) is read-time and stays unchanged.
+ # No dedup of replayed build rows is needed: min/max/argMin/argMax and the
+ # MAX(0/1) outcome are all idempotent under duplicated rows, unlike mean's sums.
+ entity_id_cast = "toUUID(t.entity_id)" if self._b.entity_key == "person_id" else "t.entity_id"
+ start_events_body = f"""FROM (
+ SELECT
+ {entity_id_cast} AS entity_id,
+ t.timestamp AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE t.job_id IN {{metric_events_job_ids}}
+ AND t.team_id = {{metric_events_team_id}}
+ AND arrayElement(t.steps, 1) = 1
+ AND t.timestamp >= {{metric_events_date_from}}
+ AND t.timestamp < {{metric_events_date_to}} + toIntervalSecond({{metric_events_start_window_seconds}})
+ ) AS events
+ INNER JOIN exposures ON events.entity_id = exposures.entity_id
+ WHERE {{start_after_exposure_predicate}}"""
+ completion_events_body = f"""SELECT
+ {entity_id_cast} AS entity_id,
+ t.event_uuid AS completion_uuid,
+ t.timestamp AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE t.job_id IN {{metric_events_job_ids}}
+ AND t.team_id = {{metric_events_team_id}}
+ AND arrayElement(t.steps, 2) = 1
+ AND t.timestamp >= {{metric_events_date_from}}
+ AND t.timestamp < {{metric_events_date_to}} + toIntervalSecond({{metric_events_completion_window_seconds}})"""
+ else:
+ start_events_body = """FROM events
+ INNER JOIN exposures ON {entity_key} = exposures.entity_id
+ WHERE {start_event_predicate}
+ AND {start_after_exposure_predicate}"""
+ completion_events_body = """SELECT
+ {entity_key} AS entity_id,
+ uuid AS completion_uuid,
+ timestamp AS completion_timestamp
+ FROM events
+ WHERE {completion_event_predicate}"""
+
# Build the CTEs
- common_ctes = """
+ common_ctes = (
+ f"""
exposures AS (
- {exposure_select_query}
+ {{exposure_select_query}}
),
start_events AS (
SELECT
exposures.entity_id AS entity_id,
- {start_timestamp_expr} AS start_timestamp,
- {start_uuid_expr} AS start_uuid
- FROM events
- INNER JOIN exposures ON {entity_key} = exposures.entity_id
- WHERE {start_event_predicate}
- AND {start_after_exposure_predicate}
+ {{start_timestamp_expr}} AS start_timestamp,
+ {{start_uuid_expr}} AS start_uuid
+ {start_events_body}
GROUP BY exposures.entity_id
),
completion_events AS (
- SELECT
- {entity_key} AS entity_id,
- uuid AS completion_uuid,
- timestamp AS completion_timestamp
- FROM events
- WHERE {completion_event_predicate}
+ {completion_events_body}
),
- entity_metrics AS (
+ entity_metrics AS ("""
+ + """
SELECT
exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -174,6 +290,7 @@ class RetentionQueryBuilder:
GROUP BY exposures.entity_id, exposures.variant
)
"""
+ )
placeholders = {
"exposure_select_query": self._b._get_exposure_query(),
@@ -196,6 +313,18 @@ class RetentionQueryBuilder:
),
}
+ if self._b.metric_events_preaggregation_job_ids:
+ placeholders["metric_events_job_ids"] = ast.Constant(value=self._b.metric_events_preaggregation_job_ids)
+ placeholders["metric_events_team_id"] = ast.Constant(value=self._b.team.id)
+ placeholders["metric_events_date_from"] = self._b.date_range_query.date_from_as_hogql()
+ placeholders["metric_events_date_to"] = self._b.date_range_query.date_to_as_hogql()
+ placeholders["metric_events_start_window_seconds"] = ast.Constant(
+ value=self._b._get_conversion_window_seconds()
+ )
+ placeholders["metric_events_completion_window_seconds"] = ast.Constant(
+ value=self.get_metric_events_window_extension_seconds()
+ )
+
query = parse_select(
f"""
WITH {common_ctes}
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_retention_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_retention_metric.ambr
index cf9dfe476664..3f2949ac9d0a 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_retention_metric.ambr
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_retention_metric.ambr
@@ -103,32 +103,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'login'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -268,33 +259,24 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(259200))), equals(events.event, 'signup')), and(greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), lessOrEquals(events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(259200)))))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(259200))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE and(greaterOrEquals(events.timestamp, exposures.first_exposure_time), lessOrEquals(events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(259200))))
GROUP BY exposures.entity_id
- HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
+ HAVING ifNull(lessOrEquals(plus(min(events.timestamp), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC')), 0)),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(864000))), equals(events.event, 'login'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(864000))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -434,33 +416,24 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id
- HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
+ HAVING ifNull(lessOrEquals(plus(min(events.timestamp), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC')), 0)),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'login'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(604800))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -600,33 +573,24 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id
- HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
+ HAVING ifNull(lessOrEquals(plus(min(events.timestamp), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC')), 0)),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'login'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(604800))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -765,32 +729,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'first_action'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -1289,32 +1244,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'session_start')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'key_action'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -1453,32 +1399,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'purchase'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -1617,32 +1554,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'app_open')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'feature_used'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -1781,32 +1709,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'purchase'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -1945,32 +1864,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'action_performed')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'action_performed'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(604800))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -2109,32 +2019,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE greaterOrEquals(events.timestamp, exposures.first_exposure_time)
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(1209600))), equals(events.event, 'return_visit'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(1209600))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
@@ -2273,32 +2174,23 @@
GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp,
- argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS start_uuid
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(7200))), equals(events.event, 'signup')), and(greaterOrEquals(events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), lessOrEquals(events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(7200)))))
+ min(events.timestamp) AS start_timestamp,
+ argMin(events.uuid, events.timestamp) AS start_uuid
+ FROM
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ t.event_uuid AS uuid
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 1), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(7200))))) AS events
+ INNER JOIN exposures ON equals(events.entity_id, exposures.entity_id)
+ WHERE and(greaterOrEquals(events.timestamp, exposures.first_exposure_time), lessOrEquals(events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(7200))))
GROUP BY exposures.entity_id),
completion_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- events.uuid AS completion_uuid,
- toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(266400))), equals(events.event, 'return_visit'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ t.event_uuid AS completion_uuid,
+ toTimeZone(t.timestamp, 'UTC') AS completion_timestamp
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), ifNull(equals(arrayElement(t.steps, 2), 1), 0), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(266400))))),
entity_metrics AS
(SELECT exposures.entity_id AS entity_id,
exposures.variant AS variant,
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
index 0540dcdeb96e..28935b216e60 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
@@ -2,6 +2,7 @@ from datetime import timedelta
from pathlib import Path
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
+from unittest.mock import patch
from django.test import override_settings
from django.utils import timezone
@@ -19,7 +20,10 @@ from posthog.models.team.extensions import get_or_create_team_extension
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
from products.data_tools.backend.models.join import DataWarehouseJoin
-from products.experiments.backend.hogql_queries.experiment_query_runner import MIN_PRECOMPUTATION_DURATION_SECONDS
+from products.experiments.backend.hogql_queries.experiment_query_runner import (
+ MIN_PRECOMPUTATION_DURATION_SECONDS,
+ ExperimentQueryRunner,
+)
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -64,6 +68,16 @@ class ExperimentQueryRunnerBaseTest(ClickhouseTestMixin, APIBaseTest):
config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
config.experiment_precomputation_enabled = True
config.save()
+ # Retention metric-events pre-aggregation has an additional default-off
+ # kill-switch flag; force it on so tests still exercise the precomputed
+ # metric-events path.
+ if not getattr(self, "_retention_metric_events_precompute_patched", False):
+ patcher = patch.object(
+ ExperimentQueryRunner, "_retention_metric_events_precomputation_enabled", return_value=True
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self._retention_metric_events_precompute_patched = True
def _disable_precomputation(self):
config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py
new file mode 100644
index 000000000000..5469d22cc944
--- /dev/null
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py
@@ -0,0 +1,358 @@
+from datetime import UTC, datetime
+from typing import cast
+
+from posthog.test.base import _create_event, _create_person
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ Breakdown,
+ BreakdownFilter,
+ EventsNode,
+ ExperimentDataWarehouseNode,
+ ExperimentQuery,
+ ExperimentQueryResponse,
+ ExperimentRetentionMetric,
+ FunnelConversionWindowTimeUnit,
+ IntervalType,
+ StartHandling,
+)
+
+from posthog.clickhouse.client.execute import sync_execute
+from posthog.clickhouse.preaggregation.experiment_metric_events_sql import SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+
+from products.experiments.backend.hogql_queries.base_query_utils import experiment_window
+from products.experiments.backend.hogql_queries.experiment_query_builder import (
+ ExperimentQueryBuilder,
+ get_exposure_config_params_for_builder,
+)
+from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
+from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key
+from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
+
+DW_NODE = ExperimentDataWarehouseNode(
+ table_name="usage",
+ events_join_key="distinct_id",
+ data_warehouse_join_key="userid",
+ timestamp_field="ds",
+)
+
+
+def _retention_metric(
+ start_event: EventsNode | ExperimentDataWarehouseNode | None = None,
+ completion_event: EventsNode | ExperimentDataWarehouseNode | None = None,
+ retention_window_end: int = 7,
+ retention_window_unit: FunnelConversionWindowTimeUnit = FunnelConversionWindowTimeUnit.DAY,
+ breakdown_filter: BreakdownFilter | None = None,
+) -> ExperimentRetentionMetric:
+ return ExperimentRetentionMetric(
+ start_event=start_event or EventsNode(event="signup"),
+ completion_event=completion_event or EventsNode(event="login"),
+ retention_window_start=0,
+ retention_window_end=retention_window_end,
+ retention_window_unit=retention_window_unit,
+ start_handling=StartHandling.FIRST_SEEN,
+ breakdownFilter=breakdown_filter,
+ )
+
+
+@override_settings(IN_UNIT_TESTING=True)
+class TestExperimentRetentionMetricEventsPreaggregation(ExperimentQueryRunnerBaseTest):
+ def _build_lazy_computation_builder(
+ self, experiment, feature_flag, metric, as_of: datetime | None = None
+ ) -> ExperimentQueryBuilder:
+ exposure_config, multiple_variant_handling, filter_test_accounts = get_exposure_config_params_for_builder(
+ experiment.exposure_criteria, experiment.team, experiment.start_date
+ )
+ as_of = as_of if as_of is not None else datetime.now(UTC)
+ date_range = experiment_window(experiment, self.team, as_of)
+ return ExperimentQueryBuilder(
+ team=self.team,
+ feature_flag_key=feature_flag.key,
+ exposure_config=exposure_config,
+ filter_test_accounts=filter_test_accounts,
+ multiple_variant_handling=multiple_variant_handling,
+ variants=[v["key"] for v in feature_flag.variants],
+ date_range_query=QueryDateRange(
+ date_range=date_range,
+ team=self.team,
+ interval=IntervalType.DAY,
+ now=as_of,
+ ),
+ entity_key=get_entity_key(feature_flag.filters.get("aggregation_group_type_index")),
+ metric=metric,
+ )
+
+ def _build_runner(self, experiment, metric: ExperimentRetentionMetric, as_of: datetime | None = None):
+ query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)
+ return ExperimentQueryRunner(query=query, team=self.team, as_of=as_of)
+
+ def _create_exposure_event(self, distinct_id, feature_flag, variant, timestamp):
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties={
+ f"$feature/{feature_flag.key}": variant,
+ "$feature_flag_response": variant,
+ "$feature_flag": feature_flag.key,
+ },
+ )
+
+ def test_precomputed_result_tolerates_replayed_build_rows(self):
+ feature_flag = self.create_feature_flag(key="retention-metric-events-replay")
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 1, 10),
+ )
+ metric = _retention_metric()
+ experiment.metrics = [metric.model_dump(mode="json")]
+ experiment.save()
+
+ # Per variant: 3 exposed, 2 start, 1 completes within the window.
+ for variant in ("control", "test"):
+ for i in range(3):
+ _create_person(distinct_ids=[f"{variant}_{i}"], team_id=self.team.pk)
+ self._create_exposure_event(
+ f"{variant}_{i}", feature_flag, variant, datetime(2024, 1, 2, 12, 0, tzinfo=UTC)
+ )
+ if i < 2:
+ _create_event(
+ team=self.team,
+ event="signup",
+ distinct_id=f"{variant}_{i}",
+ timestamp=datetime(2024, 1, 3, 12, 0, tzinfo=UTC),
+ )
+ if i < 1:
+ _create_event(
+ team=self.team,
+ event="login",
+ distinct_id=f"{variant}_{i}",
+ timestamp=datetime(2024, 1, 6, 12, 0, tzinfo=UTC),
+ )
+
+ self._disable_precomputation()
+ direct_runner = self._build_runner(experiment, metric)
+ direct_result = cast(ExperimentQueryResponse, direct_runner.calculate())
+
+ # First precomputed run builds the jobs whose rows the second run will re-read.
+ self._enable_precomputation()
+ first_runner = self._build_runner(experiment, metric)
+ first_runner.calculate()
+ assert first_runner._metric_events_precomputed is True
+
+ # Simulate a replayed build INSERT: every stored metric-event row appears twice
+ # under the same job. ReplacingMergeTree only collapses these at merge time, so
+ # the retention aggregations (min/max/argMin/argMax start resolution, MAX(0/1)
+ # outcome) must stay idempotent under duplicated rows — unlike mean, no dedup
+ # CTE protects this read.
+ table = SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE()
+ rows_before = sync_execute(
+ f"SELECT count() FROM {table} WHERE team_id = %(team_id)s", {"team_id": self.team.pk}
+ )[0][0]
+ assert rows_before > 0
+ sync_execute(
+ f"INSERT INTO {table} SELECT * FROM {table} WHERE team_id = %(team_id)s",
+ {"team_id": self.team.pk},
+ )
+
+ precomputed_runner = self._build_runner(experiment, metric)
+ precomputed_result = cast(ExperimentQueryResponse, precomputed_runner.calculate())
+ assert precomputed_runner._metric_events_precomputed is True
+
+ assert direct_result.baseline is not None
+ assert precomputed_result.baseline is not None
+ assert precomputed_result.baseline.number_of_samples == direct_result.baseline.number_of_samples
+ assert precomputed_result.baseline.sum == direct_result.baseline.sum
+ assert direct_result.variant_results is not None
+ assert precomputed_result.variant_results is not None
+ assert precomputed_result.variant_results[0].sum == direct_result.variant_results[0].sum
+ assert (
+ precomputed_result.variant_results[0].number_of_samples
+ == direct_result.variant_results[0].number_of_samples
+ )
+
+ @parameterized.expand(
+ [
+ ("direct", False),
+ ("precomputed", True),
+ ]
+ )
+ def test_completion_after_experiment_end_counts_on_both_paths(self, _name, use_precomputation):
+ """
+ A completion landing after the experiment end date (but inside the retention
+ window) sits in the extension zone the build must cover: reverting the scan
+ extension to conversion-window-only would silently drop it from the
+ precomputed path while the direct scan keeps counting it. Week units also
+ exercise the non-truncated window arithmetic on the preagg read bounds.
+ """
+ self._setup_precomputation_test(use_precomputation)
+ feature_flag = self.create_feature_flag(key="retention-metric-events-extension")
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 1, 10),
+ )
+ metric = _retention_metric(retention_window_end=1, retention_window_unit=FunnelConversionWindowTimeUnit.WEEK)
+ experiment.metrics = [metric.model_dump(mode="json")]
+ experiment.save()
+ if use_precomputation:
+ self._enable_precomputation()
+ else:
+ self._disable_precomputation()
+
+ for variant in ("control", "test"):
+ # retained: starts Jan 9, completes Jan 14 — 4 days after experiment end,
+ # 5 days after start (inside the 1-week window)
+ _create_person(distinct_ids=[f"{variant}_retained"], team_id=self.team.pk)
+ self._create_exposure_event(
+ f"{variant}_retained", feature_flag, variant, datetime(2024, 1, 8, 12, 0, tzinfo=UTC)
+ )
+ _create_event(
+ team=self.team,
+ event="signup",
+ distinct_id=f"{variant}_retained",
+ timestamp=datetime(2024, 1, 9, 12, 0, tzinfo=UTC),
+ )
+ _create_event(
+ team=self.team,
+ event="login",
+ distinct_id=f"{variant}_retained",
+ timestamp=datetime(2024, 1, 14, 12, 0, tzinfo=UTC),
+ )
+ # not retained: completion 8 days after start, outside the 1-week window
+ _create_person(distinct_ids=[f"{variant}_late"], team_id=self.team.pk)
+ self._create_exposure_event(
+ f"{variant}_late", feature_flag, variant, datetime(2024, 1, 8, 12, 0, tzinfo=UTC)
+ )
+ _create_event(
+ team=self.team,
+ event="signup",
+ distinct_id=f"{variant}_late",
+ timestamp=datetime(2024, 1, 9, 12, 0, tzinfo=UTC),
+ )
+ _create_event(
+ team=self.team,
+ event="login",
+ distinct_id=f"{variant}_late",
+ timestamp=datetime(2024, 1, 17, 12, 0, tzinfo=UTC),
+ )
+
+ runner = self._build_runner(experiment, metric)
+ result = cast(ExperimentQueryResponse, runner.calculate())
+ assert runner._metric_events_precomputed is use_precomputation
+
+ assert result.baseline is not None
+ assert result.variant_results is not None
+ # 2 starters per variant, exactly 1 retained
+ assert result.baseline.number_of_samples == 2
+ assert result.baseline.sum == 1
+ assert result.variant_results[0].number_of_samples == 2
+ assert result.variant_results[0].sum == 1
+
+ @patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")
+ def test_retention_metric_events_precomputation_hash_ignores_moving_experiment_end(self, mock_sync_execute):
+ feature_flag = self.create_feature_flag(key="stable-retention-metric-events-hash")
+ # Running experiment (no end_date) so the window end follows as_of. The retention
+ # build query must keep the experiment date bounds as sentinel placeholders —
+ # resolving them into the AST (e.g. via the direct-scan predicates) would change
+ # the job hash on every load and silently defeat cache reuse.
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1),
+ end_date=None,
+ )
+ experiment.end_date = None
+ experiment.save(update_fields=["end_date"])
+ metric = _retention_metric()
+
+ first_as_of = datetime(2024, 1, 5, 12, 0, tzinfo=UTC)
+ second_as_of = datetime(2024, 1, 5, 12, 30, tzinfo=UTC)
+
+ first_result = self._build_runner(experiment, metric, as_of=first_as_of)._ensure_metric_events_precomputed(
+ self._build_lazy_computation_builder(experiment, feature_flag, metric, as_of=first_as_of)
+ )
+ second_result = self._build_runner(experiment, metric, as_of=second_as_of)._ensure_metric_events_precomputed(
+ self._build_lazy_computation_builder(experiment, feature_flag, metric, as_of=second_as_of)
+ )
+
+ assert first_result.ready is True
+ assert second_result.ready is True
+ assert first_result.job_ids == second_result.job_ids
+ assert mock_sync_execute.call_count == len(first_result.job_ids)
+
+ @patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")
+ def test_retention_metric_events_precomputation_hash_tracks_retention_window(self, mock_sync_execute):
+ feature_flag = self.create_feature_flag(key="retention-metric-events-hash-window")
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 1, 5),
+ )
+ # retention_window_end enters the build query as a hashed constant (via the
+ # window extension), not a sentinel: widening the window must invalidate the
+ # cached jobs, or reads would keep serving a scan that stops too early.
+ narrow_metric = _retention_metric(retention_window_end=7)
+ wide_metric = _retention_metric(retention_window_end=14)
+ as_of = datetime(2024, 1, 5, 12, 0, tzinfo=UTC)
+
+ first_narrow = self._build_runner(experiment, narrow_metric, as_of=as_of)._ensure_metric_events_precomputed(
+ self._build_lazy_computation_builder(experiment, feature_flag, narrow_metric, as_of=as_of)
+ )
+ second_narrow = self._build_runner(experiment, narrow_metric, as_of=as_of)._ensure_metric_events_precomputed(
+ self._build_lazy_computation_builder(experiment, feature_flag, narrow_metric, as_of=as_of)
+ )
+ wide = self._build_runner(experiment, wide_metric, as_of=as_of)._ensure_metric_events_precomputed(
+ self._build_lazy_computation_builder(experiment, feature_flag, wide_metric, as_of=as_of)
+ )
+
+ assert first_narrow.job_ids == second_narrow.job_ids
+ assert set(first_narrow.job_ids).isdisjoint(wide.job_ids)
+
+ @parameterized.expand(
+ [
+ ("events_nodes", _retention_metric(), True),
+ ("data_warehouse_start", _retention_metric(start_event=DW_NODE), False),
+ ("data_warehouse_completion", _retention_metric(completion_event=DW_NODE), False),
+ (
+ "breakdown",
+ _retention_metric(breakdown_filter=BreakdownFilter(breakdowns=[Breakdown(property="$browser")])),
+ False,
+ ),
+ # retention_window_end is an unrestricted user input; an absurd window must
+ # not stretch the precompute horizon into thousands of daily build jobs
+ ("window_beyond_precompute_horizon", _retention_metric(retention_window_end=10_000), False),
+ ]
+ )
+ def test_retention_metric_events_precompute_gate(self, _name, metric, applicable):
+ feature_flag = self.create_feature_flag(key="retention-metric-events-gate")
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 1, 10),
+ )
+
+ runner = self._build_runner(experiment, metric)
+
+ with patch.object(ExperimentQueryRunner, "_retention_metric_events_precomputation_enabled", return_value=True):
+ assert runner._metric_events_precompute_applicable() is applicable
+
+ def test_retention_metric_events_precompute_disabled_without_flag(self):
+ feature_flag = self.create_feature_flag(key="retention-metric-events-kill-switch")
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 1, 10),
+ )
+
+ runner = self._build_runner(experiment, _retention_metric())
+
+ # Fail-safe kill switch: with the flag absent/unevaluable, an otherwise
+ # eligible retention metric must stay on the direct-scan path.
+ assert runner._metric_events_precompute_applicable() is False