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(demo): seed timeseries results for the File engagement boost experiment (#69160)

Juraj Majerikcbd24736f135
diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.py
index 6bdf84286d8b..3862420918c9 100644
--- a/posthog/temporal/experiments/activities.py
+++ b/posthog/temporal/experiments/activities.py
@@ -1,4 +1,4 @@
-from datetime import datetime, time, timedelta
+from datetime import datetime, timedelta
from typing import Any, Union
from zoneinfo import ZoneInfo
@@ -22,12 +22,9 @@ from posthog.temporal.experiments.models import (
ExperimentSavedMetricInput,
ExperimentSavedMetricResult,
)
-from posthog.temporal.experiments.utils import (
- DEFAULT_EXPERIMENT_RECALCULATION_HOUR,
- check_significance_transition,
- get_metric,
-)
+from posthog.temporal.experiments.utils import DEFAULT_EXPERIMENT_RECALCULATION_HOUR, check_significance_transition
+from products.experiments.backend.facade.timeseries import backfill_experiment_timeseries
from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_end
from products.experiments.backend.hogql_queries.error_handling import capture_experiment_metric_error_event
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
@@ -36,7 +33,6 @@ from products.experiments.backend.hogql_queries.utils import get_experiment_stat
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentMetricResult as ExperimentMetricResultModel,
- ExperimentTimeseriesRecalculation,
)
from products.experiments.stats.shared.statistics import StatisticError
@@ -645,120 +641,9 @@ async def calculate_experiment_saved_metric(
)
-def _backfill_experiment_metric_sync(recalculation_id: str) -> dict[str, Any]:
- close_old_connections()
-
- logger.info("Starting timeseries recalculation", recalculation_id=recalculation_id)
-
- try:
- recalculation_request = ExperimentTimeseriesRecalculation.objects.get(id=recalculation_id)
- except ExperimentTimeseriesRecalculation.DoesNotExist:
- raise ValueError(f"Recalculation request {recalculation_id} not found")
-
- if recalculation_request.status in (
- ExperimentTimeseriesRecalculation.Status.PENDING,
- ExperimentTimeseriesRecalculation.Status.FAILED,
- ):
- recalculation_request.status = ExperimentTimeseriesRecalculation.Status.IN_PROGRESS
- recalculation_request.save(update_fields=["status"])
-
- experiment = recalculation_request.experiment
- if not experiment.start_date:
- raise ValueError(f"Experiment {experiment.id} has no start_date")
-
- team_tz = ZoneInfo(experiment.team.timezone) if experiment.team.timezone else ZoneInfo("UTC")
- start_date = experiment.start_date.astimezone(team_tz).date()
-
- if experiment.end_date:
- end_date = experiment.end_date.astimezone(team_tz).date()
- else:
- end_date = datetime.now(team_tz).date()
-
- if recalculation_request.last_successful_date:
- current_date = recalculation_request.last_successful_date + timedelta(days=1)
- logger.info("Resuming recalculation", current_date=str(current_date))
- else:
- current_date = start_date
- logger.info("Starting fresh recalculation", current_date=str(current_date))
-
- metric_obj = get_metric(recalculation_request.metric)
- experiment_query = ExperimentQuery(experiment_id=experiment.id, metric=metric_obj)
- fingerprint = recalculation_request.fingerprint
-
- days_processed = 0
-
- with HeartbeaterSync(logger=logger):
- while current_date <= end_date:
- try:
- end_of_day_team_tz = datetime.combine(current_date + timedelta(days=1), time(0, 0, 0)).replace(
- tzinfo=team_tz
- )
- query_to_utc = end_of_day_team_tz.astimezone(ZoneInfo("UTC"))
-
- query_runner = ExperimentQueryRunner(
- query=experiment_query,
- 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,
- # Backfilling historical points is not user-visible pain — no terminal error event.
- error_event_context=None,
- )
- result = query_runner._calculate()
-
- ExperimentMetricResultModel.objects.update_or_create(
- experiment_id=experiment.id,
- metric_uuid=recalculation_request.metric["uuid"],
- query_to=query_to_utc,
- defaults={
- "fingerprint": fingerprint,
- "query_from": experiment.start_date,
- "status": ExperimentMetricResultModel.Status.COMPLETED,
- "result": result.model_dump(),
- "query_id": None,
- "completed_at": datetime.now(ZoneInfo("UTC")),
- "error_message": None,
- },
- )
-
- recalculation_request.last_successful_date = current_date
- recalculation_request.save(update_fields=["last_successful_date"])
- days_processed += 1
-
- except Exception:
- logger.exception(
- "Timeseries recalculation failed",
- recalculation_id=recalculation_id,
- failed_date=str(current_date),
- )
- recalculation_request.status = ExperimentTimeseriesRecalculation.Status.FAILED
- recalculation_request.save(update_fields=["status"])
- raise
-
- current_date += timedelta(days=1)
-
- recalculation_request.status = ExperimentTimeseriesRecalculation.Status.COMPLETED
- recalculation_request.save(update_fields=["status"])
-
- logger.info(
- "Timeseries recalculation completed",
- recalculation_id=recalculation_id,
- days_processed=days_processed,
- )
-
- return {
- "recalculation_id": str(recalculation_id),
- "experiment_id": experiment.id,
- "metric_uuid": recalculation_request.metric["uuid"],
- "days_processed": days_processed,
- "start_date": start_date.isoformat(),
- "end_date": end_date.isoformat(),
- }
-
-
@temporalio.activity.defn
def backfill_experiment_metric(recalculation_id: str) -> dict[str, Any]:
"""Backfill timeseries data for an experiment recalculation request."""
- return _backfill_experiment_metric_sync(recalculation_id)
+ close_old_connections()
+ with HeartbeaterSync(logger=logger):
+ return backfill_experiment_timeseries(recalculation_id)
diff --git a/products/demo/backend/logic/products/hedgebox/matrix.py b/products/demo/backend/logic/products/hedgebox/matrix.py
index 9d2d607a7973..faa0c58985c1 100644
--- a/products/demo/backend/logic/products/hedgebox/matrix.py
+++ b/products/demo/backend/logic/products/hedgebox/matrix.py
@@ -71,7 +71,15 @@ from products.event_definitions.backend.models.schema import (
SchemaPropertyGroup,
SchemaPropertyGroupProperty,
)
-from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
+from products.experiments.backend.facade.timeseries import backfill_experiment_timeseries
+from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
+from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
+from products.experiments.backend.models.experiment import (
+ Experiment,
+ ExperimentSavedMetric,
+ ExperimentTimeseriesRecalculation,
+ ExperimentToSavedMetric,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.models.insight import Insight, InsightViewed
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, get_or_create_datawarehouse_credential
@@ -1178,154 +1186,7 @@ class HedgeboxMatrix(Matrix):
metadata={"type": "secondary"},
)
- # Experiments and shared metrics
-
- # Shared metrics
- new_shared_funnel = ExperimentSavedMetric.objects.create(
- team=team,
- name="Pageview engagement",
- description="Users who have multiple pageviews in a session",
- query={
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "uuid": str(uuid.uuid4()),
- "series": [
- {"kind": "EventsNode", "event": "$pageview"},
- {"kind": "EventsNode", "event": "$pageview"},
- ],
- "goal": "increase",
- "conversion_window": 1,
- "conversion_window_unit": "day",
- },
- created_by=user,
- )
-
- new_shared_mean = ExperimentSavedMetric.objects.create(
- team=team,
- name="Files uploaded per user",
- description="Mean count of file uploads",
- query={
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": str(uuid.uuid4()),
- "source": {"kind": "EventsNode", "event": EVENT_UPLOADED_FILE},
- "goal": "increase",
- },
- created_by=user,
- )
-
- new_shared_ratio = ExperimentSavedMetric.objects.create(
- team=team,
- name="Delete-to-upload ratio",
- description="Ratio of file deletions to uploads",
- query={
- "kind": "ExperimentMetric",
- "metric_type": "ratio",
- "uuid": str(uuid.uuid4()),
- "numerator": {"kind": "EventsNode", "event": EVENT_DELETED_FILE},
- "denominator": {"kind": "EventsNode", "event": EVENT_UPLOADED_FILE},
- "goal": "increase",
- },
- created_by=user,
- )
-
- new_shared_retention = ExperimentSavedMetric.objects.create(
- team=team,
- name="7-day user retention",
- description="Users who return after 7 days",
- query={
- "kind": "ExperimentMetric",
- "metric_type": "retention",
- "uuid": str(uuid.uuid4()),
- "goal": "increase",
- "start_event": {"kind": "EventsNode", "event": "$pageview"},
- "start_handling": "first_seen",
- "completion_event": {"kind": "EventsNode", "event": "$pageview", "math": "total"},
- "retention_window_start": 1,
- "retention_window_end": 7,
- "retention_window_unit": "day",
- },
- created_by=user,
- )
-
- new_experiment_metrics_ordered_uuids = [str(uuid.uuid4()) for _ in range(4)]
-
- # New experiment with one metric of each type, configured to show as many
- # different UI states as possible
- # Primary metrics are one time metrics, secondary metrics are shared metrics
- new_experiment = Experiment.objects.create(
- team=team,
- name="File engagement boost",
- description="Testing features to increase file uploads, sharing, and overall user engagement with files.",
- feature_flag=file_engagement_flag,
- created_by=user,
- metrics=[
- {
- "kind": "ExperimentMetric",
- "metric_type": "funnel",
- "uuid": new_experiment_metrics_ordered_uuids[0],
- "name": "Upload activation",
- "series": [
- {"kind": "EventsNode", "event": "$pageview"},
- {"kind": "EventsNode", "event": EVENT_UPLOADED_FILE},
- ],
- "goal": "increase",
- "conversion_window": 7,
- "conversion_window_unit": "day",
- },
- {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "uuid": new_experiment_metrics_ordered_uuids[1],
- "name": "Active sessions per user",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- "goal": "increase",
- },
- {
- "kind": "ExperimentMetric",
- "metric_type": "ratio",
- "uuid": new_experiment_metrics_ordered_uuids[2],
- "name": "Download-to-upload ratio",
- "numerator": {"kind": "EventsNode", "event": EVENT_DOWNLOADED_FILE},
- "denominator": {"kind": "EventsNode", "event": EVENT_UPLOADED_FILE},
- "goal": "increase",
- },
- {
- "kind": "ExperimentMetric",
- "metric_type": "retention",
- "uuid": new_experiment_metrics_ordered_uuids[3],
- "name": "7-day user retention",
- "goal": "increase",
- "start_event": {"kind": "EventsNode", "event": "$pageview"},
- "start_handling": "first_seen",
- "completion_event": {"kind": "EventsNode", "event": "$pageview", "math": "total"},
- "retention_window_start": 1,
- "retention_window_end": 7,
- "retention_window_unit": "day",
- },
- ],
- primary_metrics_ordered_uuids=new_experiment_metrics_ordered_uuids,
- secondary_metrics_ordered_uuids=[
- new_shared_funnel.query["uuid"],
- new_shared_mean.query["uuid"],
- new_shared_ratio.query["uuid"],
- new_shared_retention.query["uuid"],
- ],
- parameters={
- "recommended_sample_size": int(len(self.clusters) * 0.40),
- "minimum_detectable_effect": 10,
- },
- scheduling_config={"timeseries": True},
- start_date=self.file_engagement_experiment_start,
- end_date=None,
- created_at=file_engagement_flag.created_at,
- )
-
- # Link ONLY new format shared metrics to new experiment as secondary
- for metric in [new_shared_funnel, new_shared_mean, new_shared_ratio, new_shared_retention]:
- ExperimentToSavedMetric.objects.create(
- experiment=new_experiment, saved_metric=metric, metadata={"type": "secondary"}
- )
+ self._set_up_file_engagement_experiment(team, user, file_engagement_flag)
# --- Additional experiments for coverage of various states ---
@@ -1744,6 +1605,195 @@ class HedgeboxMatrix(Matrix):
self._set_up_demo_oauth_application(team, user)
+ def _set_up_file_engagement_experiment(self, team: "Team", user: "User", flag: FeatureFlag) -> None:
+ """Create the "File engagement boost" experiment, its shared metrics, and its timeseries data.
+
+ Dates derive from the flag rather than matrix state, so this can be re-run standalone against an
+ already-seeded team (delete the experiment, then call this with the existing flag).
+ """
+ # The flag is created 2h before the experiment starts — see create_experiment_flag call sites.
+ start_date = flag.created_at + dt.timedelta(hours=2)
+
+ # Shared metrics
+ new_shared_funnel = ExperimentSavedMetric.objects.create(
+ team=team,
+ name="Pageview engagement",
+ description="Users who have multiple pageviews in a session",
+ query={
+ "kind": "ExperimentMetric",
+ "metric_type": "funnel",
+ "uuid": str(uuid.uuid4()),
+ "series": [
+ {"kind": "EventsNode", "event": "$pageview"},
+ {"kind": "EventsNode", "event": "$pageview"},
+ ],
+ "goal": "increase",
+ "conversion_window": 1,
+ "conversion_window_unit": "day",
+ },
+ created_by=user,
+ )
+
+ new_shared_mean = ExperimentSavedMetric.objects.create(
+ team=team,
+ name="Files uploaded per user",
+ description="Mean count of file uploads",
+ query={
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": str(uuid.uuid4()),
+ "source": {"kind": "EventsNode", "event": EVENT_UPLOADED_FILE},
+ "goal": "increase",
+ },
+ created_by=user,
+ )
+
+ new_shared_ratio = ExperimentSavedMetric.objects.create(
+ team=team,
+ name="Delete-to-upload ratio",
+ description="Ratio of file deletions to uploads",
+ query={
+ "kind": "ExperimentMetric",
+ "metric_type": "ratio",
+ "uuid": str(uuid.uuid4()),
+ "numerator": {"kind": "EventsNode", "event": EVENT_DELETED_FILE},
+ "denominator": {"kind": "EventsNode", "event": EVENT_UPLOADED_FILE},
+ "goal": "increase",
+ },
+ created_by=user,
+ )
+
+ new_shared_retention = ExperimentSavedMetric.objects.create(
+ team=team,
+ name="7-day user retention",
+ description="Users who return after 7 days",
+ query={
+ "kind": "ExperimentMetric",
+ "metric_type": "retention",
+ "uuid": str(uuid.uuid4()),
+ "goal": "increase",
+ "start_event": {"kind": "EventsNode", "event": "$pageview"},
+ "start_handling": "first_seen",
+ "completion_event": {"kind": "EventsNode", "event": "$pageview", "math": "total"},
+ "retention_window_start": 1,
+ "retention_window_end": 7,
+ "retention_window_unit": "day",
+ },
+ created_by=user,
+ )
+
+ new_experiment_metrics_ordered_uuids = [str(uuid.uuid4()) for _ in range(4)]
+
+ # One metric of each type, configured to show as many different UI states as possible
+ metrics: list[dict[str, Any]] = [
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "funnel",
+ "uuid": new_experiment_metrics_ordered_uuids[0],
+ "name": "Upload activation",
+ "series": [
+ {"kind": "EventsNode", "event": "$pageview"},
+ {"kind": "EventsNode", "event": EVENT_UPLOADED_FILE},
+ ],
+ "goal": "increase",
+ "conversion_window": 7,
+ "conversion_window_unit": "day",
+ },
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": new_experiment_metrics_ordered_uuids[1],
+ "name": "Active sessions per user",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ "goal": "increase",
+ },
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "ratio",
+ "uuid": new_experiment_metrics_ordered_uuids[2],
+ "name": "Download-to-upload ratio",
+ "numerator": {"kind": "EventsNode", "event": EVENT_DOWNLOADED_FILE},
+ "denominator": {"kind": "EventsNode", "event": EVENT_UPLOADED_FILE},
+ "goal": "increase",
+ },
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "retention",
+ "uuid": new_experiment_metrics_ordered_uuids[3],
+ "name": "7-day user retention",
+ "goal": "increase",
+ "start_event": {"kind": "EventsNode", "event": "$pageview"},
+ "start_handling": "first_seen",
+ "completion_event": {"kind": "EventsNode", "event": "$pageview", "math": "total"},
+ "retention_window_start": 1,
+ "retention_window_end": 7,
+ "retention_window_unit": "day",
+ },
+ ]
+
+ # New experiment; primary metrics are one time metrics, secondary metrics are shared metrics
+ new_experiment = Experiment.objects.create(
+ team=team,
+ name="File engagement boost",
+ description="Testing features to increase file uploads, sharing, and overall user engagement with files.",
+ feature_flag=flag,
+ created_by=user,
+ metrics=metrics,
+ primary_metrics_ordered_uuids=new_experiment_metrics_ordered_uuids,
+ secondary_metrics_ordered_uuids=[
+ new_shared_funnel.query["uuid"],
+ new_shared_mean.query["uuid"],
+ new_shared_ratio.query["uuid"],
+ new_shared_retention.query["uuid"],
+ ],
+ parameters={
+ "recommended_sample_size": int(len(self.clusters) * 0.40),
+ "minimum_detectable_effect": 10,
+ },
+ scheduling_config={"timeseries": True},
+ start_date=start_date,
+ end_date=None,
+ created_at=flag.created_at,
+ )
+
+ # Link ONLY new format shared metrics to new experiment as secondary
+ for metric in [new_shared_funnel, new_shared_mean, new_shared_ratio, new_shared_retention]:
+ ExperimentToSavedMetric.objects.create(
+ experiment=new_experiment, saved_metric=metric, metadata={"type": "secondary"}
+ )
+
+ # Inline metrics need stored fingerprints (normally stamped by the experiment service on
+ # create/launch) — the timeseries endpoint looks results up by them.
+ for metric_dict in metrics:
+ metric_dict["fingerprint"] = compute_metric_fingerprint(
+ metric_dict,
+ new_experiment.start_date,
+ get_experiment_stats_method(new_experiment),
+ new_experiment.exposure_criteria,
+ only_count_matured_users=new_experiment.only_count_matured_users,
+ excluded_variants=new_experiment.excluded_variants or [],
+ )
+ new_experiment.metrics = metrics
+ new_experiment.save(update_fields=["metrics"])
+
+ # Seed timeseries for the first metric so the day-by-day view has data out of the box.
+ # Skipped in tests: one ClickHouse query per experiment day is too slow for CI seeding.
+ if settings.TEST:
+ return
+ timeseries_metric = metrics[0]
+ recalculation = ExperimentTimeseriesRecalculation.objects.create(
+ team=team,
+ experiment=new_experiment,
+ metric=timeseries_metric,
+ fingerprint=timeseries_metric["fingerprint"],
+ status=ExperimentTimeseriesRecalculation.Status.PENDING,
+ )
+ try:
+ backfill_experiment_timeseries(str(recalculation.id))
+ except Exception as e:
+ # Timeseries are nice-to-have; never fail demo generation over them
+ capture_exception(e)
+
def _set_up_demo_oauth_application(self, team: "Team", user: "User") -> None:
# This app is first-party (skips OAuth consent, issues tokens scoped to all of the user's orgs) and
# ships with committed public credentials, so it must only ever exist in local dev — never in cloud
diff --git a/products/experiments/backend/facade/timeseries.py b/products/experiments/backend/facade/timeseries.py
new file mode 100644
index 000000000000..d343c5d1af66
--- /dev/null
+++ b/products/experiments/backend/facade/timeseries.py
@@ -0,0 +1,5 @@
+"""Timeseries backfill capability, re-exported for callers outside the experiments product."""
+
+from products.experiments.backend.timeseries_backfill import backfill_experiment_timeseries
+
+__all__ = ["backfill_experiment_timeseries"]
diff --git a/posthog/temporal/experiments/test_backfill.py b/products/experiments/backend/test/test_timeseries_backfill.py
similarity index 88%
rename from posthog/temporal/experiments/test_backfill.py
rename to products/experiments/backend/test/test_timeseries_backfill.py
index 5e503ba73142..700bc17a3f56 100644
--- a/posthog/temporal/experiments/test_backfill.py
+++ b/products/experiments/backend/test/test_timeseries_backfill.py
@@ -8,18 +8,18 @@ from unittest.mock import MagicMock, patch
from posthog.schema import ExperimentQueryResponse, ExperimentStatsBaseValidated, ExperimentVariantResultFrequentist
from posthog.models import Organization, Team, User
-from posthog.temporal.experiments.activities import _backfill_experiment_metric_sync
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentMetricResult,
ExperimentTimeseriesRecalculation,
)
+from products.experiments.backend.timeseries_backfill import backfill_experiment_timeseries
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@pytest.mark.django_db
-class TestBackfillExperimentMetric(BaseTest):
+class TestBackfillExperimentTimeseries(BaseTest):
def test_backfill_processes_all_days_and_creates_correct_records(self):
org = Organization.objects.create(name="Test Org")
team = Team.objects.create(organization=org, name="Test Team", timezone="America/New_York")
@@ -56,16 +56,12 @@ class TestBackfillExperimentMetric(BaseTest):
],
)
- with (
- patch("posthog.temporal.experiments.activities.close_old_connections"),
- patch("posthog.temporal.experiments.activities.HeartbeaterSync"),
- patch("posthog.temporal.experiments.activities.ExperimentQueryRunner") as mock_query_runner_class,
- ):
+ with patch("products.experiments.backend.timeseries_backfill.ExperimentQueryRunner") as mock_query_runner_class:
mock_query_runner = MagicMock()
mock_query_runner._calculate.return_value = mock_result
mock_query_runner_class.return_value = mock_query_runner
- result = _backfill_experiment_metric_sync(str(recalculation_request.id))
+ result = backfill_experiment_timeseries(str(recalculation_request.id))
recalculation_request.refresh_from_db()
assert recalculation_request.status == ExperimentTimeseriesRecalculation.Status.COMPLETED
diff --git a/products/experiments/backend/timeseries_backfill.py b/products/experiments/backend/timeseries_backfill.py
new file mode 100644
index 000000000000..99dd4f6bc77a
--- /dev/null
+++ b/products/experiments/backend/timeseries_backfill.py
@@ -0,0 +1,133 @@
+"""Day-by-day timeseries backfill for experiment metrics.
+
+Computes one ExperimentMetricResult row per experiment day by running the experiment
+query with as_of pinned to each day's end. Normally invoked via the Temporal
+`experiment-timeseries-recalculation-workflow` activity, but has no Temporal
+dependencies, so it can also run in-process (e.g. from demo data seeding).
+"""
+
+from datetime import datetime, time, timedelta
+from typing import Any
+from zoneinfo import ZoneInfo
+
+import structlog
+
+from posthog.schema import ExperimentQuery
+
+from posthog.clickhouse.client.connection import Workload
+
+from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
+from products.experiments.backend.models.experiment import ExperimentMetricResult, ExperimentTimeseriesRecalculation
+from products.experiments.backend.temporal.metric_resolution import build_metric
+
+logger = structlog.get_logger(__name__)
+
+
+def backfill_experiment_timeseries(recalculation_id: str) -> dict[str, Any]:
+ logger.info("Starting timeseries recalculation", recalculation_id=recalculation_id)
+
+ try:
+ recalculation_request = ExperimentTimeseriesRecalculation.objects.get(id=recalculation_id)
+ except ExperimentTimeseriesRecalculation.DoesNotExist:
+ raise ValueError(f"Recalculation request {recalculation_id} not found")
+
+ if recalculation_request.status in (
+ ExperimentTimeseriesRecalculation.Status.PENDING,
+ ExperimentTimeseriesRecalculation.Status.FAILED,
+ ):
+ recalculation_request.status = ExperimentTimeseriesRecalculation.Status.IN_PROGRESS
+ recalculation_request.save(update_fields=["status"])
+
+ experiment = recalculation_request.experiment
+ if not experiment.start_date:
+ raise ValueError(f"Experiment {experiment.id} has no start_date")
+
+ team_tz = ZoneInfo(experiment.team.timezone) if experiment.team.timezone else ZoneInfo("UTC")
+ start_date = experiment.start_date.astimezone(team_tz).date()
+
+ if experiment.end_date:
+ end_date = experiment.end_date.astimezone(team_tz).date()
+ else:
+ end_date = datetime.now(team_tz).date()
+
+ if recalculation_request.last_successful_date:
+ current_date = recalculation_request.last_successful_date + timedelta(days=1)
+ logger.info("Resuming recalculation", current_date=str(current_date))
+ else:
+ current_date = start_date
+ logger.info("Starting fresh recalculation", current_date=str(current_date))
+
+ metric_obj = build_metric(recalculation_request.metric)
+ experiment_query = ExperimentQuery(experiment_id=experiment.id, metric=metric_obj)
+ fingerprint = recalculation_request.fingerprint
+
+ days_processed = 0
+
+ while current_date <= end_date:
+ try:
+ end_of_day_team_tz = datetime.combine(current_date + timedelta(days=1), time(0, 0, 0)).replace(
+ tzinfo=team_tz
+ )
+ query_to_utc = end_of_day_team_tz.astimezone(ZoneInfo("UTC"))
+
+ query_runner = ExperimentQueryRunner(
+ query=experiment_query,
+ 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,
+ # Backfilling historical points is not user-visible pain — no terminal error event.
+ error_event_context=None,
+ )
+ result = query_runner._calculate()
+
+ ExperimentMetricResult.objects.update_or_create(
+ experiment_id=experiment.id,
+ metric_uuid=recalculation_request.metric["uuid"],
+ query_to=query_to_utc,
+ defaults={
+ "fingerprint": fingerprint,
+ "query_from": experiment.start_date,
+ "status": ExperimentMetricResult.Status.COMPLETED,
+ "result": result.model_dump(),
+ "query_id": None,
+ "completed_at": datetime.now(ZoneInfo("UTC")),
+ "error_message": None,
+ },
+ )
+
+ recalculation_request.last_successful_date = current_date
+ recalculation_request.save(update_fields=["last_successful_date"])
+ days_processed += 1
+
+ except Exception:
+ logger.exception(
+ "Timeseries recalculation failed",
+ recalculation_id=recalculation_id,
+ failed_date=str(current_date),
+ )
+ recalculation_request.status = ExperimentTimeseriesRecalculation.Status.FAILED
+ recalculation_request.save(update_fields=["status"])
+ raise
+
+ current_date += timedelta(days=1)
+
+ recalculation_request.status = ExperimentTimeseriesRecalculation.Status.COMPLETED
+ recalculation_request.save(update_fields=["status"])
+
+ logger.info(
+ "Timeseries recalculation completed",
+ recalculation_id=recalculation_id,
+ days_processed=days_processed,
+ )
+
+ return {
+ "recalculation_id": str(recalculation_id),
+ "experiment_id": experiment.id,
+ "metric_uuid": recalculation_request.metric["uuid"],
+ "days_processed": days_processed,
+ "start_date": start_date.isoformat(),
+ "end_date": end_date.isoformat(),
+ }