Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(experiments): name the cause of zero exposures (#121107)

Marcel Poelkere091995093a6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 48e65a85ddce..ff89b3a830d5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10835,9 +10835,9 @@ snapshots:
scenes-app-experiments--experiment-frequentist-two-variants--light:
hash: v1.k794b7964.4ddea1c7537af9d50c57b4b9a76d4bcba39f743a23b4715683c0ce59d4c24f57.0ueR8XMLqRby_u6I0EyNIiUwXkbjmWMH3vBdoFNYmII
scenes-app-experiments--experiment-health-debug-tab--dark:
- hash: v1.k794b7964.5cc5e86e5c2379904d044c54858ac88f2b864584975e9ac75bc4c9cc55499be7.n1wcGp5JgWshP7nhURz-X-LyFqi7Ht2RXc6qOq5hLuc
+ hash: v1.k794b7964.91ba56f50391aab86778f2933317b208ffac976d4ec78239c0a09d724a61b789.ftlKzczALPofIwcDj3S9xS5DI8IZ-VPywrNrFPJw8ow
scenes-app-experiments--experiment-health-debug-tab--light:
- hash: v1.k794b7964.e7ed4da61b907080726cd60bb44f0253ff715e9ec2ae314ebea1d0537218ccf7.DSB70UsaEOYBs_2j-uGHqfeD99JRnVFpUbPAfPg81UY
+ hash: v1.k794b7964.ce981e71594609f8b54d3f248837db9ec8ed3352af2bdd8f910f1711e6030a2f.oQwgMeJDgn3NeL_yaRCldOooFmYBBYz0PNVbQvA5STg
scenes-app-experiments--experiment-recordings-dropped-metric--dark:
hash: v1.k794b7964.e0e7181f2c9e61a8324eff9aa7a9230fef25b3cf37e0b24ef875780186ed25dc.9VEvZ4iVieVJwmDol0gwtAsr3wgZYW5gj2KXAGZJfiw
scenes-app-experiments--experiment-recordings-dropped-metric--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index f872347a4720..b5e65e99fb61 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -25641,7 +25641,7 @@
"type": "object"
},
"ExperimentExposureHealthFindingActionKind": {
- "enum": ["edit_exposure_criteria", "adjust_distribution", "use_first_seen_variant"],
+ "enum": ["open_feature_flag", "edit_exposure_criteria", "adjust_distribution", "use_first_seen_variant"],
"type": "string"
},
"ExperimentExposureHealthFindingCode": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 1cc99f7d43ef..d388d761421d 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -6322,6 +6322,7 @@ export type ExperimentExposureHealthFindingCode =
export type ExperimentExposureHealthFindingSeverity = 'critical' | 'warning' | 'info'
export type ExperimentExposureHealthFindingActionKind =
+ | 'open_feature_flag'
| 'edit_exposure_criteria'
| 'adjust_distribution'
| 'use_first_seen_variant'
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index ea29b31a63f3..c25e3093305b 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -133,7 +133,12 @@ describe('experimentLogic', () => {
bias_risk: { multiple_variant_percentage: 5 },
health_findings: [{ code: 'srm' }, { code: 'bias_risk_multiple_excluded' }],
}
- const noServerVerdicts = { srm_server: null, zero_exposures_server: null, bias_risk_server: null }
+ const noServerVerdicts = {
+ srm_server: null,
+ zero_exposures_server: null,
+ zero_exposures_cause: null,
+ bias_risk_server: null,
+ }
it.each([
{
@@ -198,10 +203,15 @@ describe('experimentLogic', () => {
exposures: {
timeseries: [{ variant: 'control' }, { variant: 'test' }],
total_exposures: { control: 0, test: 0 },
- health_findings: [{ code: 'zero_exposures' }],
+ health_findings: [{ code: 'zero_exposures', subcode: 'flag_not_called' }],
},
handling: undefined,
- expected: { health_ui: 'warnings', exposures_total: 0, zero_exposures_server: true },
+ expected: {
+ health_ui: 'warnings',
+ exposures_total: 0,
+ zero_exposures_server: true,
+ zero_exposures_cause: 'flag_not_called',
+ },
},
])(
'reports the exposure state with the completed refresh: $desc',
diff --git a/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx
index e1aab1cbeaf3..7473e7ba87f5 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx
@@ -67,6 +67,16 @@ const HEALTH_INPUTS: ExperimentHealthInputsApi = {
variants: SPLIT_AFTER,
split_text: 'control 34%, test-1 33%, test-2 33%',
},
+ flag_last_called_at: '2025-05-21T09:12:00Z',
+ flag_called: true,
+ flag_called_during_run: true,
+ exposure_events: {
+ custom_event: null,
+ required_flag_key: 'experiment-with-mean-metric',
+ variant_property: '$feature_flag_response',
+ activation: null,
+ },
+ events_received: {},
flag_history: {
checked: true,
not_checked_reason: null,
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 5f8eecd6ee28..ac75d813268c 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1454,6 +1454,7 @@ class ExperimentExposureHealthCheckStatus(StrEnum):
class ExperimentExposureHealthFindingActionKind(StrEnum):
+ OPEN_FEATURE_FLAG = "open_feature_flag"
EDIT_EXPOSURE_CRITERIA = "edit_exposure_criteria"
ADJUST_DISTRIBUTION = "adjust_distribution"
USE_FIRST_SEEN_VARIANT = "use_first_seen_variant"
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index c40cf012d913..c51613d5ad41 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -10292,6 +10292,7 @@ export namespace Schemas {
status: ExperimentExposureHealthCheckStatus;
};
export type ExperimentExposureHealthFindingActionKind =
+ | "open_feature_flag"
| "edit_exposure_criteria"
| "adjust_distribution"
| "use_first_seen_variant";
diff --git a/products/experiments/backend/health/checks/events_received.py b/products/experiments/backend/health/checks/events_received.py
index 26ad2323cbb4..b801cbc30fac 100644
--- a/products/experiments/backend/health/checks/events_received.py
+++ b/products/experiments/backend/health/checks/events_received.py
@@ -8,8 +8,8 @@ normal: the code that sends the event often ships with the launch.
from collections.abc import Sequence
from products.experiments.backend.facade.contracts import ExperimentHealthFindingSeverity
-from products.experiments.backend.health.checks.zero_exposures import ZERO_EXPOSURES_GRACE_HOURS
from products.experiments.backend.health.context import HealthContext
+from products.experiments.backend.health.delays import ZERO_EXPOSURES_GRACE_HOURS
def not_received_severity(ctx: HealthContext, *, affects_results: bool) -> ExperimentHealthFindingSeverity:
diff --git a/products/experiments/backend/health/checks/new_flag_no_traffic.py b/products/experiments/backend/health/checks/new_flag_no_traffic.py
index b565c2a4d4da..14c2b345047c 100644
--- a/products/experiments/backend/health/checks/new_flag_no_traffic.py
+++ b/products/experiments/backend/health/checks/new_flag_no_traffic.py
@@ -12,6 +12,7 @@ from products.experiments.backend.facade.contracts import (
ExperimentHealthFindingSeverity,
)
from products.experiments.backend.health.context import HealthContext
+from products.experiments.backend.health.delays import LAST_CALLED_AT_LAG
from products.experiments.backend.health.skips import (
FLAG_DELETED,
NO_FLAG,
@@ -22,11 +23,6 @@ from products.experiments.backend.health.skips import (
not_checked,
)
-# `last_called_at` moves only when `sync_feature_flag_last_called` runs, every 30 minutes (`posthog/tasks/scheduled.py`).
-# A run reads the calls up to a buffer before its start (`FEATURE_FLAG_LAST_CALLED_AT_SYNC_*_BUFFER_SECONDS`, 1 or 6
-# minutes by default), so a call waits up to one interval plus that buffer. Update this when the schedule changes.
-LAST_CALLED_AT_LAG = "an hour"
-
def new_flag_no_traffic_skip(ctx: HealthContext) -> CheckSkip | None:
if ctx.archived:
diff --git a/products/experiments/backend/health/checks/zero_exposures.py b/products/experiments/backend/health/checks/zero_exposures.py
index d3b772d3b802..de6d1de028d8 100644
--- a/products/experiments/backend/health/checks/zero_exposures.py
+++ b/products/experiments/backend/health/checks/zero_exposures.py
@@ -4,11 +4,16 @@ from products.experiments.backend.facade.contracts import (
ExperimentHealthFindingCode,
ExperimentHealthFindingSeverity,
)
+from products.experiments.backend.health.checks.exposure_criteria import exposure_criteria_cannot_match
from products.experiments.backend.health.context import HealthContext
+from products.experiments.backend.health.delays import LAST_CALLED_AT_LAG, ZERO_EXPOSURES_GRACE_HOURS
from products.experiments.backend.health.skips import RUNS_AFTER_LAUNCH, CheckSkip, not_applicable
-# A new experiment often has no exposure in its first hours, so the finding waits as long as the experiments scout does.
-ZERO_EXPOSURES_GRACE_HOURS = 24
+# pinned: the subcodes are sent as `finding_variant` on the health finding events, so insights group on them.
+EXPERIMENT_PAUSED = "experiment_paused"
+FLAG_NOT_CALLED = "flag_not_called"
+CALLS_NOT_COUNTED = "calls_not_counted"
+CUSTOM_EXPOSURE_NOT_MATCHED = "custom_exposure_not_matched"
def zero_exposures_skip(ctx: HealthContext) -> CheckSkip | None:
@@ -17,6 +22,8 @@ def zero_exposures_skip(ctx: HealthContext) -> CheckSkip | None:
return not_applicable(RUNS_AFTER_LAUNCH)
if exposures.hours_since_launch < ZERO_EXPOSURES_GRACE_HOURS:
return not_applicable(f"Runs {ZERO_EXPOSURES_GRACE_HOURS} hours after launch")
+ if exposure_criteria_cannot_match(ctx) is not None:
+ return not_applicable("The exposure criteria check reports why no users are exposed")
return None
@@ -26,17 +33,125 @@ def zero_exposures(ctx: HealthContext) -> ExperimentHealthFinding | None:
return None
if exposures.hours_since_launch < ZERO_EXPOSURES_GRACE_HOURS or sum(exposures.total_exposures.values()) > 0:
return None
- return ExperimentHealthFinding(
- code=ExperimentHealthFindingCode.ZERO_EXPOSURES,
+ # Criteria that no event can match leave nobody exposed, and the exposure criteria check names that cause. This
+ # check calls it rather than repeating its rules, so exactly one of the two reports the experiment.
+ if exposure_criteria_cannot_match(ctx) is not None:
+ return None
+ evidence = {"hours_since_launch": int(exposures.hours_since_launch)}
+ # A group experiment counts groups, by the rule the exposure query uses.
+ unit = "group" if exposures.counts_groups else "user"
+ # The cause reads the flag besides the cached exposure answer. The page recomputes that answer on each load while it
+ # holds fewer than 50 exposures, so the cause is as fresh as the zero.
+ flag = ctx.flag
+ # Deleting a flag changes its key, so its calls stop moving `last_called_at`. The flag-state check reports the
+ # deletion.
+ if flag is None or flag.deleted:
+ return _cause_unknown(evidence, unit)
+ if ctx.is_paused:
+ return _finding(
+ subcode=EXPERIMENT_PAUSED,
+ title=f"No {unit}s exposed: the experiment is paused",
+ detail=(
+ "The experiment is paused, so its feature flag serves no variants and nobody is counted as exposed. "
+ f"Resume the experiment to expose {unit}s."
+ ),
+ evidence=evidence,
+ actions=(),
+ )
+ events = ctx.exposure_events
+ if events is None:
+ return _cause_unknown(evidence, unit)
+ if events.required_flag_key is None:
+ # A custom event or an action carries the variant in a property that client SDKs add to every event, so the
+ # flag's calls say nothing about these exposures.
+ sender = "a member sends" if unit == "group" else "they send"
+ if events.custom_event is not None:
+ counted = f'{sender} the event "{events.custom_event}"'
+ else:
+ counted = f"{sender} an event that matches the exposure action"
+ return _finding(
+ subcode=CUSTOM_EXPOSURE_NOT_MATCHED,
+ title=f"No {unit}s exposed: no events match the exposure criteria",
+ detail=(
+ f"{unit.capitalize()}s are counted as exposed when {counted} with one of the experiment's variants in "
+ f'the property "{events.variant_property}". No event has matched during the experiment, so nobody is '
+ "counted. Check that your code sends the event with the variant, and that the exposure criteria, such "
+ f"as the test account filter, don't leave out your {unit}s."
+ ),
+ evidence=evidence,
+ actions=(ExperimentHealthFindingActionKind.EDIT_EXPOSURE_CRITERIA,),
+ )
+ flag_key = events.required_flag_key
+ if ctx.flag_called_during_run is False:
+ return _finding(
+ subcode=FLAG_NOT_CALLED,
+ title=f"No {unit}s exposed: the feature flag has no recorded calls",
+ detail=(
+ f'PostHog hasn\'t recorded a call of the feature flag "{flag_key}" during the experiment, so nobody is '
+ f"counted as exposed. {unit.capitalize()}s are counted when your code reads this flag's value, for "
+ "example with getFeatureFlag in the browser or with get_flag on the result of evaluate_flags in Python. "
+ "Reading only a payload or a list of all flags records no call, and neither does a call with "
+ f"send_event set to false. New calls can take up to {LAST_CALLED_AT_LAG} to show up here."
+ ),
+ evidence=evidence,
+ actions=(),
+ )
+ if ctx.flag_called_during_run is True:
+ # Calls made before the group is set carry no group key, and the exposure query drops them.
+ groups = " A call counts only when it carries the group, so set the group before your code reads the flag."
+ activation = (
+ f' With the activation "{events.activation}" set, a {unit} also needs a matching event after the flag call.'
+ if events.activation
+ else ""
+ )
+ return _finding(
+ subcode=CALLS_NOT_COUNTED,
+ title=f"No {unit}s exposed, although the feature flag is called",
+ detail=(
+ f'PostHog has recorded calls of the feature flag "{flag_key}" during the experiment, but none of them '
+ "counts as an exposure. A call counts when the flag returns one of the experiment's variants and the "
+ f"{unit} passes the exposure criteria.{groups if unit == 'group' else ''}{activation} Check that the "
+ f"flag's release conditions include your {unit}s, and that the exposure criteria, such as the test "
+ "account filter, don't leave them out."
+ ),
+ evidence=evidence,
+ actions=(
+ ExperimentHealthFindingActionKind.OPEN_FEATURE_FLAG,
+ ExperimentHealthFindingActionKind.EDIT_EXPOSURE_CRITERIA,
+ ),
+ )
+ return _cause_unknown(evidence, unit)
+
+
+def _cause_unknown(evidence: dict[str, int], unit: str) -> ExperimentHealthFinding:
+ return _finding(
subcode=None,
- severity=ExperimentHealthFindingSeverity.WARNING,
- title="No users exposed",
+ title=f"No {unit}s exposed",
detail=(
- "No users have been exposed to this experiment, so it shows no results. "
- "Users are counted when the exposure event is sent for them. Check that your code evaluates "
- "the linked feature flag and that the exposure criteria match the events you send."
+ f"No {unit}s have been exposed to this experiment, so it shows no results. "
+ f"{unit.capitalize()}s are counted when the exposure event is sent for them. Check that your code "
+ "evaluates the linked feature flag and that the exposure criteria match the events you send."
),
- evidence={"hours_since_launch": int(exposures.hours_since_launch)},
+ evidence=evidence,
actions=(ExperimentHealthFindingActionKind.EDIT_EXPOSURE_CRITERIA,),
+ )
+
+
+def _finding(
+ *,
+ subcode: str | None,
+ title: str,
+ detail: str,
+ evidence: dict[str, int],
+ actions: tuple[ExperimentHealthFindingActionKind, ...],
+) -> ExperimentHealthFinding:
+ return ExperimentHealthFinding(
+ code=ExperimentHealthFindingCode.ZERO_EXPOSURES,
+ subcode=subcode,
+ severity=ExperimentHealthFindingSeverity.WARNING,
+ title=title,
+ detail=detail,
+ evidence=evidence,
+ actions=actions,
diagnostic_ref=None,
)
diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.py
index aa537c7612e7..6d494794a708 100644
--- a/products/experiments/backend/health/context.py
+++ b/products/experiments/backend/health/context.py
@@ -8,7 +8,13 @@ from django.utils import timezone
import pydantic
-from posthog.schema import EventPropertyFilter, ExperimentEventExposureConfig, MultipleVariantHandling, PropertyOperator
+from posthog.schema import (
+ ActionsNode,
+ EventPropertyFilter,
+ ExperimentEventExposureConfig,
+ MultipleVariantHandling,
+ PropertyOperator,
+)
from posthog.dataclasses import frozen
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -19,6 +25,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
DEFAULT_EXPOSURE_EVENT,
EXPERIMENT_EXPOSURE_EVENT,
get_exposure_event_and_property,
+ has_activation_config,
normalize_to_exposure_criteria,
)
from products.experiments.backend.metric_resolution import MetricRole, saved_metric_link_role, saved_metric_links
@@ -274,7 +281,13 @@ class ExposureEvents:
# The flag key that the exposure query requires in `$feature_flag`, because the flag call events are not specific
# to one flag. None when the criteria count a custom event or an action, and when the experiment has no flag.
required_flag_key: str | None
+ # The event property that holds the variant: `$feature_flag_response` on the flag call events, `$feature/<flag key>`
+ # on a custom event or the events of an action.
+ variant_property: str
flag_key_filters: tuple[FlagKeyFilter, ...]
+ # The event, or the action's name, that has to follow a user's flag call before the user counts. None without an
+ # activation, which the exposure query reads only next to the flag call events.
+ activation: str | None = None
@frozen
@@ -290,6 +303,11 @@ class HealthContext:
# Whether PostHog has recorded a call of the flag. None when the experiment has no flag, or when PostHog can't
# record the calls of this organization's flags.
flag_called: bool | None
+ # Whether PostHog has recorded a call of the flag between launch and the end, or until now while the experiment
+ # runs. A flag that served an earlier experiment can carry only calls from before launch, so `flag_called` doesn't
+ # answer this. None before launch, when the experiment has no flag, when the flag's latest call came after the
+ # end, or when PostHog can't record the calls of this organization's flags.
+ flag_called_during_run: bool | None
# Whether the team has an active flag, which posthog-js needs to request flags on page load. None when not read:
# it is read only for a draft whose flag has no recorded call.
team_has_active_flag: bool | None
@@ -437,16 +455,32 @@ def _flag_called(experiment: Experiment) -> bool | None:
return None
if experiment.feature_flag.last_called_at is not None:
return True
+ return None if _flag_calls_unrecorded(experiment) else False
+
+
+def _flag_called_during_run(experiment: Experiment, flag_called: bool | None) -> bool | None:
+ start_date = experiment.start_date
+ if start_date is None or flag_called is None:
+ return None
+ if flag_called is False:
+ return False
+ last_called_at = experiment.feature_flag.last_called_at
+ if last_called_at is not None and last_called_at >= start_date:
+ # `last_called_at` holds only the latest call, so a call after the end hides whether any came during the run.
+ end_date = experiment.end_date
+ return True if end_date is None or last_called_at <= end_date else None
+ return None if _flag_calls_unrecorded(experiment) else False
+
+
+def _flag_calls_unrecorded(experiment: Experiment) -> bool:
# The task that sets `last_called_at` reads `$feature_flag_called` from the events table, unless it is set to
# read flag_evaluations. On FLAG_EVALUATIONS_ONLY, ingestion writes no `$feature_flag_called` to the events table
# for the teams in its allowlist, which this side can't read. Their flags keep no `last_called_at` however often
# they are called.
- if settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE != "flag_evaluations" and (
+ return settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE != "flag_evaluations" and (
get_organization_flag_evaluations_mode(experiment.team.organization_id)
== FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY
- ):
- return None
- return False
+ )
def _metric_events(experiment: Experiment, links: list[ExperimentToSavedMetric]) -> tuple[MetricEvents, ...]:
@@ -471,23 +505,35 @@ def _exposure_events(experiment: Experiment) -> ExposureEvents | None:
criteria = normalize_to_exposure_criteria(experiment.exposure_criteria)
except pydantic.ValidationError:
return None
- flag_key = experiment.feature_flag.key if experiment.feature_flag_id else None
- event, _ = get_exposure_event_and_property(flag_key or "", criteria, default_exposure_event=DEFAULT_EXPOSURE_EVENT)
+ # A deleted flag carries a tombstone in its key, and the exposure query reads the key without it.
+ flag_key = experiment.feature_flag.key_without_tombstone() if experiment.feature_flag_id else None
+ event, variant_property = get_exposure_event_and_property(
+ flag_key or "", criteria, default_exposure_event=DEFAULT_EXPOSURE_EVENT
+ )
reads_flag_calls = event in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT)
config = criteria.exposure_config if criteria else None
properties = config.properties if isinstance(config, ExperimentEventExposureConfig) else []
+ activation = criteria.activation_config if criteria and has_activation_config(criteria) else None
return ExposureEvents(
custom_event=event if event is not None and not reads_flag_calls else None,
required_flag_key=flag_key if reads_flag_calls else None,
+ variant_property=variant_property,
flag_key_filters=tuple(
# The exposure query reads a filter without an operator as `exact`, as `property_to_expr` does.
FlagKeyFilter(operator=prop.operator or PropertyOperator.EXACT, values=_filter_values(prop.value))
for prop in properties
if isinstance(prop, EventPropertyFilter) and prop.key == "$feature_flag"
),
+ activation=_activation_name(activation) if activation else None,
)
+def _activation_name(activation: ExperimentEventExposureConfig | ActionsNode) -> str:
+ if isinstance(activation, ExperimentEventExposureConfig):
+ return activation.event
+ return activation.name or f"action {activation.id}"
+
+
def _filter_values(value: list[str | float | bool] | str | float | bool | None) -> tuple[str | float | bool, ...]:
if isinstance(value, list):
return tuple(value)
@@ -574,6 +620,7 @@ def load_health_context(
archived=experiment.archived,
flag=_load_flag_state(experiment),
flag_called=flag_called,
+ flag_called_during_run=_flag_called_during_run(experiment, flag_called),
team_has_active_flag=(
has_active_flags(experiment.team) if flag_called is False and not experiment.is_launched else None
),
diff --git a/products/experiments/backend/health/delays.py b/products/experiments/backend/health/delays.py
new file mode 100644
index 000000000000..8d01b4378868
--- /dev/null
+++ b/products/experiments/backend/health/delays.py
@@ -0,0 +1,8 @@
+# A new experiment often has no exposure in its first hours, so the zero exposures finding waits as long as the
+# experiments scout does.
+ZERO_EXPOSURES_GRACE_HOURS = 24
+
+# `last_called_at` moves only when `sync_feature_flag_last_called` runs, every 30 minutes (`posthog/tasks/scheduled.py`).
+# A run reads the calls up to a buffer before its start (`FEATURE_FLAG_LAST_CALLED_AT_SYNC_*_BUFFER_SECONDS`, 1 or 6
+# minutes by default), so a call waits up to one interval plus that buffer. Update this when the schedule changes.
+LAST_CALLED_AT_LAG = "an hour"
diff --git a/products/experiments/backend/health/inputs_payload.py b/products/experiments/backend/health/inputs_payload.py
index b3bbc8ccb00c..36bba862a499 100644
--- a/products/experiments/backend/health/inputs_payload.py
+++ b/products/experiments/backend/health/inputs_payload.py
@@ -218,6 +218,18 @@ def health_inputs_payload(inputs: HealthInputs) -> dict[str, Any]:
"primary_metric_count": ctx.primary_metric_count,
"secondary_metric_count": ctx.secondary_metric_count,
"flag": _health_inputs_flag(ctx.flag) if ctx.flag else None,
+ "flag_last_called_at": inputs.flag_last_called_at,
+ "flag_called": ctx.flag_called,
+ "flag_called_during_run": ctx.flag_called_during_run,
+ "exposure_events": {
+ "custom_event": ctx.exposure_events.custom_event,
+ "required_flag_key": ctx.exposure_events.required_flag_key,
+ "variant_property": ctx.exposure_events.variant_property,
+ "activation": ctx.exposure_events.activation,
+ }
+ if ctx.exposure_events
+ else None,
+ "events_received": dict(ctx.events_received),
"flag_history": _health_inputs_flag_history(ctx.flag_history) if ctx.flag_history else None,
"condition_set_traffic_status": _health_inputs_traffic_status(inputs),
"condition_set_traffic": _health_inputs_traffic(ctx.condition_set_traffic)
diff --git a/products/experiments/backend/health/loader.py b/products/experiments/backend/health/loader.py
index 132d68a207e9..c894b7fb5b3f 100644
--- a/products/experiments/backend/health/loader.py
+++ b/products/experiments/backend/health/loader.py
@@ -1,4 +1,5 @@
from dataclasses import replace
+from datetime import datetime
from posthog.dataclasses import frozen
from posthog.models.user import User
@@ -23,6 +24,8 @@ class HealthInputs:
reader_access: ExperimentHealthReaderAccess
# None when the experiment has no flag, or the flag has no version.
flag_version: int | None
+ # The flag's latest recorded call. None when the experiment has no flag, or the flag has no recorded call.
+ flag_last_called_at: datetime | None
project: ProjectSetupFacts
@@ -43,6 +46,7 @@ def load_experiment_health_inputs(
exposures=load_exposure_inputs(experiment, user=user, can_query_events=reader_access.can_query_events),
reader_access=reader_access,
flag_version=experiment.feature_flag.version if experiment.feature_flag_id else None,
+ flag_last_called_at=experiment.feature_flag.last_called_at if experiment.feature_flag_id else None,
project=build_project_setup_facts(
experiment.team,
can_query_events=reader_access.can_query_events,
diff --git a/products/experiments/backend/health/test/factories.py b/products/experiments/backend/health/test/factories.py
index 7bddcc2fa2e4..8e32e3ae975a 100644
--- a/products/experiments/backend/health/test/factories.py
+++ b/products/experiments/backend/health/test/factories.py
@@ -24,13 +24,16 @@ RUNNING_CONTEXT = HealthContext(
archived=False,
flag=None,
flag_called=None,
+ flag_called_during_run=None,
team_has_active_flag=None,
baseline_variant_key=None,
primary_metric_count=1,
secondary_metric_count=0,
hours_since_launch=72,
metric_events=(),
- exposure_events=ExposureEvents(custom_event=None, required_flag_key="flag", flag_key_filters=()),
+ exposure_events=ExposureEvents(
+ custom_event=None, required_flag_key="flag", variant_property="$feature_flag_response", flag_key_filters=()
+ ),
events_received={},
exposures=None,
flag_history=None,
diff --git a/products/experiments/backend/health/test/test_events_received.py b/products/experiments/backend/health/test/test_events_received.py
index 71afde9cf034..e8acd06b38f0 100644
--- a/products/experiments/backend/health/test/test_events_received.py
+++ b/products/experiments/backend/health/test/test_events_received.py
@@ -120,6 +120,30 @@ class TestEventsReceived(BaseTest):
self.assertEqual((exposure.subcode, dict(exposure.evidence)), expected_exposure)
self.assertEqual(exposure.severity, WARNING)
+ def test_a_filter_on_a_deleted_flags_own_key_can_match(self) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, key="checkout-test", created_by=self.user)
+ flag.key, flag.deleted = flag.tombstoned_key(), True
+ flag.save()
+ experiment = Experiment.objects.create(
+ team=self.team,
+ name="Checkout",
+ feature_flag=flag,
+ start_date=timezone.now() - timedelta(days=2),
+ exposure_criteria={
+ "exposure_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "$feature_flag_called",
+ "properties": [
+ {"key": "$feature_flag", "type": "event", "value": ["checkout-test"], "operator": "exact"}
+ ],
+ }
+ },
+ )
+
+ health = get_experiment_health(team_id=self.team.id, experiment_id=experiment.id, reader_access=NO_QUERIES)
+
+ self.assertNotIn(Code.EXPOSURE_CRITERIA_CANNOT_MATCH, {finding.code for finding in health.findings})
+
def test_shared_metrics_add_no_queries(self) -> None:
flag = FeatureFlag.objects.create(team=self.team, key="checkout-test", created_by=self.user)
experiment = Experiment.objects.create(team=self.team, name="Checkout", feature_flag=flag)
diff --git a/products/experiments/backend/health/test/test_exposure_criteria.py b/products/experiments/backend/health/test/test_exposure_criteria.py
index ec32774cae6d..d5cf19100673 100644
--- a/products/experiments/backend/health/test/test_exposure_criteria.py
+++ b/products/experiments/backend/health/test/test_exposure_criteria.py
@@ -24,13 +24,19 @@ def _flag_filter(*values: str | float | bool, operator: PropertyOperator = EXACT
events = ExposureEvents(
custom_event=None,
required_flag_key="checkout-test",
+ variant_property="$feature_flag_response",
flag_key_filters=(FlagKeyFilter(operator=operator, values=values),),
)
return replace(RUNNING_CONTEXT, exposure_events=events, **changes)
def _custom_event(received: dict[str, bool], **changes: Any) -> HealthContext:
- events = ExposureEvents(custom_event="checkout_viewed", required_flag_key=None, flag_key_filters=())
+ events = ExposureEvents(
+ custom_event="checkout_viewed",
+ required_flag_key=None,
+ variant_property="$feature/checkout-test",
+ flag_key_filters=(),
+ )
return replace(RUNNING_CONTEXT, exposure_events=events, events_received=received, **changes)
diff --git a/products/experiments/backend/health/test/test_registry.py b/products/experiments/backend/health/test/test_registry.py
index 03c8023826f4..022ed531a49e 100644
--- a/products/experiments/backend/health/test/test_registry.py
+++ b/products/experiments/backend/health/test/test_registry.py
@@ -7,7 +7,7 @@ from unittest.mock import patch
from parameterized import parameterized
-from posthog.schema import MultipleVariantHandling
+from posthog.schema import MultipleVariantHandling, PropertyOperator
from products.experiments.backend.facade.contracts import (
ExperimentHealthCheckKey,
@@ -19,6 +19,7 @@ from products.experiments.backend.health.context import (
ExposureEvents,
ExposureTotals,
FlagHistoryNotCheckedReason,
+ FlagKeyFilter,
FlagState,
FlagVariant,
HealthContext,
@@ -67,7 +68,9 @@ EVENT_KEYS = (Key.METRIC_EVENT_NOT_INGESTED, Key.EXPOSURE_CRITERIA_CANNOT_MATCH)
def _events(name: str, received: dict[str, bool]) -> dict[str, Any]:
return {
"metric_events": (MetricEvents(name="Metric", role="primary", events=(name,)),),
- "exposure_events": ExposureEvents(custom_event=name, required_flag_key=None, flag_key_filters=()),
+ "exposure_events": ExposureEvents(
+ custom_event=name, required_flag_key=None, variant_property="$feature/flag", flag_key_filters=()
+ ),
"events_received": received,
}
@@ -271,6 +274,57 @@ class TestEvaluate(TestCase):
self.assertEqual([finding.title for finding in health.findings], [title])
+ @parameterized.expand(
+ [
+ (
+ "exposure_event_never_received",
+ _events("checkout_viewed", {"checkout_viewed": False}),
+ ExperimentHealthFindingCode.EXPOSURE_CRITERIA_CANNOT_MATCH,
+ ),
+ (
+ "filter_on_another_flag",
+ {
+ "exposure_events": ExposureEvents(
+ custom_event=None,
+ required_flag_key="checkout-test",
+ variant_property="$feature_flag_response",
+ flag_key_filters=(FlagKeyFilter(operator=PropertyOperator.EXACT, values=("pricing-test",)),),
+ )
+ },
+ ExperimentHealthFindingCode.EXPOSURE_CRITERIA_CANNOT_MATCH,
+ ),
+ (
+ "exposure_event_never_received_after_the_end",
+ {**_events("checkout_viewed", {"checkout_viewed": False}), **ENDED},
+ ExperimentHealthFindingCode.ZERO_EXPOSURES,
+ ),
+ (
+ "exposure_event_received",
+ _events("checkout_viewed", {"checkout_viewed": True}),
+ ExperimentHealthFindingCode.ZERO_EXPOSURES,
+ ),
+ ]
+ )
+ def test_one_check_reports_an_experiment_without_exposures(
+ self, _name: str, changes: dict[str, Any], expected: ExperimentHealthFindingCode
+ ) -> None:
+ ctx = replace(RUNNING_CONTEXT, flag=EVEN_SPLIT_FLAG, exposures=replace(NO_EXPOSURES, hours_since_launch=48))
+
+ health = evaluate(replace(ctx, **changes), (*EXPERIMENT_HEALTH_CHECKS, *EXPOSURE_HEALTH_CHECKS))
+
+ reporting = {finding.code for finding in health.findings} & {
+ ExperimentHealthFindingCode.ZERO_EXPOSURES,
+ ExperimentHealthFindingCode.EXPOSURE_CRITERIA_CANNOT_MATCH,
+ }
+ zero_exposures = next(check for check in health.checks if check.key == Key.ZERO_EXPOSURES)
+ self.assertEqual(
+ (reporting, zero_exposures.status),
+ (
+ {expected},
+ Status.FINDING if expected == ExperimentHealthFindingCode.ZERO_EXPOSURES else Status.NOT_APPLICABLE,
+ ),
+ )
+
def test_a_failing_check_does_not_hide_the_other_findings(self) -> None:
with patch.object(registry, "capture_exception") as capture:
health = evaluate(RUNNING_UNEVEN_SPLIT, (FAILING_CHECK, *EXPOSURE_HEALTH_CHECKS))
diff --git a/products/experiments/backend/health/test/test_zero_exposures.py b/products/experiments/backend/health/test/test_zero_exposures.py
new file mode 100644
index 000000000000..c0c4d0d235ae
--- /dev/null
+++ b/products/experiments/backend/health/test/test_zero_exposures.py
@@ -0,0 +1,269 @@
+from dataclasses import replace
+from datetime import UTC, datetime
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest import TestCase
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.schema import MultipleVariantHandling
+
+from products.experiments.backend.facade.contracts import ExperimentHealthFindingActionKind
+from products.experiments.backend.health.checks.zero_exposures import (
+ CALLS_NOT_COUNTED,
+ CUSTOM_EXPOSURE_NOT_MATCHED,
+ EXPERIMENT_PAUSED,
+ FLAG_NOT_CALLED,
+ zero_exposures,
+)
+from products.experiments.backend.health.context import (
+ ExposureEvents,
+ ExposureTotals,
+ FlagState,
+ FlagVariant,
+ load_health_context,
+)
+from products.experiments.backend.health.test.factories import RUNNING_CONTEXT
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
+
+Action = ExperimentHealthFindingActionKind
+
+FLAG = FlagState(
+ active=True,
+ deleted=False,
+ release_groups=(),
+ variants=(FlagVariant(key="control", rollout_percentage=50), FlagVariant(key="test", rollout_percentage=50)),
+ reachable_conditions=(),
+)
+NO_EXPOSURES = ExposureTotals(
+ total_exposures={"control": 0, "test": 0},
+ multiple_variant_handling=MultipleVariantHandling.EXCLUDE,
+ sample_ratio_mismatch_p_value=None,
+ hours_since_launch=48,
+ counts_groups=False,
+)
+FLAG_CALLS = ExposureEvents(
+ custom_event=None, required_flag_key="checkout-test", variant_property="$feature_flag_response", flag_key_filters=()
+)
+CUSTOM_EVENT = ExposureEvents(
+ custom_event="checkout_viewed",
+ required_flag_key=None,
+ variant_property="$feature/checkout-test",
+ flag_key_filters=(),
+)
+ACTION = replace(CUSTOM_EVENT, custom_event=None)
+
+LAUNCHED_AT = datetime(2026, 10, 1, tzinfo=UTC)
+ENDED_AT = datetime(2026, 10, 10, tzinfo=UTC)
+
+
+class TestZeroExposures(TestCase):
+ @parameterized.expand(
+ [
+ ("flag_not_called", {"flag_called_during_run": False}, FLAG_NOT_CALLED, ()),
+ (
+ "flag_called",
+ {"flag_called_during_run": True},
+ CALLS_NOT_COUNTED,
+ (Action.OPEN_FEATURE_FLAG, Action.EDIT_EXPOSURE_CRITERIA),
+ ),
+ ("calls_unknown", {"flag_called_during_run": None}, None, (Action.EDIT_EXPOSURE_CRITERIA,)),
+ ("paused", {"is_paused": True, "flag_called_during_run": True}, EXPERIMENT_PAUSED, ()),
+ (
+ "custom_event_whatever_the_flag_calls",
+ {"exposure_events": CUSTOM_EVENT, "flag_called_during_run": False},
+ CUSTOM_EXPOSURE_NOT_MATCHED,
+ (Action.EDIT_EXPOSURE_CRITERIA,),
+ ),
+ (
+ "action",
+ {"exposure_events": ACTION, "flag_called_during_run": False},
+ CUSTOM_EXPOSURE_NOT_MATCHED,
+ (Action.EDIT_EXPOSURE_CRITERIA,),
+ ),
+ (
+ "unreadable_criteria",
+ {"exposure_events": None, "flag_called_during_run": False},
+ None,
+ (Action.EDIT_EXPOSURE_CRITERIA,),
+ ),
+ (
+ "deleted_flag",
+ {"flag": replace(FLAG, deleted=True), "flag_called_during_run": False},
+ None,
+ (Action.EDIT_EXPOSURE_CRITERIA,),
+ ),
+ ]
+ )
+ def test_names_the_cause(
+ self, _name: str, changes: dict[str, Any], subcode: str | None, actions: tuple[Action, ...]
+ ) -> None:
+ ctx = replace(
+ RUNNING_CONTEXT, **{"flag": FLAG, "exposures": NO_EXPOSURES, "exposure_events": FLAG_CALLS, **changes}
+ )
+
+ finding = zero_exposures(ctx)
+
+ assert finding is not None
+ self.assertEqual((finding.subcode, finding.actions), (subcode, actions))
+
+ @parameterized.expand(
+ [
+ ("users", False, None, "No users exposed, although the feature flag is called", False, False),
+ ("groups", True, None, "No groups exposed, although the feature flag is called", True, False),
+ ("activation", False, "signed_up", "No users exposed, although the feature flag is called", False, True),
+ ]
+ )
+ def test_names_what_a_call_needs_to_count(
+ self,
+ _name: str,
+ counts_groups: bool,
+ activation: str | None,
+ title: str,
+ names_the_group: bool,
+ names_the_activation: bool,
+ ) -> None:
+ ctx = replace(
+ RUNNING_CONTEXT,
+ flag=FLAG,
+ exposures=replace(NO_EXPOSURES, counts_groups=counts_groups),
+ exposure_events=replace(FLAG_CALLS, activation=activation),
+ flag_called_during_run=True,
+ )
+
+ finding = zero_exposures(ctx)
+
+ assert finding is not None
+ self.assertEqual(
+ (
+ finding.title,
+ "A call counts only when it carries the group" in finding.detail,
+ 'With the activation "signed_up" set' in finding.detail,
+ ),
+ (title, names_the_group, names_the_activation),
+ )
+
+
+class TestExposureActivation(BaseTest):
+ @parameterized.expand(
+ [
+ (
+ "event",
+ {"kind": "ExperimentEventExposureConfig", "event": "signed_up", "properties": []},
+ None,
+ "signed_up",
+ ),
+ ("action", {"kind": "ActionsNode", "id": 7, "name": "Signed up"}, None, "Signed up"),
+ (
+ "ignored_next_to_a_custom_exposure_event",
+ {"kind": "ExperimentEventExposureConfig", "event": "signed_up", "properties": []},
+ {"kind": "ExperimentEventExposureConfig", "event": "checkout_viewed", "properties": []},
+ None,
+ ),
+ ]
+ )
+ def test_reads_the_activation_the_exposure_query_applies(
+ self, _name: str, activation: dict[str, Any], exposure: dict[str, Any] | None, expected: str | None
+ ) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, key="checkout-test", created_by=self.user)
+ criteria: dict[str, Any] = {"activation_config": activation}
+ if exposure is not None:
+ criteria["exposure_config"] = exposure
+ experiment = Experiment.objects.create(
+ team=self.team, name="exp", feature_flag=flag, start_date=LAUNCHED_AT, exposure_criteria=criteria
+ )
+
+ events = load_health_context(experiment).exposure_events
+
+ assert events is not None
+ self.assertEqual(events.activation, expected)
+
+
+class TestFlagCalledDuringRun(BaseTest):
+ @parameterized.expand(
+ [
+ ("never_called", LAUNCHED_AT, None, None, FlagEvaluationsMode.EVENTS, False),
+ (
+ "called_after_launch",
+ LAUNCHED_AT,
+ None,
+ datetime(2026, 10, 2, tzinfo=UTC),
+ FlagEvaluationsMode.EVENTS,
+ True,
+ ),
+ (
+ "called_before_launch_only",
+ LAUNCHED_AT,
+ None,
+ datetime(2026, 9, 1, tzinfo=UTC),
+ FlagEvaluationsMode.EVENTS,
+ False,
+ ),
+ (
+ "called_before_launch_with_calls_kept_out_of_events",
+ LAUNCHED_AT,
+ None,
+ datetime(2026, 9, 1, tzinfo=UTC),
+ FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,
+ None,
+ ),
+ (
+ "ended_called_during_the_run",
+ LAUNCHED_AT,
+ ENDED_AT,
+ datetime(2026, 10, 5, tzinfo=UTC),
+ FlagEvaluationsMode.EVENTS,
+ True,
+ ),
+ (
+ "ended_called_after_the_end",
+ LAUNCHED_AT,
+ ENDED_AT,
+ datetime(2026, 10, 15, tzinfo=UTC),
+ FlagEvaluationsMode.EVENTS,
+ None,
+ ),
+ ("draft", None, None, None, FlagEvaluationsMode.EVENTS, None),
+ ]
+ )
+ def test_reads_the_calls_during_the_run(
+ self,
+ _name: str,
+ start_date: datetime | None,
+ end_date: datetime | None,
+ last_called_at: datetime | None,
+ mode: FlagEvaluationsMode,
+ expected: bool | None,
+ ) -> None:
+ OrganizationFeatureFlagsConfig.objects.update_or_create(
+ organization=self.organization, defaults={"flag_evaluations_mode": mode}
+ )
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="checkout-test",
+ created_by=self.user,
+ last_called_at=last_called_at,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ experiment = Experiment.objects.create(
+ team=self.team, name="exp", feature_flag=flag, start_date=start_date, end_date=end_date
+ )
+
+ with override_settings(FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE="events"):
+ ctx = load_health_context(experiment)
+
+ self.assertEqual(ctx.flag_called_during_run, expected)
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.py
index 5be5b6ff3e55..60a53315356f 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
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
import time_machine
@@ -1483,13 +1483,30 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
@parameterized.expand(
[
- ("first_day", "2024-01-01T23:00:00Z", []),
- ("after_a_day", "2024-01-02T01:00:00Z", [ExperimentExposureHealthFindingCode.ZERO_EXPOSURES]),
+ ("first_day", "2024-01-01T23:00:00Z", None, []),
+ (
+ "after_a_day",
+ "2024-01-02T01:00:00Z",
+ None,
+ [(ExperimentExposureHealthFindingCode.ZERO_EXPOSURES, "flag_not_called")],
+ ),
+ (
+ "after_a_day_with_flag_calls",
+ "2024-01-02T01:00:00Z",
+ datetime(2024, 1, 1, 12, tzinfo=UTC),
+ [(ExperimentExposureHealthFindingCode.ZERO_EXPOSURES, "calls_not_counted")],
+ ),
]
)
- def test_zero_exposures_finding_waits_a_day_after_launch(
- self, _name: str, now: str, expected_codes: list[ExperimentExposureHealthFindingCode]
+ def test_zero_exposures_finding_waits_a_day_and_names_the_flag_calls(
+ self,
+ _name: str,
+ now: str,
+ last_called_at: datetime | None,
+ expected: list[tuple[ExperimentExposureHealthFindingCode, str]],
) -> None:
+ self.feature_flag.last_called_at = last_called_at
+ self.feature_flag.save()
query = ExperimentExposureQuery(
kind="ExperimentExposureQuery",
experiment_id=self.experiment.id,
@@ -1504,7 +1521,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
response = ExperimentExposuresQueryRunner(team=self.team, query=query).calculate()
self.assertEqual(response.total_exposures, {"control": 0, "test": 0})
- self.assertEqual([finding.code for finding in response.health_findings or []], expected_codes)
+ self.assertEqual([(finding.code, finding.subcode) for finding in response.health_findings or []], expected)
@parameterized.expand([("direct", False), ("precomputed", True)])
@time_machine.travel("2024-01-07T12:00:00Z", tick=False)
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 23c1935474e6..b9a434f1624f 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -3283,6 +3283,25 @@ class ExperimentHealthInputsConditionSetTrafficSerializer(serializers.Serializer
)
+class ExperimentHealthInputsExposureEventsSerializer(serializers.Serializer):
+ custom_event = serializers.CharField(
+ allow_null=True,
+ help_text="The event the exposure criteria count in place of the flag calls. Null for flag calls or an action.",
+ )
+ required_flag_key = serializers.CharField(
+ allow_null=True,
+ help_text="The flag key the exposure query requires on the flag call events. Null for a custom event or an action.",
+ )
+ variant_property = serializers.CharField(help_text="The event property that holds the variant.")
+ activation = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "The event, or the action's name, that has to follow a user's flag call before the user counts. Null "
+ "without an activation."
+ ),
+ )
+
+
class ExperimentHealthInputsReaderAccessSerializer(serializers.Serializer):
can_read_flag_history = serializers.BooleanField(
help_text="Whether the reader may read the flag's history, which the flag-change checks need."
@@ -3375,6 +3394,39 @@ class ExperimentHealthInputsSerializer(serializers.Serializer):
flag = ExperimentHealthInputsFlagSerializer(
allow_null=True, help_text="The experiment's feature flag. Null when it has none."
)
+ flag_last_called_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text=(
+ "The flag's latest recorded call, which a periodic sync of the flag call events sets. Null when the "
+ "experiment has no flag, or the flag has no recorded call."
+ ),
+ )
+ flag_called = serializers.BooleanField(
+ allow_null=True,
+ help_text=(
+ "Whether PostHog has recorded any call of the flag. The flag traffic check reads it on a draft. Null when "
+ "the experiment has no flag, or the organization's flag calls are stored where the checks can't read them."
+ ),
+ )
+ flag_called_during_run = serializers.BooleanField(
+ allow_null=True,
+ help_text=(
+ "Whether PostHog has recorded a call of the flag between launch and the end, or until now. The zero "
+ "exposures check reads it to say whether the flag is called. Null before launch, after a latest call that "
+ "came after the end, or when the organization's flag calls can't be read."
+ ),
+ )
+ exposure_events = ExperimentHealthInputsExposureEventsSerializer(
+ allow_null=True,
+ help_text="The events the exposure criteria count. Null when the stored exposure criteria don't parse.",
+ )
+ events_received = serializers.DictField(
+ child=serializers.BooleanField(),
+ help_text=(
+ "Whether the project has received each event that the metrics and the exposure criteria name, by event "
+ "name. A name that ingestion keeps no record of is absent."
+ ),
+ )
flag_history = ExperimentHealthInputsFlagHistorySerializer(
allow_null=True,
help_text=(
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index edafb4327021..802f361061d5 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -1060,6 +1060,8 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.user.is_staff = is_staff
self.user.save()
experiment = self._create_experiment_with_a_pinned_condition(f"health-inputs-{_name}")
+ experiment.feature_flag.last_called_at = timezone.now() - timedelta(days=1)
+ experiment.feature_flag.save()
if denied_property is not None:
self._deny_event_property(denied_property)
headers: dict[str, str] = {}
@@ -1087,6 +1089,14 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
[(condition["number"], condition["pinned_variant"]) for condition in inputs["flag"]["release_conditions"]],
[(1, "test"), (2, None)],
)
+ self.assertEqual(
+ (
+ inputs["flag_last_called_at"] is not None,
+ inputs["flag_called_during_run"],
+ inputs["exposure_events"]["required_flag_key"],
+ ),
+ (True, True, f"health-inputs-{_name}"),
+ )
traffic = inputs["condition_set_traffic"]
self.assertEqual(
(
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index ff600815881d..58ef181d5a50 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -3129,6 +3129,11 @@ export interface ExperimentFlagCleanupTaskApi {
can_view_task: boolean
}
+/**
+ * Whether the project has received each event that the metrics and the exposure criteria name, by event name. A name that ingestion keeps no record of is absent.
+ */
+export type ExperimentHealthInputsApiEventsReceived = { [key: string]: boolean }
+
export interface ExperimentHealthInputsReleaseConditionApi {
/** The condition's position in the flag, from 1, as the flag page labels it ('Set 2'). */
number: number
@@ -3177,6 +3182,26 @@ export interface ExperimentHealthInputsFlagApi {
split_text: string
}
+export interface ExperimentHealthInputsExposureEventsApi {
+ /**
+ * The event the exposure criteria count in place of the flag calls. Null for flag calls or an action.
+ * @nullable
+ */
+ custom_event: string | null
+ /**
+ * The flag key the exposure query requires on the flag call events. Null for a custom event or an action.
+ * @nullable
+ */
+ required_flag_key: string | null
+ /** The event property that holds the variant. */
+ variant_property: string
+ /**
+ * The event, or the action's name, that has to follow a user's flag call before the user counts. Null without an activation.
+ * @nullable
+ */
+ activation: string | null
+}
+
/**
* * `split` - Split
* * `bucketing` - Bucketing
@@ -3568,6 +3593,25 @@ export interface ExperimentHealthInputsApi {
secondary_metric_count: number
/** The experiment's feature flag. Null when it has none. */
flag: ExperimentHealthInputsFlagApi | null
+ /**
+ * The flag's latest recorded call, which a periodic sync of the flag call events sets. Null when the experiment has no flag, or the flag has no recorded call.
+ * @nullable
+ */
+ flag_last_called_at: string | null
+ /**
+ * Whether PostHog has recorded any call of the flag. The flag traffic check reads it on a draft. Null when the experiment has no flag, or the organization's flag calls are stored where the checks can't read them.
+ * @nullable
+ */
+ flag_called: boolean | null
+ /**
+ * Whether PostHog has recorded a call of the flag between launch and the end, or until now. The zero exposures check reads it to say whether the flag is called. Null before launch, after a latest call that came after the end, or when the organization's flag calls can't be read.
+ * @nullable
+ */
+ flag_called_during_run: boolean | null
+ /** The events the exposure criteria count. Null when the stored exposure criteria don't parse. */
+ exposure_events: ExperimentHealthInputsExposureEventsApi | null
+ /** Whether the project has received each event that the metrics and the exposure criteria name, by event name. A name that ingestion keeps no record of is absent. */
+ events_received: ExperimentHealthInputsApiEventsReceived
/** The changes of the flag since launch that can move exposed people. Null when the experiment is not running, is archived, its flag is missing or deleted, or the read failed. */
flag_history: ExperimentHealthInputsFlagHistoryApi | null
/** Whether the condition-set traffic was read, or why not. The forced-variant check needs it when the experiment is launched and some but not all release conditions pin a variant that has a share of the split and is not excluded from the analysis. The release-condition check needs it when such an override was removed after launch.
diff --git a/products/experiments/frontend/health/debug/healthDebugInputs.ts b/products/experiments/frontend/health/debug/healthDebugInputs.ts
index d6ea9e6d2d7a..3c6ebe59b07e 100644
--- a/products/experiments/frontend/health/debug/healthDebugInputs.ts
+++ b/products/experiments/frontend/health/debug/healthDebugInputs.ts
@@ -55,6 +55,22 @@ function yesNoUnknown(value: boolean | null): string {
return value === null ? 'Unknown' : formatYesNo(value)
}
+function describeExposureEvents({ exposure_events, events_received }: ExperimentHealthInputsApi): string {
+ if (!exposure_events) {
+ return "The stored exposure criteria don't parse"
+ }
+ if (exposure_events.custom_event) {
+ const received = events_received[exposure_events.custom_event]
+ const receivedText = received === undefined ? 'no record' : received ? 'received' : 'never received'
+ return `The event "${exposure_events.custom_event}" (${receivedText}), with the variant in ${exposure_events.variant_property}`
+ }
+ if (exposure_events.required_flag_key) {
+ const calls = `Calls of the flag "${exposure_events.required_flag_key}"`
+ return exposure_events.activation ? `${calls}, then the activation "${exposure_events.activation}"` : calls
+ }
+ return `An action, with the variant in ${exposure_events.variant_property}`
+}
+
function describeState(inputs: ExperimentHealthInputsApi): string {
if (!inputs.is_launched) {
return 'not launched'
@@ -124,6 +140,18 @@ export function buildFlagFacts(experiment: Experiment, state: HealthInputsState)
label: 'Variants',
value: serverValue(state, ({ flag }) => (flag ? flag.split_text : 'No flag')),
},
+ {
+ label: 'Latest recorded call',
+ value: serverValue(state, ({ flag_last_called_at }) =>
+ flag_last_called_at ? formatTimestamp(flag_last_called_at) : 'None'
+ ),
+ help: 'A sync of the flag call events sets it every 30 minutes, so it can trail a call by up to an hour.',
+ },
+ {
+ label: 'Called during the run',
+ value: serverValue(state, ({ flag_called_during_run }) => yesNoUnknown(flag_called_during_run)),
+ help: "The zero-exposures finding says the flag has no recorded calls when this is No. Unknown before launch, when the latest call came after the end, or when the organization's flag calls skip the events table.",
+ },
]
}
@@ -312,6 +340,11 @@ export function buildExposureFacts(state: HealthInputsState): SetupFact[] {
value: serverValue(state, (inputs) => exposureStatusLabel(inputs.exposures)),
help: 'The server reads the cached answer and never waits for the query.',
},
+ {
+ label: 'Counted on',
+ value: serverValue(state, describeExposureEvents),
+ help: "The zero-exposures finding reads the flag's calls only when the exposures are counted on them. A custom event or an action carries the variant in its own property.",
+ },
]
const totals = exposures?.totals
if (!exposures || !totals) {
diff --git a/products/experiments/frontend/health/debug/healthDebugReport.ts b/products/experiments/frontend/health/debug/healthDebugReport.ts
index cc2ab8656f76..50b0c1382259 100644
--- a/products/experiments/frontend/health/debug/healthDebugReport.ts
+++ b/products/experiments/frontend/health/debug/healthDebugReport.ts
@@ -309,7 +309,7 @@ function exposureChecks(input: HealthDebugInput): HealthDebugCheck[] {
}
return [
- exposureCheck('zero_exposures', ['experiment', 'exposures'], null),
+ exposureCheck('zero_exposures', ['experiment', 'flag', 'exposures'], null),
exposureCheck('srm', ['exposures'], 'The finding needs p < 0.001.'),
exposureCheck('bias_risk_multiple_excluded', ['exposures'], null),
exposureCheck(
diff --git a/products/experiments/frontend/health/experimentHealthFindingEvents.ts b/products/experiments/frontend/health/experimentHealthFindingEvents.ts
index cb7ee6db812a..099d14a6e3bb 100644
--- a/products/experiments/frontend/health/experimentHealthFindingEvents.ts
+++ b/products/experiments/frontend/health/experimentHealthFindingEvents.ts
@@ -241,7 +241,8 @@ export function captureExperimentHealthChecked(
* every load. `experiment results refresh completed` follows the exposure load on every tab.
* `has_srm`, `has_bias_risk` and a zero `exposures_total` are the page's own rules. The `_server` values are
* the server's checks on the same answer, null when the answer holds no server findings (a cached answer
- * from before the server ran them).
+ * from before the server ran them). `zero_exposures_cause` is the server's zero-exposures subcode, null without the
+ * finding or when it names no cause.
*/
export function exposureHealthEventProperties(
exposures: ExperimentExposureQueryResponse | null | undefined,
@@ -253,6 +254,7 @@ export function exposureHealthEventProperties(
has_bias_risk: boolean | null
srm_server: boolean | null
zero_exposures_server: boolean | null
+ zero_exposures_cause: string | null
bias_risk_server: boolean | null
} {
if (!exposures) {
@@ -263,6 +265,7 @@ export function exposureHealthEventProperties(
has_bias_risk: null,
srm_server: null,
zero_exposures_server: null,
+ zero_exposures_cause: null,
bias_risk_server: null,
}
}
@@ -279,6 +282,8 @@ export function exposureHealthEventProperties(
has_bias_risk: exposures.bias_risk != null,
srm_server: serverCodes ? serverCodes.has('srm') : null,
zero_exposures_server: serverCodes ? serverCodes.has('zero_exposures') : null,
+ // pinned: analytics property, so renaming it breaks insights. Its values are the server's pinned subcodes.
+ zero_exposures_cause: exposures.health_findings?.find(({ code }) => code === 'zero_exposures')?.subcode ?? null,
bias_risk_server: serverCodes ? serverCodes.has('bias_risk_multiple_excluded') : null,
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 274eaccda94a..0d8673fdb78f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -45335,6 +45335,7 @@ export namespace Schemas {
export const ExperimentExposureHealthFindingActionKind = {
+ OpenFeatureFlag: 'open_feature_flag',
EditExposureCriteria: 'edit_exposure_criteria',
AdjustDistribution: 'adjust_distribution',
UseFirstSeenVariant: 'use_first_seen_variant',
@@ -45630,6 +45631,11 @@ export namespace Schemas {
ReleaseConditions: 'release_conditions',
} as const;
+ /**
+ * Whether the project has received each event that the metrics and the exposure criteria name, by event name. A name that ingestion keeps no record of is absent.
+ */
+ export type ExperimentHealthInputsEventsReceived = {[key: string]: boolean};
+
export interface ExperimentHealthInputsReleaseCondition {
/** The condition's position in the flag, from 1, as the flag page labels it ('Set 2'). */
number: number;
@@ -45678,6 +45684,26 @@ export namespace Schemas {
split_text: string;
}
+ export interface ExperimentHealthInputsExposureEvents {
+ /**
+ * The event the exposure criteria count in place of the flag calls. Null for flag calls or an action.
+ * @nullable
+ */
+ custom_event: string | null;
+ /**
+ * The flag key the exposure query requires on the flag call events. Null for a custom event or an action.
+ * @nullable
+ */
+ required_flag_key: string | null;
+ /** The event property that holds the variant. */
+ variant_property: string;
+ /**
+ * The event, or the action's name, that has to follow a user's flag call before the user counts. Null without an activation.
+ * @nullable
+ */
+ activation: string | null;
+ }
+
export interface ExperimentHealthInputsFlagChange {
/** The kind of change. A bucketing change is a change of a setting that decides the variant draw.
*
@@ -46056,6 +46082,25 @@ export namespace Schemas {
secondary_metric_count: number;
/** The experiment's feature flag. Null when it has none. */
flag: ExperimentHealthInputsFlag | null;
+ /**
+ * The flag's latest recorded call, which a periodic sync of the flag call events sets. Null when the experiment has no flag, or the flag has no recorded call.
+ * @nullable
+ */
+ flag_last_called_at: string | null;
+ /**
+ * Whether PostHog has recorded any call of the flag. The flag traffic check reads it on a draft. Null when the experiment has no flag, or the organization's flag calls are stored where the checks can't read them.
+ * @nullable
+ */
+ flag_called: boolean | null;
+ /**
+ * Whether PostHog has recorded a call of the flag between launch and the end, or until now. The zero exposures check reads it to say whether the flag is called. Null before launch, after a latest call that came after the end, or when the organization's flag calls can't be read.
+ * @nullable
+ */
+ flag_called_during_run: boolean | null;
+ /** The events the exposure criteria count. Null when the stored exposure criteria don't parse. */
+ exposure_events: ExperimentHealthInputsExposureEvents | null;
+ /** Whether the project has received each event that the metrics and the exposure criteria name, by event name. A name that ingestion keeps no record of is absent. */
+ events_received: ExperimentHealthInputsEventsReceived;
/** The changes of the flag since launch that can move exposed people. Null when the experiment is not running, is archived, its flag is missing or deleted, or the read failed. */
flag_history: ExperimentHealthInputsFlagHistory | null;
/** Whether the condition-set traffic was read, or why not. The forced-variant check needs it when the experiment is launched and some but not all release conditions pin a variant that has a share of the split and is not excluded from the analysis. The release-condition check needs it when such an override was removed after launch.