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.

chore(experiments): explicit precomputation state and query context (#60785)

Anders980bfb4474bc
diff --git a/posthog/hogql_queries/experiments/experiment_query_builder.py b/posthog/hogql_queries/experiments/experiment_query_builder.py
index 1e5518ca0949..a83eed59f174 100644
--- a/posthog/hogql_queries/experiments/experiment_query_builder.py
+++ b/posthog/hogql_queries/experiments/experiment_query_builder.py
@@ -39,6 +39,10 @@ from posthog.hogql_queries.experiments.base_query_utils import (
)
from posthog.hogql_queries.experiments.breakdown_injector import BreakdownInjector
from posthog.hogql_queries.experiments.cuped_config import CupedQueryConfig
+from posthog.hogql_queries.experiments.experiment_query_context import (
+ ExperimentPrecomputationContext,
+ ExperimentQueryContext,
+)
from posthog.hogql_queries.experiments.exposure_query_logic import normalize_to_exposure_criteria
from posthog.hogql_queries.experiments.funnel_step_builder import FunnelStepBuilder
from posthog.hogql_queries.experiments.funnel_validation import FunnelDWValidator
@@ -110,16 +114,43 @@ class ExperimentQueryBuilder:
self.metric_events_preaggregation_job_ids: list[str] | None = None
self.cuped_config = cuped_config or CupedQueryConfig()
+ # Experiment-level invariants, gathered into a single frozen context for
+ # later extracted modules to consume. Additive: every self.* attribute
+ # above remains the source of truth for existing internal methods.
+ self.context = ExperimentQueryContext(
+ team=self.team,
+ feature_flag_key=self.feature_flag_key,
+ exposure_config=self.exposure_config,
+ filter_test_accounts=self.filter_test_accounts,
+ multiple_variant_handling=self.multiple_variant_handling,
+ variants=tuple(self.variants),
+ date_range_query=self.date_range_query,
+ entity_key=self.entity_key,
+ breakdowns=tuple(self.breakdowns),
+ only_count_matured_users=self.only_count_matured_users,
+ funnel_steps_data_disabled=self.funnel_steps_data_disabled,
+ cuped_config=self.cuped_config,
+ )
+
# Experiment queries group by (variant, breakdown_values), so the row count is
# bounded by num_variants × num_breakdown_values. The HogQL executor injects
# LIMIT 100 when no explicit limit is set, which silently truncates results for
# high-cardinality breakdowns. Set a generous explicit limit to prevent this.
QUERY_RESULT_LIMIT = MAX_SELECT_RETURNED_ROWS
- def build_query(self) -> ast.SelectQuery:
+ def build_query(self, precomputation_context: ExperimentPrecomputationContext | None = None) -> ast.SelectQuery:
"""
Main entry point. Returns complete query built from HogQL with placeholders.
+
+ When ``precomputation_context`` is supplied, the precomputed job IDs are
+ applied here so every internal method that reads ``self.*`` stays
+ unchanged. Job IDs can only be supplied at build time because the builder
+ itself generates the precompute queries before any job IDs exist.
"""
+ if precomputation_context is not None:
+ self.preaggregation_job_ids = precomputation_context.exposure_job_ids
+ self.metric_events_preaggregation_job_ids = precomputation_context.metric_events_job_ids
+
assert self.metric is not None, "metric is required for build_query()"
match self.metric:
case ExperimentFunnelMetric():
diff --git a/posthog/hogql_queries/experiments/experiment_query_context.py b/posthog/hogql_queries/experiments/experiment_query_context.py
new file mode 100644
index 000000000000..2c35acad154c
--- /dev/null
+++ b/posthog/hogql_queries/experiments/experiment_query_context.py
@@ -0,0 +1,45 @@
+from dataclasses import dataclass
+
+from posthog.schema import ActionsNode, Breakdown, ExperimentEventExposureConfig, MultipleVariantHandling
+
+from posthog.hogql_queries.experiments.cuped_config import CupedQueryConfig
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.models.team.team import Team
+
+
+@dataclass(frozen=True)
+class ExperimentQueryContext:
+ """Experiment-level invariants shared across query construction.
+
+ This is a transitional and organizational object: it carries the
+ experiment-scoped parameters that the builder receives at construction
+ time so future extracted modules can take a single, stable input
+ instead of threading each parameter individually.
+ """
+
+ team: Team
+ feature_flag_key: str
+ exposure_config: ExperimentEventExposureConfig | ActionsNode
+ filter_test_accounts: bool
+ multiple_variant_handling: MultipleVariantHandling
+ variants: tuple[str, ...]
+ date_range_query: QueryDateRange
+ entity_key: str
+ breakdowns: tuple[Breakdown, ...]
+ only_count_matured_users: bool
+ funnel_steps_data_disabled: bool
+ cuped_config: CupedQueryConfig
+
+
+@dataclass(frozen=True)
+class ExperimentPrecomputationContext:
+ """Explicit precomputation inputs supplied at build time.
+
+ Replaces post-construction mutation of the builder's job-id attributes.
+ The builder is needed to generate the precompute queries before any job
+ IDs exist (chicken-and-egg), so job IDs can only be supplied once they
+ are known, at the build call.
+ """
+
+ exposure_job_ids: list[str] | None = None
+ metric_events_job_ids: list[str] | None = None
diff --git a/posthog/hogql_queries/experiments/experiment_query_runner.py b/posthog/hogql_queries/experiments/experiment_query_runner.py
index b05023a8c6ff..5ffa4873aa35 100644
--- a/posthog/hogql_queries/experiments/experiment_query_runner.py
+++ b/posthog/hogql_queries/experiments/experiment_query_runner.py
@@ -38,6 +38,7 @@ from posthog.hogql_queries.experiments.experiment_query_builder import (
ExperimentQueryBuilder,
get_exposure_config_params_for_builder,
)
+from posthog.hogql_queries.experiments.experiment_query_context import ExperimentPrecomputationContext
from posthog.hogql_queries.experiments.exposure_query_logic import (
get_entity_key,
get_multiple_variant_handling_from_experiment,
@@ -338,13 +339,16 @@ class ExperimentQueryRunner(QueryRunner):
should_precompute = self._should_precompute()
+ exposure_job_ids: list[str] | None = None
+ metric_events_job_ids: list[str] | None = None
+
# Skip precomputation for data warehouse metrics because the precomputed table
# doesn't include the join keys needed to link exposures to data warehouse tables
if should_precompute and not self.is_data_warehouse_query:
try:
result = self._ensure_exposures_precomputed(builder)
if result.ready:
- builder.preaggregation_job_ids = [str(job_id) for job_id in result.job_ids]
+ exposure_job_ids = [str(job_id) for job_id in result.job_ids]
self._is_precomputed = True
else:
logger.warning("exposure_lazy_computation_not_ready", experiment_id=self.experiment.id)
@@ -374,7 +378,7 @@ class ExperimentQueryRunner(QueryRunner):
try:
metric_result = self._ensure_metric_events_precomputed(builder)
if metric_result.ready:
- builder.metric_events_preaggregation_job_ids = [str(job_id) for job_id in metric_result.job_ids]
+ metric_events_job_ids = [str(job_id) for job_id in metric_result.job_ids]
else:
logger.warning("metric_events_lazy_computation_not_ready", experiment_id=self.experiment.id)
except Exception as e:
@@ -388,7 +392,12 @@ class ExperimentQueryRunner(QueryRunner):
},
)
- return builder.build_query()
+ return builder.build_query(
+ precomputation_context=ExperimentPrecomputationContext(
+ exposure_job_ids=exposure_job_ids,
+ metric_events_job_ids=metric_events_job_ids,
+ )
+ )
def _evaluate_experiment_query(
self,