: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(experiments): count every health wait from the real launch (#129160)
Marcel Poelker21cee3ae7897
diff --git a/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsxindex a4a16a27b328..dcc2105864be 100644--- a/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx@@ -94,7 +94,7 @@ const HEALTH_INPUTS: ExperimentHealthInputsApi = {flag_history: {checked: true,not_checked_reason: null,- launched_at: '2025-01-06T10:00:00Z',+ start_date: '2025-01-06T10:00:00Z',team_timezone: 'UTC',changes: [{diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 663d92fffb69..b8d0cef16835 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -742,6 +742,7 @@'get_type_display','holdout_id','hours_since_launch',+ 'hours_since_start','id','is_draft','is_exposure_frozen',@@ -749,6 +750,7 @@'is_paused','is_running','is_stopped',+ 'launched_at','repository','save','start_date',diff --git a/products/experiments/backend/health/checks/change_wording.py b/products/experiments/backend/health/checks/change_wording.pyindex 4ab228fe1454..ecdce7f15bd9 100644--- a/products/experiments/backend/health/checks/change_wording.py+++ b/products/experiments/backend/health/checks/change_wording.py@@ -22,15 +22,15 @@ def suggested_start(changed_at: datetime, team_timezone: str) -> str:def delay(- *, launched_at: datetime, first_changed_at: datetime, exposed_before_first: bool | None, change_count: int+ *, start_date: datetime, first_changed_at: datetime, exposed_before_first: bool | None, change_count: int) -> list[str]:- # When nobody knows whether anyone was exposed before the change, or the change came days after launch,- # the time since launch tells the reader how many people the change can have moved.- seconds = (first_changed_at - launched_at).total_seconds()+ # When nobody knows whether anyone was exposed before the change, or the change came days after the start date,+ # the time since the start date tells the reader how many people the change can have moved.+ seconds = (first_changed_at - start_date).total_seconds()if exposed_before_first is not None and seconds <= SECONDS_PER_DAY:return []change = "The change" if change_count == 1 else "The first change"- return [f"{change} came {duration(seconds)} after launch."]+ return [f"{change} came {duration(seconds)} after the start date."]def the_change(change_count: int, determiner: Literal["the", "this"]) -> str:@@ -52,7 +52,7 @@ def not_checked_because(reason: FlagHistoryNotCheckedReason) -> str:case FlagHistoryNotCheckedReason.NO_HISTORY_ACCESS:return "you can't view the linked feature flag's history"case FlagHistoryNotCheckedReason.TOO_MANY_SAVES:- return f"the flag was saved more than {MAX_FLAG_SAVES} times since launch"+ return f"the flag was saved more than {MAX_FLAG_SAVES} times since the start date"case FlagHistoryNotCheckedReason.TOO_MANY_CONDITIONS:return f"the flag has more than {MAX_RELEASE_CONDITIONS} release conditions"diff --git a/products/experiments/backend/health/checks/flag_change_findings.py b/products/experiments/backend/health/checks/flag_change_findings.pyindex 6aa606817725..a6bf62faa8a4 100644--- a/products/experiments/backend/health/checks/flag_change_findings.py+++ b/products/experiments/backend/health/checks/flag_change_findings.py@@ -169,9 +169,9 @@ def few_exposed_units(history: FlagHistory, kind: ExperimentHealthFlagChangeKinddef exposed_when(history: FlagHistory, effect: ChangeEffect, count: int) -> str:- after_launch = duration((effect.last.changed_at - history.launched_at).total_seconds())+ after_start = duration((effect.last.changed_at - history.start_date).total_seconds())change = "The change" if effect.change_count == 1 else "The last change"- return f"{change} came {after_launch} after launch, when {_units(count, history.counts_groups)} had been exposed."+ return f"{change} came {after_start} after the start date, when {_units(count, history.counts_groups)} had been exposed."def leave_out(history: FlagHistory, effect: ChangeEffect, count: int) -> list[str]:@@ -234,13 +234,13 @@ def change_evidence("last_changed_at": effect.last.changed_at.astimezone(UTC).isoformat(),**kind_evidence,"exposed_before_change": exposed_before_change,- "seconds_after_launch": int((effect.first.changed_at - history.launched_at).total_seconds()),+ "seconds_after_start": int((effect.first.changed_at - history.start_date).total_seconds()),}def delay_after_launch(history: FlagHistory, effect: ChangeEffect) -> list[str]:return delay(- launched_at=history.launched_at,+ start_date=history.start_date,first_changed_at=effect.first.changed_at,exposed_before_first=history.exposed_before_first,change_count=effect.change_count,diff --git a/products/experiments/backend/health/checks/flag_state.py b/products/experiments/backend/health/checks/flag_state.pyindex f95323ff12cb..e2c125fedde4 100644--- a/products/experiments/backend/health/checks/flag_state.py+++ b/products/experiments/backend/health/checks/flag_state.py@@ -215,7 +215,7 @@ def _flag_disabled(pause: PauseHistory | None, *, running_others: int) -> Experi"conclusion."),)- if pause is not None and pause.launched_at >= PAUSE_ENTRIES_SINCE:+ if pause is not None and pause.start_date >= PAUSE_ENTRIES_SINCE:return _finding(code=ExperimentHealthFindingCode.FLAG_OFF_WHILE_RUNNING,subcode=RUNNING_BUT_FLAG_DISABLED,@@ -298,7 +298,7 @@ def _live_after_end(ctx: HealthContext, ended_at: datetime) -> ExperimentHealthFdef _serves_later_experiment(other: ExperimentOnFlag, ended_at: datetime) -> bool:- return other.launched_at is not None and (other.ended_at is None or other.launched_at > ended_at)+ return other.start_date is not None and (other.ended_at is None or other.start_date > ended_at)def _shared_with_draft(ended_at: datetime, team_timezone: str) -> ExperimentHealthFinding:diff --git a/products/experiments/backend/health/condition_set_traffic.py b/products/experiments/backend/health/condition_set_traffic.pyindex 52dc91b757eb..bc15ffdebfd3 100644--- a/products/experiments/backend/health/condition_set_traffic.py+++ b/products/experiments/backend/health/condition_set_traffic.py@@ -234,10 +234,10 @@ def _reads_exposure_copies(organization_id: UUID) -> bool:def _load_condition_set_traffic(experiment: Experiment, ctx: HealthContext) -> ConditionSetTraffic | None:- launched_at = experiment.start_date- if launched_at is None or experiment.feature_flag.version is None:+ start_date = experiment.start_date+ if start_date is None or experiment.feature_flag.version is None:return None- cache_key = _cache_key(experiment, launched_at)+ cache_key = _cache_key(experiment, start_date)hit, traffic = _cached(cache_key)if hit:return traffic@@ -249,15 +249,15 @@ def _load_condition_set_traffic(experiment: Experiment, ctx: HealthContext) -> Chit, traffic = _cached(cache_key)if hit:return traffic- return _scan(experiment, ctx, cache_key, launched_at)+ return _scan(experiment, ctx, cache_key, start_date)def _scan(- experiment: Experiment, ctx: HealthContext, cache_key: str, launched_at: datetime+ experiment: Experiment, ctx: HealthContext, cache_key: str, start_date: datetime) -> ConditionSetTraffic | None:flag = experiment.feature_flagnow = timezone.now()- window_start = max(launched_at, flag.updated_at or launched_at, now - TRAFFIC_WINDOW)+ window_start = max(start_date, flag.updated_at or start_date, now - TRAFFIC_WINDOW)try:traffic = query_condition_set_traffic(experiment, window_start=window_start, window_end=now)except Exception as error:@@ -289,13 +289,13 @@ def _wait_for_scan(cache_key: str) -> ConditionSetTraffic | None:return None-def _cache_key(experiment: Experiment, launched_at: datetime) -> str:+def _cache_key(experiment: Experiment, start_date: datetime) -> str:flag = experiment.feature_flag# Every input of the query except the end of the window, which moves with the clock.inputs = json.dumps([_ANSWER_SHAPE,- launched_at.isoformat(),+ start_date.isoformat(),flag.key,flag.version,flag.updated_at.isoformat() if flag.updated_at else None,diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.pyindex eb3446afc093..d0df4d54d7fc 100644--- a/products/experiments/backend/health/context.py+++ b/products/experiments/backend/health/context.py@@ -89,7 +89,9 @@ class FlagHistory:"""The changes of the flag after launch that can have moved exposed people, and whether anyone was exposedbefore them. A change before the first exposure moved nobody, so it does not count."""- launched_at: datetime+ # The experiment's start date, which can lie before its launch. The results count exposures from it, so the history+ # and its exposure windows start there too.+ start_date: datetimeteam_timezone: str# Every change of every kind, in time order.changes: tuple[FlagChange, ...]@@ -146,7 +148,7 @@ class FlagHistoryNotChecked:"""A flag history that was not compared with the exposures, and the reason. Every change counts."""reason: FlagHistoryNotCheckedReason- launched_at: datetime+ start_date: datetimeteam_timezone: str# Every change since launch, in time order. Empty for NO_HISTORY_ACCESS, which does not read them.changes: tuple[FlagChange, ...]@@ -221,7 +223,7 @@ class PauseHistory:write these entries, from the page, the API or MCP. A flag disabled or enabled anywhere else, such as on the flagpage, writes none."""- launched_at: datetime+ start_date: datetimeteam_timezone: str# The time of the latest entry when it is a pause. None when it is a resume, or the experiment has no entry.paused_at: datetime | None@@ -233,17 +235,17 @@ class ExperimentOnFlag:flag, so the flag's state can belong to one of them. It has no name or id, because the reader of this experimentmay have no access to the other one."""- launched_at: datetime | None+ start_date: datetime | Noneended_at: datetime | Nonearchived: bool@propertydef is_draft(self) -> bool:- return self.launched_at is None+ return self.start_date is None@propertydef is_running(self) -> bool:- return self.launched_at is not None and self.ended_at is None+ return self.start_date is not None and self.ended_at is None@frozen@@ -817,7 +819,7 @@ def _other_experiments_on_flag(experiment: Experiment) -> tuple[ExperimentOnFlag.values_list("start_date", "end_date", "archived", named=True))return tuple(- ExperimentOnFlag(launched_at=other.start_date, ended_at=other.end_date, archived=other.archived)+ ExperimentOnFlag(start_date=other.start_date, ended_at=other.end_date, archived=other.archived)for other in others)@@ -1100,6 +1102,7 @@ def load_health_context(exposures: ExposureTotals | None = None,*,flag_history: FlagHistory | FlagHistoryNotChecked | None = None,+ can_read_flag_history: bool = False,) -> HealthContext:links = saved_metric_links(experiment)shared_metric_roles = [saved_metric_link_role(link) for link in links]@@ -1127,7 +1130,7 @@ def load_health_context(baseline_variant_key=_configured_baseline_variant_key(experiment.stats_config),primary_metric_count=len(experiment.metrics or []) + shared_metric_roles.count("primary"),secondary_metric_count=len(experiment.metrics_secondary or []) + shared_metric_roles.count("secondary"),- hours_since_launch=experiment.hours_since_launch,+ hours_since_launch=experiment.hours_since_launch(read_activity_log=can_read_flag_history),metric_events=metric_events,exposure_events=exposure_events,events_received=events_received,diff --git a/products/experiments/backend/health/exposure_gate.py b/products/experiments/backend/health/exposure_gate.pyindex 94cbfab84657..f653e8023c5a 100644--- a/products/experiments/backend/health/exposure_gate.py+++ b/products/experiments/backend/health/exposure_gate.py@@ -306,17 +306,17 @@ class _ExposureGate:def __init__(self,experiment: Experiment,- launched_at: datetime,+ start_date: datetime,*,group_type_index: int | None,denied_event_properties: frozenset[str],prefetch: Sequence[_Window | _UnitsWindow],) -> None:self._experiment = experiment- self._launched_at = launched_at+ self._start_date = start_dateself._group_type_index = group_type_indexself._denied_event_properties = denied_event_properties- self._default_exposure_event = resolve_default_exposure_event(experiment.team, launched_at)+ self._default_exposure_event = resolve_default_exposure_event(experiment.team, start_date)# One cache read for all windows of the walk and the counts, so a flag with many changes costs one round trip.self._prefetched_keys = (set()@@ -435,7 +435,7 @@ class _ExposureGate:# Every input of the query. The resolved exposure event is one, because the exposure event rollout# can move an experiment to another event.inputs = json.dumps(- [self._launched_at.isoformat(), *window_inputs, experiment.exposure_criteria, self._default_exposure_event],+ [self._start_date.isoformat(), *window_inputs, experiment.exposure_criteria, self._default_exposure_event],sort_keys=True,default=str,)@@ -453,10 +453,10 @@ def _load_flag_history(*,asked: frozenset[ExperimentHealthFlagChangeKind] = frozenset(_KINDS),) -> FlagHistory | FlagHistoryNotChecked | None:- launched_at = experiment.start_date+ start_date = experiment.start_date# django-stubs types the id as int, but an unsaved instance can carry None.feature_flag_id: int | None = experiment.feature_flag_id- if launched_at is None or experiment.end_date is not None or experiment.archived or feature_flag_id is None:+ if start_date is None or experiment.end_date is not None or experiment.archived or feature_flag_id is None:return Noneif experiment.feature_flag.deleted:return None@@ -464,17 +464,17 @@ def _load_flag_history(if not reader_access.can_read_flag_history:return FlagHistoryNotChecked(reason=FlagHistoryNotCheckedReason.NO_HISTORY_ACCESS,- launched_at=launched_at,+ start_date=start_date,team_timezone=team_timezone,changes=(),)edits = flag_edits_since(- team_id=experiment.team_id, feature_flag_id=feature_flag_id, since=launched_at, limit=MAX_FLAG_SAVES + 1+ team_id=experiment.team_id, feature_flag_id=feature_flag_id, since=start_date, limit=MAX_FLAG_SAVES + 1)too_large = _too_large(edits)if too_large is not None:- return FlagHistoryNotChecked(reason=too_large, launched_at=launched_at, team_timezone=team_timezone, changes=())+ return FlagHistoryNotChecked(reason=too_large, start_date=start_date, team_timezone=team_timezone, changes=())read = _flag_changes(edits, feature_flag_id=feature_flag_id)flag = experiment.feature_flagtrust_flag_aggregation = conditions_follow_flag_aggregation(flag.aggregation_group_type_index, flag.conditions)@@ -502,7 +502,7 @@ def _load_flag_history(merged.extend(applied)changes = tuple(sorted(merged, key=lambda change: change.changed_at))history = FlagHistory(- launched_at=launched_at,+ start_date=start_date,team_timezone=team_timezone,changes=changes,counted_since=None,@@ -522,27 +522,25 @@ def _load_flag_history(return historyreason = _not_checked_reason(experiment, reader_access)if reason is not None:- return FlagHistoryNotChecked(- reason=reason, launched_at=launched_at, team_timezone=team_timezone, changes=changes- )+ return FlagHistoryNotChecked(reason=reason, start_date=start_date, team_timezone=team_timezone, changes=changes)timeline = _Timeline(changes,current_key=experiment.get_feature_flag_key(),current_split=parse_variants(experiment.feature_flag.variants),)- starts = (launched_at, *times[:-1])+ starts = (start_date, *times[:-1])walk = [timeline.window(start=start, end=end) for start, end in zip(starts, times)]# The last change of a kind is its last counted change whenever the kind has one, so these windows are known# before the walk and share its cache read.units_windows = {- kind: timeline.units_window(start=launched_at, end=of_kind[-1].changed_at)+ kind: timeline.units_window(start=start_date, end=of_kind[-1].changed_at)for kind, change_type in _KINDS.items()if kind in asked and (of_kind := changes_of_kind(changes, change_type))}gate = _ExposureGate(experiment,- launched_at,+ start_date,group_type_index=flag.aggregation_group_type_index,denied_event_properties=reader_access.denied_event_properties,prefetch=[*walk, *(window for window in units_windows.values() if window is not None)],diff --git a/products/experiments/backend/health/exposure_inputs.py b/products/experiments/backend/health/exposure_inputs.pyindex d6a15e82d67b..914dd00bf437 100644--- a/products/experiments/backend/health/exposure_inputs.py+++ b/products/experiments/backend/health/exposure_inputs.py@@ -13,7 +13,6 @@ from posthog.models.user import Userfrom products.experiments.backend.facade.contracts import HealthExposureInputsStatusfrom products.experiments.backend.health.context import ExposureTotals-from products.experiments.backend.health.launch_time import hours_since_launchfrom products.experiments.backend.hogql_queries.experiment_exposures_query_runner import (ExperimentExposuresQueryRunner,build_experiment_exposure_query,@@ -99,7 +98,7 @@ def load_exposure_inputs(daily_exposures={},# The checks read the hours at computation, not now.hours_since_launch=(- hours_since_launch(experiment, computed_at, can_read_flag_history=can_read_flag_history)+ experiment.hours_since_launch(computed_at, read_activity_log=can_read_flag_history)if computed_atelse None),diff --git a/products/experiments/backend/health/inputs_payload.py b/products/experiments/backend/health/inputs_payload.pyindex 93dcfd981247..45e698fe6466 100644--- a/products/experiments/backend/health/inputs_payload.py+++ b/products/experiments/backend/health/inputs_payload.py@@ -143,7 +143,7 @@ def _health_inputs_flag_history(history: FlagHistory | FlagHistoryNotChecked) ->return {"checked": reason is None,"not_checked_reason": reason,- "launched_at": history.launched_at,+ "start_date": history.start_date,"team_timezone": history.team_timezone,"changes": changes,"exposed_before_first": exposed_before_first,diff --git a/products/experiments/backend/health/launch_time.py b/products/experiments/backend/health/launch_time.pydeleted file mode 100644index d80ec7757de5..000000000000--- a/products/experiments/backend/health/launch_time.py+++ /dev/null@@ -1,49 +0,0 @@-from datetime import datetime--from posthog.exceptions_capture import capture_exception-from posthog.models.activity_logging.activity_log import ActivityLog--from products.experiments.backend.health.delays import ZERO_EXPOSURES_GRACE_HOURS-from products.experiments.backend.models.experiment import Experiment---def hours_since_launch(experiment: Experiment, at: datetime, *, can_read_flag_history: bool) -> float | None:- """- The hours from the experiment's launch to `at`, which the exposure checks wait on. The start date can be moved- back to before the launch, when the flag didn't serve variants yet, so the wait counts from the later of the start- date and the latest launch in the activity log. The activity log needs the access of the flag history, so a reader- without it waits from the start date.- """- start_date = experiment.start_date- if start_date is None:- return None- hours = (at - start_date).total_seconds() / 3600- # A wait that holds by the start date also holds by the launch, which can only be later.- if hours < ZERO_EXPOSURES_GRACE_HOURS or not can_read_flag_history:- return hours- launched_at = _latest_launch(experiment)- if launched_at is None or launched_at <= start_date:- return hours- return (at - launched_at).total_seconds() / 3600---def _latest_launch(experiment: Experiment) -> datetime | None:- # A launch logs the start date that it sets on a draft. An experiment created with a start date logs none, and its- # start date stands.- try:- return (- ActivityLog.objects.filter(- team_id=experiment.team_id,- scope="Experiment",- item_id=str(experiment.id),- activity="updated",- detail__contains={"changes": [{"field": "start_date", "before": None}]},- )- .order_by("-created_at")- .values_list("created_at", flat=True)- .first()- )- except Exception as error:- # The start date is a safe fallback, so a failed lookup must not fail the exposure answer.- capture_exception(error)- return Nonediff --git a/products/experiments/backend/health/loader.py b/products/experiments/backend/health/loader.pyindex a285f9598cc4..6672110dae70 100644--- a/products/experiments/backend/health/loader.py+++ b/products/experiments/backend/health/loader.py@@ -75,7 +75,9 @@ def _health_context(experiment: Experiment, reader_access: ExperimentHealthReaderAccess, user: User | None) -> HealthContext:flag_history = load_flag_history(experiment, reader_access=reader_access)- context = load_health_context(experiment, flag_history=flag_history)+ context = load_health_context(+ experiment, flag_history=flag_history, can_read_flag_history=reader_access.can_read_flag_history+ )traffic = load_condition_set_traffic(experiment, context, reader_access=reader_access)latest_calculation = load_latest_calculation(experiment)return replace(@@ -83,7 +85,9 @@ def _health_context(condition_set_traffic=traffic,pause_history=load_pause_history(experiment, reader_access=reader_access),primary_metric=load_primary_metric(experiment),- primary_metric_windows=load_primary_metric_windows(experiment),+ primary_metric_windows=load_primary_metric_windows(+ experiment, can_read_flag_history=reader_access.can_read_flag_history+ ),metric_compiles=load_metric_compiles(experiment, user=user),latest_calculation=latest_calculation,exposure_filters_without_column=load_filters_without_column(experiment)diff --git a/products/experiments/backend/health/metric_windows.py b/products/experiments/backend/health/metric_windows.pyindex ec20899e6c7b..0167d52c88f2 100644--- a/products/experiments/backend/health/metric_windows.py+++ b/products/experiments/backend/health/metric_windows.py@@ -16,22 +16,26 @@ from products.experiments.backend.metric_resolution import build_metricfrom products.experiments.backend.models.experiment import Experiment-def load_primary_metric_windows(experiment: Experiment) -> tuple[MetricWindow, ...] | None:+def load_primary_metric_windows(+ experiment: Experiment, *, can_read_flag_history: bool+) -> tuple[MetricWindow, ...] | None:"""The windows of the primary metrics of a launched experiment that hasn't ended, isn't archived and has`only_count_matured_users` on, or None. Never raises: the check that reads them then reports that it couldn't check."""- start_date = experiment.start_date- if start_date is None or experiment.is_stopped or experiment.archived or not experiment.only_count_matured_users:+ if not experiment.is_running or experiment.archived or not experiment.only_count_matured_users:return Nonetry:- return _load_primary_metric_windows(experiment, start_date)+ launched_at = experiment.launched_at(read_activity_log=can_read_flag_history)+ if launched_at is None:+ return None+ return _load_primary_metric_windows(experiment, launched_at)except Exception as error:capture_exception(error)return None-def metric_window(*, name: str, definition: dict[str, Any], start_date: datetime) -> MetricWindow | None:+def metric_window(*, name: str, definition: dict[str, Any], launched_at: datetime) -> MetricWindow | None:"""The window of one metric definition. None when the definition doesn't parse, which `metric_cannot_compile`reports, so this captures nothing."""try:@@ -41,11 +45,11 @@ def metric_window(*, name: str, definition: dict[str, Any], start_date: datetimereturn MetricWindow(name=name,window_seconds=window_seconds,- first_users_count_at=start_date + timedelta(seconds=window_seconds),+ first_users_count_at=launched_at + timedelta(seconds=window_seconds),)-def _load_primary_metric_windows(experiment: Experiment, start_date: datetime) -> tuple[MetricWindow, ...] | None:+def _load_primary_metric_windows(experiment: Experiment, launched_at: datetime) -> tuple[MetricWindow, ...] | None:# Metrics that share a uuid share its first definition, so one window covers them.configs: dict[str, MetricCalculationConfig] = {}for calculation_config in build_primary_calculation_configs(experiment):@@ -55,7 +59,7 @@ def _load_primary_metric_windows(experiment: Experiment, start_date: datetime) -window = metric_window(name=calculation_metric_name(experiment, calculation_config),definition=calculation_config.definition,- start_date=start_date,+ launched_at=launched_at,)if window is None:return Nonediff --git a/products/experiments/backend/health/pause_history.py b/products/experiments/backend/health/pause_history.pyindex 21329c8699ab..6ab9da3f1ff9 100644--- a/products/experiments/backend/health/pause_history.py+++ b/products/experiments/backend/health/pause_history.py@@ -28,8 +28,8 @@ def load_pause_history(experiment: Experiment, *, reader_access: ExperimentHealtdef _load_pause_history(experiment: Experiment) -> PauseHistory | None:- launched_at = experiment.start_date- if launched_at is None:+ start_date = experiment.start_date+ if start_date is None:return None# A pause before a reset to draft belongs to an earlier run, so only the entries since launch count.latest = (@@ -38,14 +38,14 @@ def _load_pause_history(experiment: Experiment) -> PauseHistory | None:scope="Experiment",item_id=str(experiment.id),activity__in=(_PAUSED, _RESUMED),- created_at__gte=launched_at,+ created_at__gte=start_date,).order_by("-created_at").values_list("activity", "created_at").first())return PauseHistory(- launched_at=launched_at,+ start_date=start_date,team_timezone=experiment.team.timezone,paused_at=latest[1] if latest is not None and latest[0] == _PAUSED else None,)diff --git a/products/experiments/backend/health/test/factories.py b/products/experiments/backend/health/test/factories.pyindex ea2cb1f6c6b3..b0d1e578b970 100644--- a/products/experiments/backend/health/test/factories.py+++ b/products/experiments/backend/health/test/factories.py@@ -69,7 +69,7 @@ DRAFT: Status = {"is_launched": False, "is_running": False, "has_ended": False}def flag_history(changes: Sequence[FlagChange],*,- launched_at: datetime,+ start_date: datetime,exposed_before_first: bool | None = True,exposed_between: Mapping[ExperimentHealthFlagChangeKind, bool | None] | None = None,not_checked: FlagHistoryNotCheckedReason | None = None,@@ -81,10 +81,10 @@ def flag_history(# Every change counts from the first, as when someone was exposed before it.if not_checked is not None:return FlagHistoryNotChecked(- reason=not_checked, launched_at=launched_at, team_timezone="Europe/Berlin", changes=tuple(changes)+ reason=not_checked, start_date=start_date, team_timezone="Europe/Berlin", changes=tuple(changes))return FlagHistory(- launched_at=launched_at,+ start_date=start_date,team_timezone="Europe/Berlin",changes=tuple(changes),counted_since=changes[0].changed_at if changes else None,diff --git a/products/experiments/backend/health/test/test_bucketing_changed.py b/products/experiments/backend/health/test/test_bucketing_changed.pyindex 19cdf6144253..a073c4c1954b 100644--- a/products/experiments/backend/health/test/test_bucketing_changed.py+++ b/products/experiments/backend/health/test/test_bucketing_changed.py@@ -65,7 +65,7 @@ def _context(),flag_history=flag_history(bucketing,- launched_at=LAUNCHED_AT,+ start_date=LAUNCHED_AT,exposed_before_first=exposed_before_first,exposed_between={ExperimentHealthFlagChangeKind.BUCKETING: exposed_between},not_checked=not_checked,@@ -91,7 +91,7 @@ class TestBucketingChangedMidRun(TestCase):_context((KEY, "old-key", "new-key"), exposed_units=4),("key_changed", ExperimentHealthFindingSeverity.INFO, "The flag key changed after launch"),f'The flag key changed from "old-key" to "new-key" on {FIRST_CHANGE}. The change came 3 hours after '- f"launch, when 4 people had been exposed. Move the start date to {FIRST_CHANGE} so the results count only exposures after it. "+ f"the start date, when 4 people had been exposed. Move the start date to {FIRST_CHANGE} so the results count only exposures after it. "'Code that still uses "old-key" no longer gets this flag.',),(@@ -112,7 +112,7 @@ class TestBucketingChangedMidRun(TestCase):"The flag's variant assignment changed after launch",),f"The flag changed from matching by users to matching by groups on {FIRST_CHANGE}. The change came 3 "- f"hours after launch, when 4 people had been exposed. Move the start date to {FIRST_CHANGE} so the results count only exposures after it.",+ f"hours after the start date, when 4 people had been exposed. Move the start date to {FIRST_CHANGE} so the results count only exposures after it.",),("bucketing_identifier_changed_days_after_launch",@@ -123,7 +123,7 @@ class TestBucketingChangedMidRun(TestCase):"The flag's variant assignment changed after launch",),"The flag changed from matching by user ID to matching by device ID on September 20, 2026 at 3:04 PM "- "CEST. The change came 8 days after launch. Users whose device ID differs from their user ID got a "+ "CEST. The change came 8 days after the start date. Users whose device ID differs from their user ID got a "f"new variant draw, so they may have switched variants. {MIXED_ASSIGNMENTS} Reset the experiment, or ""move its start date to September 20, 2026 at 3:04 PM CEST.",),@@ -136,7 +136,7 @@ class TestBucketingChangedMidRun(TestCase):"The flag's variant assignment changed after launch",),f'On {FIRST_CHANGE}, "Persist flag across authentication steps" was turned off. The change came 3 '- "hours after launch. Users who logged in while it was on no longer keep the variant they got before "+ "hours after the start date. Users who logged in while it was on no longer keep the variant they got before "f"logging in, so they may have switched variants. {MIXED_ASSIGNMENTS} Reset the experiment, or move "f"its start date to {FIRST_CHANGE}.",),@@ -220,7 +220,7 @@ class TestBucketingChangedMidRun(TestCase):"The flag's variant assignment changed after launch",),f'The flag\'s "Match by" setting changed on {FIRST_CHANGE} and was set back on {SECOND_CHANGE}. '- "The last change came 3 hours after launch, when 4 people had been exposed. Move the start date to "+ "The last change came 3 hours after the start date, when 4 people had been exposed. Move the start date to "f"{SECOND_CHANGE} so the results count only exposures after it.",),(diff --git a/products/experiments/backend/health/test/test_conditions_changed.py b/products/experiments/backend/health/test/test_conditions_changed.pyindex 824a52d16796..76b59814d08a 100644--- a/products/experiments/backend/health/test/test_conditions_changed.py+++ b/products/experiments/backend/health/test/test_conditions_changed.py@@ -71,7 +71,7 @@ def _context(flag=parse_flag_state(active=True, deleted=False, groups=now or conditions[-1], variants=variants),flag_history=flag_history(changes,- launched_at=LAUNCHED_AT,+ start_date=LAUNCHED_AT,exposed_between={ExperimentHealthFlagChangeKind.RELEASE_CONDITIONS: exposed_between},not_checked=not_checked,release_conditions=None if now is None else parse_release_conditions(now, variant_keys=variant_keys),@@ -138,7 +138,7 @@ class TestReleaseConditionsChangedMidRun(TestCase):_context([PRO_PINNED, EVERYONE], [PRO, EVERYONE], people_by_set={1: 300, 2: 2700}, exposed_units=4),("variant_override_changed", INFO, OVERRIDE_TITLE, "A7"),f'The variant override "test" of Set 1 was removed on {FIRST_CHANGE}. The change came 3 hours after '- f"launch, when 4 people had been exposed. Move the start date to {FIRST_CHANGE} so the results count only exposures after it. "+ f"the start date, when 4 people had been exposed. Move the start date to {FIRST_CHANGE} so the results count only exposures after it. "f'Since {TRAFFIC_SINCE}, Set 1 matched about 18.2% of the users who would get "test" with the '"override in place (300 of about 1,650).",),diff --git a/products/experiments/backend/health/test/test_flag_state.py b/products/experiments/backend/health/test/test_flag_state.pyindex fae80108bb73..73834b9b58ee 100644--- a/products/experiments/backend/health/test/test_flag_state.py+++ b/products/experiments/backend/health/test/test_flag_state.py@@ -77,8 +77,8 @@ def _traffic(people_assigned_outside: int, *, window: timedelta = timedelta(days)-def _pause_history(*, launched_at: datetime, paused_at: datetime | None) -> PauseHistory:- return PauseHistory(launched_at=launched_at, team_timezone="Europe/Berlin", paused_at=paused_at)+def _pause_history(*, start_date: datetime, paused_at: datetime | None) -> PauseHistory:+ return PauseHistory(start_date=start_date, team_timezone="Europe/Berlin", paused_at=paused_at)LAUNCHED_BEFORE_PAUSE_ENTRIES = datetime(2026, 8, 1, 9, 0, tzinfo=UTC)@@ -87,11 +87,11 @@ PAUSED_AT = datetime(2026, 10, 12, 13, 4, tzinfo=UTC)ENDED_AT = datetime(2026, 10, 14, 8, 30, tzinfo=UTC)-def _other(*, launched_at: datetime | None, ended_at: datetime | None = None) -> ExperimentOnFlag:- return ExperimentOnFlag(launched_at=launched_at, ended_at=ended_at, archived=False)+def _other(*, start_date: datetime | None, ended_at: datetime | None = None) -> ExperimentOnFlag:+ return ExperimentOnFlag(start_date=start_date, ended_at=ended_at, archived=False)-DRAFT_ON_FLAG = _other(launched_at=None)+DRAFT_ON_FLAG = _other(start_date=None)def _context(@@ -188,7 +188,7 @@ class TestFlagState(TestCase):active=True,filters=MULTIVARIANT,flag_called_after_end=True,- other_experiments=(_other(launched_at=ENDED_AT - timedelta(days=3)),),+ other_experiments=(_other(start_date=ENDED_AT - timedelta(days=3)),),),not_applicable(OTHER_EXPERIMENT_DECIDES),),@@ -200,7 +200,7 @@ class TestFlagState(TestCase):filters=MULTIVARIANT,flag_called_after_end=True,other_experiments=(- _other(launched_at=ENDED_AT + timedelta(days=1), ended_at=ENDED_AT + timedelta(days=5)),+ _other(start_date=ENDED_AT + timedelta(days=1), ended_at=ENDED_AT + timedelta(days=5)),),),not_applicable(OTHER_EXPERIMENT_DECIDES),@@ -213,7 +213,7 @@ class TestFlagState(TestCase):filters=MULTIVARIANT,flag_called_after_end=True,other_experiments=(- _other(launched_at=ENDED_AT - timedelta(days=30), ended_at=ENDED_AT - timedelta(days=20)),+ _other(start_date=ENDED_AT - timedelta(days=30), ended_at=ENDED_AT - timedelta(days=20)),),),(ExperimentHealthFindingCode.FLAG_LIVE_AFTER_END, "ended_but_multiple_variants_rolled_out", None),@@ -257,7 +257,7 @@ class TestFlagState(TestCase):DRAFT,active=True,filters=MULTIVARIANT,- other_experiments=(_other(launched_at=ENDED_AT - timedelta(days=3)),),+ other_experiments=(_other(start_date=ENDED_AT - timedelta(days=3)),),),not_applicable(OTHER_EXPERIMENT_DECIDES),),@@ -316,7 +316,7 @@ class TestFlagState(TestCase):RUNNING,active=False,filters=MULTIVARIANT,- pause_history=_pause_history(launched_at=LAUNCHED_BEFORE_PAUSE_ENTRIES, paused_at=PAUSED_AT),+ pause_history=_pause_history(start_date=LAUNCHED_BEFORE_PAUSE_ENTRIES, paused_at=PAUSED_AT),),("paused_from_experiment", ExperimentHealthFindingSeverity.INFO, "The experiment is paused"),),@@ -326,7 +326,7 @@ class TestFlagState(TestCase):RUNNING,active=False,filters=MULTIVARIANT,- pause_history=_pause_history(launched_at=LAUNCHED_AFTER_PAUSE_ENTRIES, paused_at=None),+ pause_history=_pause_history(start_date=LAUNCHED_AFTER_PAUSE_ENTRIES, paused_at=None),),("running_but_flag_disabled",@@ -340,8 +340,8 @@ class TestFlagState(TestCase):RUNNING,active=False,filters=MULTIVARIANT,- pause_history=_pause_history(launched_at=LAUNCHED_AFTER_PAUSE_ENTRIES, paused_at=None),- other_experiments=(_other(launched_at=LAUNCHED_AFTER_PAUSE_ENTRIES),),+ pause_history=_pause_history(start_date=LAUNCHED_AFTER_PAUSE_ENTRIES, paused_at=None),+ other_experiments=(_other(start_date=LAUNCHED_AFTER_PAUSE_ENTRIES),),),("running_but_flag_disabled",@@ -355,7 +355,7 @@ class TestFlagState(TestCase):RUNNING,active=False,filters=MULTIVARIANT,- pause_history=_pause_history(launched_at=LAUNCHED_BEFORE_PAUSE_ENTRIES, paused_at=None),+ pause_history=_pause_history(start_date=LAUNCHED_BEFORE_PAUSE_ENTRIES, paused_at=None),),("running_but_flag_disabled", ExperimentHealthFindingSeverity.WARNING, "The experiment is paused"),),@@ -460,7 +460,7 @@ class TestFlagState(TestCase):RUNNING,active=False,filters=MULTIVARIANT,- pause_history=_pause_history(launched_at=LAUNCHED_AFTER_PAUSE_ENTRIES, paused_at=PAUSED_AT),+ pause_history=_pause_history(start_date=LAUNCHED_AFTER_PAUSE_ENTRIES, paused_at=PAUSED_AT),),"The experiment was paused on October 12, 2026 at 3:04 PM CEST, so the linked feature flag serves no ""variants. Users exposed before the pause stay in the results. Their events during the pause can "diff --git a/products/experiments/backend/health/test/test_forced_variant.py b/products/experiments/backend/health/test/test_forced_variant.pyindex deda497d2d00..daa3e1db9a9e 100644--- a/products/experiments/backend/health/test/test_forced_variant.py+++ b/products/experiments/backend/health/test/test_forced_variant.py@@ -93,7 +93,7 @@ def _history(before=parse_release_conditions(before, variant_keys=variant_keys),after=parse_release_conditions(after, variant_keys=variant_keys),)- return flag_history([change], launched_at=datetime(2026, 9, 12, 10, 0, tzinfo=UTC))+ return flag_history([change], start_date=datetime(2026, 9, 12, 10, 0, tzinfo=UTC))def _traffic(people_by_set: dict[int, int], *, remotely_evaluated: float = 1.0) -> ConditionSetTraffic:diff --git a/products/experiments/backend/health/test/test_metrics_not_matured.py b/products/experiments/backend/health/test/test_metrics_not_matured.pyindex 84a9514910f4..2c3ea373ffcb 100644--- a/products/experiments/backend/health/test/test_metrics_not_matured.py+++ b/products/experiments/backend/health/test/test_metrics_not_matured.py@@ -9,6 +9,8 @@ from django.utils import timezonefrom parameterized import parameterized+from posthog.models.activity_logging.activity_log import ActivityLog+from products.experiments.backend.facade.api import get_experiment_healthfrom products.experiments.backend.facade.contracts import (ExperimentHealthCheckKey,@@ -36,6 +38,7 @@ Status = ExperimentHealthCheckStatusNO_QUERIES = ExperimentHealthReaderAccess(can_read_flag_history=False, can_query_events=False, denied_event_properties=frozenset())+READS_HISTORY = replace(NO_QUERIES, can_read_flag_history=True)LAUNCHED_AT = datetime(2026, 10, 1, 12, tzinfo=UTC)PURCHASE = {"kind": "EventsNode", "event": "purchase"}NO_WINDOW = {"kind": "ExperimentMetric", "metric_type": "funnel", "series": [PURCHASE]}@@ -64,7 +67,7 @@ RETENTION = {def _window(name: str, metric: dict[str, Any]) -> MetricWindow:- window = metric_window(name=name, definition=metric, start_date=LAUNCHED_AT)+ window = metric_window(name=name, definition=metric, launched_at=LAUNCHED_AT)assert window is not Nonereturn window@@ -173,12 +176,13 @@ class TestMetricsNotMatured(TestCase):class TestMetricsNotMaturedFromStoredMetrics(BaseTest):@parameterized.expand([- ("saved_primary_held_back", [], [], FOUR_DAYS, Status.FINDING, "Checkout funnel"),+ ("saved_primary_held_back", [], [], FOUR_DAYS, None, Status.FINDING, "Checkout funnel"),("a_secondary_past_its_window_does_not_clear_the_primaries",[FOUR_DAYS],[NO_WINDOW],None,+ None,Status.FINDING,"purchase conversion",),@@ -187,11 +191,41 @@ class TestMetricsNotMaturedFromStoredMetrics(BaseTest):[FOUR_DAYS],[],{**FOUR_DAYS, "uuid": "primary-0"},+ None,Status.FINDING,"purchase conversion",),- ("only_a_secondary_held_back", [NO_WINDOW], [FOUR_DAYS], None, Status.PASSED, None),- ("a_primary_that_does_not_parse", [{"metric_type": "funnel"}], [], None, Status.NOT_CHECKED, None),+ ("only_a_secondary_held_back", [NO_WINDOW], [FOUR_DAYS], None, None, Status.PASSED, None),+ ("a_primary_that_does_not_parse", [{"metric_type": "funnel"}], [], None, None, Status.NOT_CHECKED, None),+ (+ "launched_after_its_start_date",+ [FOUR_DAYS],+ [],+ None,+ (5, 1),+ Status.FINDING,+ "purchase conversion",+ True,+ ),+ (+ "launch_hidden_from_a_reader_without_the_flag_history",+ [FOUR_DAYS],+ [],+ None,+ (5, 1),+ Status.PASSED,+ None,+ ),+ (+ "start_date_moved_after_the_launch",+ [FOUR_DAYS],+ [],+ None,+ (3, 5),+ Status.FINDING,+ "purchase conversion",+ True,+ ),])def test_reads_the_windows_of_the_stored_primary_metrics(@@ -200,8 +234,10 @@ class TestMetricsNotMaturedFromStoredMetrics(BaseTest):primary: list[dict[str, Any]],secondary: list[dict[str, Any]],saved_primary: dict[str, Any] | None,+ start_and_launch_days_ago: tuple[int, int] | None,expected: Status,expected_metric: str | None,+ reads_flag_history: bool = False,) -> None:flag = FeatureFlag.objects.create(team=self.team,@@ -217,15 +253,29 @@ class TestMetricsNotMaturedFromStoredMetrics(BaseTest):},},)+ start_days_ago, launch_days_ago = start_and_launch_days_ago or (3, None)+ start_date = timezone.now() - timedelta(days=start_days_ago)experiment = Experiment.objects.create(team=self.team,name="checkout",feature_flag=flag,- start_date=timezone.now() - timedelta(days=3),+ start_date=start_date,only_count_matured_users=True,metrics=[{**metric, "uuid": f"primary-{index}"} for index, metric in enumerate(primary)],metrics_secondary=[{**metric, "uuid": f"secondary-{index}"} for index, metric in enumerate(secondary)],)+ counted_from = None+ if launch_days_ago is not None:+ launched_at = timezone.now() - timedelta(days=launch_days_ago)+ ActivityLog.objects.create(+ team_id=self.team.id,+ scope="Experiment",+ item_id=str(experiment.id),+ activity="updated",+ detail={"changes": [{"field": "start_date", "before": None, "after": launched_at.isoformat()}]},+ created_at=launched_at,+ )+ counted_from = max(start_date, launched_at)if saved_primary is not None:saved_metric = ExperimentSavedMetric.objects.create(team=self.team, name="Checkout funnel", query={"uuid": "saved-primary", **saved_primary}@@ -235,7 +285,10 @@ class TestMetricsNotMaturedFromStoredMetrics(BaseTest):)health = get_experiment_health(- team_id=self.team.id, experiment_id=experiment.id, reader_access=NO_QUERIES, user=self.user+ team_id=self.team.id,+ experiment_id=experiment.id,+ reader_access=READS_HISTORY if reads_flag_history else NO_QUERIES,+ user=self.user,)check = next(check for check in health.checks if check.key == ExperimentHealthCheckKey.METRICS_NOT_MATURED)@@ -247,3 +300,7 @@ class TestMetricsNotMaturedFromStoredMetrics(BaseTest):self.assertEqual(finding is not None, expected == Status.FINDING)if finding:self.assertEqual(finding.detail.count(f'"{expected_metric}"'), 1)+ if finding and counted_from is not None:+ self.assertEqual(+ finding.evidence["first_users_count_at"], (counted_from + timedelta(days=4)).astimezone(UTC).isoformat()+ )diff --git a/products/experiments/backend/health/test/test_pause_history.py b/products/experiments/backend/health/test/test_pause_history.pyindex 944c4938fb3d..4de3e93e8edf 100644--- a/products/experiments/backend/health/test/test_pause_history.py+++ b/products/experiments/backend/health/test/test_pause_history.py@@ -21,7 +21,7 @@ FULL_ACCESS = ExperimentHealthReaderAccess(def _history(paused_after_hours: int | None) -> PauseHistory:return PauseHistory(- launched_at=LAUNCHED_AT,+ start_date=LAUNCHED_AT,team_timezone="UTC",paused_at=None if paused_after_hours is None else LAUNCHED_AT + timedelta(hours=paused_after_hours),)diff --git a/products/experiments/backend/health/test/test_registry.py b/products/experiments/backend/health/test/test_registry.pyindex 7f60a0a94c30..d08541c666fa 100644--- a/products/experiments/backend/health/test/test_registry.py+++ b/products/experiments/backend/health/test/test_registry.py@@ -223,14 +223,14 @@ class TestEvaluate(TestCase):"flag_changes_are_not_checked_without_the_history",{"flag_history": flag_history(- [], launched_at=LAUNCHED_AT, not_checked=FlagHistoryNotCheckedReason.NO_HISTORY_ACCESS+ [], start_date=LAUNCHED_AT, not_checked=FlagHistoryNotCheckedReason.NO_HISTORY_ACCESS)},{Key.FLAG_HISTORY: Status.FINDING, **dict.fromkeys(FLAG_CHANGE_KEYS, Status.NOT_CHECKED)},),("flag_changes_pass_with_a_history_without_changes",- {"flag_history": flag_history([], launched_at=LAUNCHED_AT)},+ {"flag_history": flag_history([], start_date=LAUNCHED_AT)},{Key.FLAG_HISTORY: Status.PASSED, **dict.fromkeys(FLAG_CHANGE_KEYS, Status.PASSED)},),(diff --git a/products/experiments/backend/health/test/test_shared_flag.py b/products/experiments/backend/health/test/test_shared_flag.pyindex 7d3cefaec644..5ebe62125c39 100644--- a/products/experiments/backend/health/test/test_shared_flag.py+++ b/products/experiments/backend/health/test/test_shared_flag.py@@ -21,10 +21,10 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlagLAUNCHED_AT = datetime(2026, 10, 1, tzinfo=UTC)ENDED_AT = datetime(2026, 10, 10, tzinfo=UTC)-RUNNING_OTHER = ExperimentOnFlag(launched_at=LAUNCHED_AT, ended_at=None, archived=False)-DRAFT_OTHER = ExperimentOnFlag(launched_at=None, ended_at=None, archived=False)-ENDED_OTHER = ExperimentOnFlag(launched_at=LAUNCHED_AT, ended_at=ENDED_AT, archived=False)-ARCHIVED_DRAFT_OTHER = ExperimentOnFlag(launched_at=None, ended_at=None, archived=True)+RUNNING_OTHER = ExperimentOnFlag(start_date=LAUNCHED_AT, ended_at=None, archived=False)+DRAFT_OTHER = ExperimentOnFlag(start_date=None, ended_at=None, archived=False)+ENDED_OTHER = ExperimentOnFlag(start_date=LAUNCHED_AT, ended_at=ENDED_AT, archived=False)+ARCHIVED_DRAFT_OTHER = ExperimentOnFlag(start_date=None, ended_at=None, archived=True)WARNING = ExperimentHealthFindingSeverity.WARNINGINFO = ExperimentHealthFindingSeverity.INFOdiff --git a/products/experiments/backend/health/test/test_split_changed.py b/products/experiments/backend/health/test/test_split_changed.pyindex 6c52472fb08f..eadf17695e67 100644--- a/products/experiments/backend/health/test/test_split_changed.py+++ b/products/experiments/backend/health/test/test_split_changed.py@@ -72,7 +72,7 @@ def _context(groups: list[dict[str, Any]] = EVERYONE,exposed_before_first: bool | None = True,exposed_between: bool | None = None,- launched_at: datetime = LAUNCHED_AT,+ start_date: datetime = LAUNCHED_AT,first_change_at: datetime = FIRST_CHANGE_AT,archived: bool = False,deleted: bool = False,@@ -95,7 +95,7 @@ def _context(flag=parse_flag_state(active=True, deleted=deleted, groups=groups, variants=splits[-1]),flag_history=flag_history(changes,- launched_at=launched_at,+ start_date=start_date,exposed_before_first=exposed_before_first,exposed_between={ExperimentHealthFlagChangeKind.SPLIT: exposed_between},not_checked=not_checked,@@ -137,7 +137,7 @@ class TestSplitChangedMidRun(TestCase):_context(EVEN, UNEVEN, exposed_before_first=None),("rebalanced", ExperimentHealthFindingSeverity.WARNING, "E3"),f"The split changed from control 50% / test 50% to control 80% / test 20% on {FIRST_CHANGE}. "- "The change came 3 hours after launch. "+ "The change came 3 hours after the start date. ""People exposed before the change may have switched variants, so the results mix two assignments. "f"Reset the experiment, or move its start date to {FIRST_CHANGE} to analyze only the people exposed "f"after the change. {MIXED_ASSIGNMENTS}",@@ -147,7 +147,7 @@ class TestSplitChangedMidRun(TestCase):_context(EVEN, UNEVEN, exposed_units=4),("rebalanced", ExperimentHealthFindingSeverity.INFO, "E3"),f"The split changed from control 50% / test 50% to control 80% / test 20% on {FIRST_CHANGE}. "- "The change came 3 hours after launch, when 4 people had been exposed. Move the start date to "+ "The change came 3 hours after the start date, when 4 people had been exposed. Move the start date to "f"{FIRST_CHANGE} so the results count only exposures after it.",),(@@ -164,14 +164,14 @@ class TestSplitChangedMidRun(TestCase):_context(EVEN, UNEVEN, exposed_units=0, counts_groups=True),("rebalanced", ExperimentHealthFindingSeverity.INFO, "E3"),f"The split changed from control 50% / test 50% to control 80% / test 20% on {FIRST_CHANGE}. "- "The change came 3 hours after launch, when no group had been exposed.",+ "The change came 3 hours after the start date, when no group had been exposed.",),("variant_zeroed_before_4_groups",_context(THREE_WAY, BLUE_ZEROED, exposed_units=4, counts_groups=True),("variant_zeroed", ExperimentHealthFindingSeverity.INFO, "E3"),f'Variant "blue" was set to 0% on {FIRST_CHANGE} (from control 34% / test 33% / blue 33% to '- "control 50% / test 50% / blue 0%). The change came 3 hours after launch, when 4 groups had been "+ "control 50% / test 50% / blue 0%). The change came 3 hours after the start date, when 4 groups had been "f"exposed. Move the start date to {FIRST_CHANGE} so the results count only exposures after it. "'No new users get "blue".',),@@ -233,11 +233,11 @@ class TestSplitChangedMidRun(TestCase):_split(("control", 70), ("test", 30)),_split(("control", 60), ("test", 40)),UNEVEN,- launched_at=LAUNCHED_AT - timedelta(days=8),+ start_date=LAUNCHED_AT - timedelta(days=8),),("rebalanced", ExperimentHealthFindingSeverity.WARNING, "E3"),f"The split changed 3 times between {FIRST_CHANGE} and {THIRD_CHANGE}, from control 50% / "- "test 50% to control 80% / test 20%. The first change came 8 days after launch. People exposed "+ "test 50% to control 80% / test 20%. The first change came 8 days after the start date. People exposed ""before the changes may have switched variants, so the results mix two assignments. Reset the "f"experiment, or move its start date to {THIRD_CHANGE} to analyze only the people exposed after the ""changes. A sample ratio mismatch or users in more than one variant can come from these changes.",@@ -255,7 +255,7 @@ class TestSplitChangedMidRun(TestCase):_context(EVEN, SHIPPED, EVEN, exposed_between=True, exposed_units=4),("reverted", ExperimentHealthFindingSeverity.INFO, "E3"),f"The split was set to control 0% / test 100% on {FIRST_CHANGE} and set back to control 50% / "- f"test 50% on {SECOND_CHANGE}. The last change came 3 hours after launch, when 4 people had been "+ f"test 50% on {SECOND_CHANGE}. The last change came 3 hours after the start date, when 4 people had been "f"exposed. Move the start date to {SECOND_CHANGE} so the results count only exposures after it.",),(@@ -311,7 +311,7 @@ class TestSplitChangedMidRun(TestCase):"from": "control 50% / test 50%","to": "control 80% / test 20%","exposed_before_change": None,- "seconds_after_launch": 11040,+ "seconds_after_start": 11040,"units_exposed_before_last_change": None,},),@@ -326,7 +326,7 @@ class TestSplitChangedMidRun(TestCase):"from": "control 50% / test 50%","to": "control 80% / test 20%","exposed_before_change": True,- "seconds_after_launch": 11040,+ "seconds_after_start": 11040,"units_exposed_before_last_change": 4,},),@@ -341,7 +341,7 @@ class TestSplitChangedMidRun(TestCase):"from": "control 50% / test 50%","to": "control 80% / test 20%","exposed_before_change": None,- "seconds_after_launch": 11040,+ "seconds_after_start": 11040,},),(@@ -406,7 +406,7 @@ class TestSplitChangedMidRun(TestCase):"too_many_saves",_context(EVEN, not_checked=FlagHistoryNotCheckedReason.TOO_MANY_SAVES),"This check can't see whether the flag's variant split, key, bucketing or release conditions changed "- "after launch, because the flag was saved more than 100 times since launch. Review the flag history.",+ "after launch, because the flag was saved more than 100 times since the start date. Review the flag history.",(ExperimentHealthFindingActionKind.OPEN_FEATURE_FLAG_HISTORY,),"The flag history was not checked",),diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.pyindex 6814d8dcf7b8..17d8e69a42f5 100644--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py@@ -73,7 +73,6 @@ from products.experiments.backend.health.context import (load_health_context,)from products.experiments.backend.health.exposure_gate import load_split_history-from products.experiments.backend.health.launch_time import hours_since_launchfrom products.experiments.backend.health.registry import (EXPOSURE_HEALTH_CHECKS,evaluate as evaluate_health,@@ -358,7 +357,7 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):return load_split_history(self.experiment, reader_access=reader_access)def _evaluate_health(self, exposures: ExposureTotals, exposure_params: ExposureQueryParams) -> ExperimentHealth:- context = load_health_context(self.experiment, exposures)+ context = load_health_context(self.experiment, exposures, can_read_flag_history=self._can_read_flag_history())if reads_flag_history(context):context = replace(context, flag_history=self._flag_history())# These queries run for every reader, a userless run included. The findings depend on them, and the cache key@@ -583,9 +582,7 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):sample_ratio_mismatch_p_value=sample_ratio_mismatch.p_value if sample_ratio_mismatch else None,sample_ratio_expected=sample_ratio_mismatch.expected if sample_ratio_mismatch else {},daily_exposures=daily_exposures,- hours_since_launch=hours_since_launch(- self.experiment, datetime.now(UTC), can_read_flag_history=self._can_read_flag_history()- ),+ hours_since_launch=self.experiment.hours_since_launch(read_activity_log=self._can_read_flag_history()),counts_groups=aggregates_by_group(self.group_type_index),filters_test_accounts=applies_test_account_filters(self.team, self.exposure_criteria),has_positive_test_account_filter=has_positive_test_account_filter(self.team),diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.pyindex 721c59d115cf..bb398d05dcdb 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py@@ -2077,7 +2077,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):)lookup = patch(- "products.experiments.backend.health.launch_time.ActivityLog.objects.filter",+ "products.experiments.backend.models.experiment.ActivityLog.objects.filter",side_effect=OperationalError("the activity log is unavailable"),)with time_machine.travel(now, tick=False), lookup if launch_lookup_fails else nullcontext():diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 60db565eb24f..006af4e10738 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -1,4 +1,5 @@from collections.abc import Callable, Sequence+from datetime import datetimefrom typing import TYPE_CHECKING, Any, Literalfrom django.contrib.postgres.fields import ArrayField@@ -7,6 +8,8 @@ from django.db.models import Exists, OuterRef, QuerySetfrom django.db.models.fields.json import KeyTextTransformfrom django.utils import timezone+from posthog.exceptions_capture import capture_exception+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixin@@ -204,12 +207,50 @@ class Experiment(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixireturn self.is_launched and self.end_date is not None@property- def hours_since_launch(self) -> float | None:+ def hours_since_start(self) -> float | None:# Counts to now also after the end date.if self.start_date is None:return Nonereturn (timezone.now() - self.start_date).total_seconds() / 3600+ def launched_at(self, *, read_activity_log: bool) -> datetime | None:+ """+ The later of the start date and the latest launch in the activity log. The start date can be moved back to+ before the launch, so it can be earlier than the first variant the flag served. Without `read_activity_log`,+ for a reader who may not read the experiment's activity log, it is the start date.+ """+ start_date = self.start_date+ if start_date is None or not read_activity_log:+ return start_date+ # A launch logs the start date that it sets on a draft. An experiment created with a start date logs none, and+ # its start date stands.+ try:+ logged = (+ ActivityLog.objects.filter(+ team_id=self.team_id,+ scope="Experiment",+ item_id=str(self.id),+ activity="updated",+ detail__contains={"changes": [{"field": "start_date", "before": None}]},+ )+ .order_by("-created_at")+ .values_list("created_at", flat=True)+ .first()+ )+ except Exception as error:+ # The start date is a safe fallback, so a failed lookup must not fail the caller.+ capture_exception(error)+ return start_date+ return start_date if logged is None or logged < start_date else logged++ def hours_since_launch(self, at: datetime | None = None, *, read_activity_log: bool) -> float | None:+ """The hours from `launched_at` to `at`, or to now."""+ launched_at = self.launched_at(read_activity_log=read_activity_log)+ if launched_at is None:+ return None+ # Counts to now also after the end date.+ return ((at or timezone.now()) - launched_at).total_seconds() / 3600+@propertydef is_paused(self) -> bool:# Pause is not stored on the experiment — it is the running state with the linked flag deactivated.diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex df7f573431f6..d48695fd2520 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -3426,7 +3426,9 @@ class ExperimentHealthInputsFlagHistorySerializer(serializers.Serializer):"'exposure_filters', 'exposure_action' or 'exposure_criteria'. Null when they were."),)- launched_at = serializers.DateTimeField(help_text="When the experiment launched.")+ start_date = serializers.DateTimeField(+ help_text="The experiment's start date. The flag history counts changes from it, as the results count exposures from it."+ )team_timezone = serializers.CharField(help_text="The project's time zone, which the findings use for times.")changes = ExperimentHealthInputsFlagChangeSerializer(many=True,diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 8d6676a09ad5..e08d13654e40 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -415,10 +415,10 @@ def _capture_results_refresh_completed(update: RecalculationProgressUpdate) -> Nif recalc.started_at and recalc.created_atelse None)- # Hours since the experiment launched, matching the legacy frontend definition exactly+ # Hours since the start date, matching the legacy frontend definition exactly# (now - start_date, ignoring end_date) so dashboards can share the >12h filter across paths.- hours_since_launch = experiment.hours_since_launch- experiment_duration_hours = round(hours_since_launch) if hours_since_launch is not None else None+ hours_since_start = experiment.hours_since_start+ experiment_duration_hours = round(hours_since_start) if hours_since_start is not None else None# Count from the discovery list that also sets total_metrics, so saved metrics count and legacy# metrics that the run never calculates do not.roles = [metric.role for metric in get_metrics_for_calculation(experiment)]diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 7e6ef03896f0..3086311f3916 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -3624,8 +3624,8 @@ export interface ExperimentHealthInputsFlagHistoryApi {* @nullable*/not_checked_reason: string | null- /** When the experiment launched. */- launched_at: string+ /** The experiment's start date. The flag history counts changes from it, as the results count exposures from it. */+ start_date: string/** The project's time zone, which the findings use for times. */team_timezone: string/** Every change since launch that can move exposed people, of every kind, in time order. A bucketing change is one per setting and save. A rollout change alone is no release-condition change. Empty for 'no_history_access', which does not read them. */diff --git a/products/experiments/frontend/health/debug/healthDebugInputs.ts b/products/experiments/frontend/health/debug/healthDebugInputs.tsindex 62652c0a33d6..a2d666754d46 100644--- a/products/experiments/frontend/health/debug/healthDebugInputs.ts+++ b/products/experiments/frontend/health/debug/healthDebugInputs.ts@@ -216,7 +216,7 @@ export function buildFlagHistoryFacts(state: HealthInputsState): SetupFact[] {help: 'The flag-change checks compare the changes with the exposures only for an exposure event without property filters. Every change counts from the first one, of any kind, with an exposure before it.',},...(history- ? [{ label: 'Launched at', value: `${formatTimestamp(history.launched_at)} (${history.team_timezone})` }]+ ? [{ label: 'Start date', value: `${formatTimestamp(history.start_date)} (${history.team_timezone})` }]: []),...(hasCountedChange && history? [diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0c6ecdb75bfa..f959ff134e6e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -44846,8 +44846,8 @@ export namespace Schemas {* @nullable*/not_checked_reason: string | null;- /** When the experiment launched. */- launched_at: string;+ /** The experiment's start date. The flag history counts changes from it, as the results count exposures from it. */+ start_date: string;/** The project's time zone, which the findings use for times. */team_timezone: string;/** Every change since launch that can move exposed people, of every kind, in time order. A bucketing change is one per setting and save. A rollout change alone is no release-condition change. Empty for 'no_history_access', which does not read them. */