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): store distinct_id in precompute builds (#130763)

Juraj Majerika5aa4ec7c00b
diff --git a/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md b/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md
index 64bfd6cbeb8c..e403a86b17ab 100644
--- a/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md
+++ b/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md
@@ -270,3 +270,5 @@ GROUP BY variant
7. **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.
8. **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. 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.
+
+9. **Person merges**: A row stores the person that its event had at build time. When two persons merge after the build, the cache still holds two entities and the events scan counts one. With the `experiments-precompute-person-resolution` flag on for a team, a build of either table also stores the `distinct_id` of the event (for an exposures row, of the first exposure event). A person-aggregated read then takes the entity from the `person_id` field of the table, which joins `person_distinct_id_overrides` on that `distinct_id` and falls back to the stored person. A build with the flag on has a different query hash, so the jobs of the team are built again when the flag turns on. The flag has no effect until both tables are deletion targets in `posthog/models/deletion_targets.py`. A `distinct_id` identifies a person directly, and without a sweep a row keeps it after the person is deleted, until the row expires. The squash of person overrides into events deletes override rows, so the tables must also be squash targets. Otherwise a row whose override is deleted resolves to its stored person again.
diff --git a/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py b/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py
index 09da16d29aa9..164c7009179c 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py
@@ -663,7 +663,8 @@ class ExposureQueryBuilder:
# (UTC-day-aligned). The experiment_date_from/to placeholders tighten
# the scan to the actual experiment dates so that variant aggregation
# only considers events within the experiment.
- query_string = """
+ query_string = (
+ """
SELECT
{entity_key} AS entity_id,
{variant_expr} AS variant,
@@ -671,7 +672,9 @@ class ExposureQueryBuilder:
max(timestamp) AS last_exposure_time,
argMin(uuid, timestamp) AS exposure_event_uuid,
argMin(`$session_id`, timestamp) AS exposure_session_id,
- [] AS breakdown_value
+ [] AS breakdown_value"""
+ + self.context.precompute_distinct_id_column_sql("argMin(distinct_id, timestamp)")
+ + """
FROM events
WHERE timestamp >= {time_window_min}
AND timestamp < {time_window_max}
@@ -682,6 +685,7 @@ class ExposureQueryBuilder:
AND {variant_property} IN {variants}
GROUP BY entity_id
"""
+ )
placeholders = {
"entity_key": parse_expr(self.context.entity_key),
diff --git a/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py b/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py
index 44b042239131..cc04fe105aec 100644
--- a/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py
@@ -534,13 +534,14 @@ class FunnelQueryBuilder:
AND {funnel_steps_filter}
"""
+ distinct_id_column_sql = self._b.context.precompute_distinct_id_column_sql("distinct_id")
query_string = f"""
SELECT
{{entity_key}} AS entity_id,
timestamp AS timestamp,
uuid AS event_uuid,
`$session_id` AS session_id,
- {steps_array_sql} AS steps
+ {steps_array_sql} AS steps{distinct_id_column_sql}
FROM events
WHERE timestamp >= {{time_window_min}}
AND timestamp < {{time_window_max}}
diff --git a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py
index 12a196dc13a0..3874f6691b53 100644
--- a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py
@@ -278,6 +278,7 @@ class MeanQueryBuilder:
entity_key=self._b.entity_key,
date_range_query=self._b.date_range_query,
conversion_window_seconds=self._b._get_conversion_window_seconds(),
+ distinct_id_column_sql=self._b.context.precompute_distinct_id_column_sql("distinct_id"),
)
def build_mean_query(self) -> ast.SelectQuery:
diff --git a/products/experiments/backend/hogql_queries/experiment_query_context.py b/products/experiments/backend/hogql_queries/experiment_query_context.py
index c6a0b2df40a1..5714fc3258ad 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_context.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_context.py
@@ -32,8 +32,9 @@ class ExperimentQueryContext:
breakdowns: tuple[Breakdown, ...]
only_count_matured_users: bool
cuped_config: CupedQueryConfig
- # Whether a person-aggregated read of a preaggregated table follows person merges. The caller
- # evaluates it once per query, so that every read of the query resolves persons the same way.
+ # Whether the preaggregated tables follow person merges for a person-aggregated experiment: a
+ # build stores the distinct_id of each row, and a read resolves each row to its current person.
+ # The caller evaluates it once per query, so that every build and read of the query agree.
resolve_precomputed_persons: bool
# When set, an entity only counts as exposed once it emits this event at/after its first
# default exposure event, and that activation event's timestamp becomes the exposure time.
@@ -58,6 +59,20 @@ class ExperimentQueryContext:
return "t.entity_id"
return "t.person_id" if self.resolve_precomputed_persons else "toUUID(t.entity_id)"
+ def precompute_distinct_id_column_sql(self, distinct_id_sql: str) -> str:
+ """
+ The SELECT column that makes a build store `distinct_id_sql` as the distinct_id of each
+ row. It is written to follow the last column of a build template.
+
+ A read resolves a row to its current person through this distinct_id, so a build stores
+ it only when the read does that. Otherwise the result is empty and the template stays
+ byte for byte the same. The job hash includes the source position of each node, so a
+ template that changes matches no cached job.
+ """
+ if self.entity_key != "person_id" or not self.resolve_precomputed_persons:
+ return ""
+ return f",\n {distinct_id_sql} AS distinct_id"
+
@dataclass(frozen=True)
class ExperimentPrecomputationContext:
diff --git a/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py b/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py
index ed7328a46c27..cdd602f2f4c2 100644
--- a/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py
@@ -83,6 +83,7 @@ class RatioQueryBuilder:
entity_key=self._b.entity_key,
date_range_query=self._b.date_range_query,
conversion_window_seconds=self._b._get_conversion_window_seconds(),
+ distinct_id_column_sql=self._b.context.precompute_distinct_id_column_sql("distinct_id"),
)
def build_ratio_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 e74974142b7f..ee264774f1ff 100644
--- a/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py
@@ -100,7 +100,8 @@ class RetentionQueryBuilder:
assert isinstance(start_event, (EventsNode, ActionsNode))
assert isinstance(completion_event, (EventsNode, ActionsNode))
- query_string = """
+ query_string = (
+ """
SELECT
{entity_key} AS entity_id,
timestamp AS timestamp,
@@ -109,7 +110,9 @@ class RetentionQueryBuilder:
[
_toUInt8(if({start_event_filter}, 1, 0)),
_toUInt8(if({completion_event_filter}, 1, 0))
- ] AS steps
+ ] AS steps"""
+ + self._b.context.precompute_distinct_id_column_sql("distinct_id")
+ + """
FROM events
WHERE timestamp >= {time_window_min}
AND timestamp < {time_window_max}
@@ -117,6 +120,7 @@ class RetentionQueryBuilder:
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),
diff --git a/products/experiments/backend/hogql_queries/metric_source_precompute.py b/products/experiments/backend/hogql_queries/metric_source_precompute.py
index 6199fb09cc51..d20790c20fa8 100644
--- a/products/experiments/backend/hogql_queries/metric_source_precompute.py
+++ b/products/experiments/backend/hogql_queries/metric_source_precompute.py
@@ -27,6 +27,7 @@ def build_metric_events_precompute_query(
entity_key: str,
date_range_query: QueryDateRange,
conversion_window_seconds: int,
+ distinct_id_column_sql: str,
) -> tuple[str, dict[str, ast.Expr]]:
"""
Returns the SELECT query that the lazy computation system wraps in an
@@ -46,16 +47,23 @@ def build_metric_events_precompute_query(
a sentinel) rather than reusing build_metric_predicate(), which bakes the
resolved dates into the AST. The window end of a running experiment moves,
so baked dates would change the job hash and defeat cache reuse.
+
+ distinct_id_column_sql comes from
+ ExperimentQueryContext.precompute_distinct_id_column_sql(). It is empty, or
+ it is the column that stores the distinct_id of the event.
"""
# The job hash includes the parser source position of each node, so a change to
# this template's whitespace invalidates every cached job. Keep it byte for byte.
- query_string = """
+ query_string = (
+ """
SELECT
{entity_key} AS entity_id,
timestamp AS timestamp,
uuid AS event_uuid,
`$session_id` AS session_id,
- {value_expr} AS numeric_value
+ {value_expr} AS numeric_value"""
+ + distinct_id_column_sql
+ + """
FROM events
WHERE timestamp >= {time_window_min}
AND timestamp < {time_window_max}
@@ -63,6 +71,7 @@ def build_metric_events_precompute_query(
AND timestamp < {experiment_date_to} + toIntervalSecond({conversion_window_seconds})
AND {metric_event_filter}
"""
+ )
math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL
if math_type in (ExperimentMetricMathType.DAU, ExperimentMetricMathType.UNIQUE_SESSION):
diff --git a/products/experiments/backend/hogql_queries/precompute_policy.py b/products/experiments/backend/hogql_queries/precompute_policy.py
index 2b827aba8d80..ec8401e659d4 100644
--- a/products/experiments/backend/hogql_queries/precompute_policy.py
+++ b/products/experiments/backend/hogql_queries/precompute_policy.py
@@ -13,7 +13,10 @@ from django.db.models import Q
import posthoganalytics
from pydantic import BaseModel
+from posthog.clickhouse.preaggregation.experiment_exposures_sql import SHARDED_EXPERIMENT_EXPOSURES_TABLE
+from posthog.clickhouse.preaggregation.experiment_metric_events_sql import SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE
from posthog.constants import EXPERIMENTS_PRECOMPUTE_PERSON_RESOLUTION_FEATURE_FLAG_KEY
+from posthog.models.deletion_targets import DEFAULT_DELETION_TARGETS
from posthog.models.team.team import Team
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
@@ -70,15 +73,28 @@ PRECOMPUTE_TTL_JITTER_SECONDS = 14 * 24 * 60 * 60
METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS = 90 * 24 * 60 * 60 # 90 days
+def _person_deletion_sweeps_precomputed_tables() -> bool:
+ swept_tables = {target.data_table for target in DEFAULT_DELETION_TARGETS}
+ return {SHARDED_EXPERIMENT_EXPOSURES_TABLE(), SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE()} <= swept_tables
+
+
def precompute_person_resolution_enabled(team: Team) -> bool:
"""
- Whether a person-aggregated read of the precomputed tables resolves each row to its current
- person through `person_distinct_id_overrides`.
-
- The join aggregates all of the team's override rows on every read, and it can change only a
- row that stores its distinct_id. Off, a read takes the person stored at build time and pays
- no join. Default-off and fail-safe: an absent or unevaluable flag keeps the read without the join.
+ Whether the precomputed tables follow person merges for the team. A build stores the
+ distinct_id of each row, and a person-aggregated read resolves each row to its current person
+ through `person_distinct_id_overrides`.
+
+ A build that stores distinct_id has a different job hash, so the team's cached jobs are built
+ again when the flag turns on. The read join aggregates all of the team's override rows on
+ every read. Off, a build stores no distinct_id, and a read takes the person stored at build
+ time and pays no join. Default-off and fail-safe: an absent or unevaluable flag keeps both off.
+
+ The flag has no effect while person deletion does not sweep both precomputed tables. A
+ distinct_id identifies a person directly, and a row that no sweep reaches keeps it after the
+ person is deleted, until the row expires.
"""
+ if not _person_deletion_sweeps_precomputed_tables():
+ return False
return bool(
posthoganalytics.feature_enabled(
EXPERIMENTS_PRECOMPUTE_PERSON_RESOLUTION_FEATURE_FLAG_KEY,
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_exposure_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_exposure_preaggregation.py
index 8afe6c2e27cc..b04a47efd19a 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_exposure_preaggregation.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_exposure_preaggregation.py
@@ -36,8 +36,6 @@ from posthog.schema import (
from posthog.hogql.constants import MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY, get_default_hogql_global_settings
from posthog.clickhouse.client import sync_execute
-from posthog.clickhouse.preaggregation.experiment_exposures_sql import SHARDED_EXPERIMENT_EXPOSURES_TABLE
-from posthog.clickhouse.preaggregation.experiment_metric_events_sql import SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE
from posthog.exceptions import ClickHouseAtCapacity
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
@@ -1082,11 +1080,8 @@ class TestExperimentExposurePreaggregation(ExperimentQueryRunnerBaseTest):
experiment.metrics = [metric.model_dump(mode="json")]
experiment.save()
- distinct_id_by_person_uuid: dict[str, str] = {}
-
def create_user(distinct_id: str, variant: str | None, converts: bool) -> None:
- person = _create_person(distinct_ids=[distinct_id], team_id=self.team.pk)
- distinct_id_by_person_uuid[str(person.uuid)] = distinct_id
+ _create_person(distinct_ids=[distinct_id], team_id=self.team.pk)
if variant is not None:
self._create_exposure_event(distinct_id, feature_flag, variant, datetime(2024, 1, 2, 12, 0, tzinfo=UTC))
if converts:
@@ -1135,22 +1130,6 @@ class TestExperimentExposurePreaggregation(ExperimentQueryRunnerBaseTest):
run(use_precomputation=True)
jobs_after_build = set(PreaggregationJob.objects.values_list("id", flat=True))
- # The build does not store distinct_id, so the test sets it on the built rows.
- for table in (SHARDED_EXPERIMENT_EXPOSURES_TABLE(), SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE()):
- sync_execute(
- f"""
- ALTER TABLE {table}
- UPDATE distinct_id = transform(entity_id, %(person_uuids)s, %(distinct_ids)s, '')
- WHERE team_id = %(team_id)s
- SETTINGS mutations_sync = 2
- """,
- {
- "person_uuids": list(distinct_id_by_person_uuid.keys()),
- "distinct_ids": list(distinct_id_by_person_uuid.values()),
- "team_id": self.team.pk,
- },
- )
-
for anonymous_id, identified_id in (
("anon_exposed", "identified_converts"),
("anon_converts", "identified_exposed"),
diff --git a/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py b/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
index d631ee5ddcd9..866a32371700 100644
--- a/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
+++ b/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
@@ -9,7 +9,11 @@ from parameterized import parameterized
from posthog.schema import EventsNode, ExperimentMeanMetric, ExperimentQuery, PrecomputationMode
+from posthog.clickhouse.preaggregation.experiment_exposures_sql import SHARDED_EXPERIMENT_EXPOSURES_TABLE
+from posthog.clickhouse.preaggregation.experiment_metric_events_sql import SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE
+from posthog.models.deletion_targets import EVENTS, DeletionTarget
from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.team.team import Team
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.facade.enums import PrecomputeSkipReason
@@ -19,6 +23,7 @@ from products.experiments.backend.hogql_queries.precompute_policy import (
MIN_PRECOMPUTATION_DURATION_SECONDS,
experiment_has_min_runtime_for_precomputation,
has_uncalculated_cohorts,
+ precompute_person_resolution_enabled,
)
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
@@ -51,6 +56,36 @@ class TestPrecomputationDurationGate:
assert experiment_has_min_runtime_for_precomputation(start_date, end_date) is expected
+class TestPersonResolutionGate:
+ @parameterized.expand(
+ [
+ # name, flag_on, swept_tables, expected
+ (
+ "flag_on_both_tables_swept",
+ True,
+ (SHARDED_EXPERIMENT_EXPOSURES_TABLE(), SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE()),
+ True,
+ ),
+ ("flag_on_one_table_swept", True, (SHARDED_EXPERIMENT_EXPOSURES_TABLE(),), False),
+ ("flag_on_no_table_swept", True, (), False),
+ (
+ "flag_off_both_tables_swept",
+ False,
+ (SHARDED_EXPERIMENT_EXPOSURES_TABLE(), SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE()),
+ False,
+ ),
+ ]
+ )
+ def test_gate(self, _name, flag_on, swept_tables, expected):
+ deletion_targets = (EVENTS, *(DeletionTarget(data_table=table, read_table=table) for table in swept_tables))
+
+ with (
+ patch(f"{_POLICY_MODULE}.DEFAULT_DELETION_TARGETS", deletion_targets),
+ patch(f"{_POLICY_MODULE}.posthoganalytics.feature_enabled", return_value=flag_on),
+ ):
+ assert precompute_person_resolution_enabled(Team(id=1)) is expected
+
+
def _cohort_exposure_criteria(cohort_id: int) -> dict:
return {
"exposure_config": {