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.

fix(experiments): run scheduled metric recalcs without a request user (#116083)

Juraj Majerikf760726e8228
diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.py
index b07c5eb28a83..02611e99b39c 100644
--- a/posthog/temporal/experiments/activities.py
+++ b/posthog/temporal/experiments/activities.py
@@ -193,9 +193,9 @@ def _calculate_experiment_regular_metric_sync(
team=experiment.team,
as_of=query_to_utc,
workload=Workload.OFFLINE,
- # Scheduled recalc has no request user. Attribute the query to the experiment's creator so
- # warehouse HogQL access control is enforced.
- user=experiment.created_by,
+ # Userless background recompute. Warehouse access is enforced when the metric is authored, so
+ # resolve warehouse tables here instead of failing closed.
+ bypass_warehouse_access_control=True,
# Internal caller: keep exceptions raw so the except branches below see original types
# (StatisticError must not arrive pre-converted to ValidationError). Also silences the
# runner-level error event — this activity emits its own, on the final attempt.
@@ -483,9 +483,9 @@ def _calculate_experiment_saved_metric_sync(
team=experiment.team,
as_of=query_to_utc,
workload=Workload.OFFLINE,
- # Scheduled recalc has no request user. Attribute the query to the experiment's creator so
- # warehouse HogQL access control is enforced.
- user=experiment.created_by,
+ # Userless background recompute. Warehouse access is enforced when the metric is authored, so
+ # resolve warehouse tables here instead of failing closed.
+ bypass_warehouse_access_control=True,
# Internal caller: keep exceptions raw so the except branches below see original types
# (StatisticError must not arrive pre-converted to ValidationError). Also silences the
# runner-level error event — this activity emits its own, on the final attempt.
diff --git a/posthog/temporal/experiments/test_cache_warming.py b/posthog/temporal/experiments/test_cache_warming.py
index 455e21931f26..5b72c3a5bb59 100644
--- a/posthog/temporal/experiments/test_cache_warming.py
+++ b/posthog/temporal/experiments/test_cache_warming.py
@@ -8,17 +8,23 @@ from unittest.mock import patch
from django.core.cache import cache
from django.test import override_settings
+from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.schema import CachedExperimentQueryResponse, EventsNode, ExperimentMeanMetric, ExperimentQuery
+from posthog.constants import AvailableFeature
from posthog.hogql_queries.query_runner import ExecutionMode
+from posthog.models import PropertyDefinition
+from posthog.models.organization import OrganizationMembership
from posthog.temporal.experiments.activities import (
_calculate_experiment_regular_metric_sync,
_calculate_experiment_saved_metric_sync,
)
from posthog.temporal.experiments.models import TIMESERIES_METRIC_MAX_ATTEMPTS
+from products.access_control.backend.facade.contracts import PropertyAccessLevel
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.experiments.backend.facade.timeseries import metric_calculation_keys
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
@@ -101,22 +107,39 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):
result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])
assert result_row.query_to == expected_query_to
+ @parameterized.expand([("creator_is_member", True), ("creator_left_organization", False)])
@time_machine.travel("2020-01-10T12:00:00Z", tick=False)
- def test_temporal_activity_warms_query_cache(self):
+ def test_temporal_activity_warms_query_cache(self, _name: str, creator_is_member: bool):
"""
After the daily Temporal recalc activity runs, a frontend /query
request for the same experiment+metric should be served from cache
- instead of recomputing.
+ instead of recomputing. The activity has no request user, so it must
+ also succeed once the experiment's creator has left the organization.
"""
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
feature_flag=feature_flag,
start_date=datetime(2020, 1, 1, 0, 0, 0),
)
+ if not creator_is_member:
+ # Property access control only resolves the user's membership once the org has a rule.
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=PropertyDefinition.objects.create(
+ team=self.team, name="secret_plan", property_type="String", type=PropertyDefinition.Type.EVENT
+ ),
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).delete()
metric = ExperimentMeanMetric(uuid=str(uuid4()), source=EventsNode(event="purchase"))
metric_dict = metric.model_dump(mode="json")
experiment.metrics = [metric_dict]
+ experiment.created_by = self.user
experiment.save()
feature_flag_property = f"$feature/{feature_flag.key}"
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 55c0d7fe247a..1b968593c78f 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -4541,6 +4541,9 @@ class ExperimentService:
if not experiment.is_launched:
raise ValidationError("Cannot recalculate timeseries for experiment that hasn't started")
+ # The backfill runs this metric without a user, so the caller's warehouse access is checked here.
+ enforce_warehouse_metric_access([metric], team=self.team, user=self.user)
+
existing_recalculation = ExperimentTimeseriesRecalculation.objects.filter(
experiment=experiment,
fingerprint=fingerprint,
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index cd6818fe191a..df3a92615a38 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -7560,6 +7560,22 @@ class TestExperimentServiceWarehouseMetricAccess(APIBaseTest):
saved_metrics_ids=[{"id": saved_metric.id, "metadata": {"type": "primary"}}],
)
+ def test_requesting_timeseries_recalculation_on_restricted_table_is_denied(self):
+ # The backfill runs the submitted metric without a user, so the request itself must be denied.
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="dw-recalc",
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ experiment = Experiment.objects.create(
+ team=self.team, created_by=self.user, name="E", feature_flag=flag, start_date=timezone.now()
+ )
+ service = ExperimentService(team=self.team, user=self.user)
+ with pytest.raises(PermissionDenied):
+ service.request_timeseries_recalculation(experiment, metric=self._dw_metric(), fingerprint="fp1")
+ assert not ExperimentTimeseriesRecalculation.objects.filter(experiment=experiment).exists()
+
class TestDeprecatedFieldsInRequest(SimpleTestCase):
@parameterized.expand(
diff --git a/products/experiments/backend/timeseries_backfill.py b/products/experiments/backend/timeseries_backfill.py
index 6dfc8f5c867b..aa9989af4c4b 100644
--- a/products/experiments/backend/timeseries_backfill.py
+++ b/products/experiments/backend/timeseries_backfill.py
@@ -86,9 +86,9 @@ def backfill_experiment_timeseries(recalculation_id: str, *, backfill_until: dat
team=experiment.team,
as_of=query_to_utc,
workload=Workload.OFFLINE,
- # Scheduled backfill has no request user. Attribute the query to the experiment's creator
- # so warehouse HogQL access control is enforced.
- user=experiment.created_by,
+ # Userless background recompute. Warehouse access is enforced when the metric is authored,
+ # so resolve warehouse tables here instead of failing closed.
+ bypass_warehouse_access_control=True,
# Backfilling historical points is not user-visible pain — no terminal error event.
error_event_context=None,
)