: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
feat(experiments): report failed metric calculations in health checks (#123946)
Marcel Poelker1b216455d21a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2fa8be67381b..9f6f583cf4df 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11231,9 +11231,9 @@ snapshots:scenes-app-experiments--experiment-frequentist-two-variants--light:hash: v1.k794b7964.4ddea1c7537af9d50c57b4b9a76d4bcba39f743a23b4715683c0ce59d4c24f57.0ueR8XMLqRby_u6I0EyNIiUwXkbjmWMH3vBdoFNYmIIscenes-app-experiments--experiment-health-debug-tab--dark:- hash: v1.k794b7964.5edf9e51dc2fcaf83180f5ebad252d4f2e4db0759ac475691c7a06e7bcd47b77.aOSdT75x7w_nAKP96aVhXKbpOYrzivbbdmfc_PUUpgo+ hash: v1.k794b7964.87bfeebb075566d42d1fc0dc9c82a152fb4d9c90fdaa6c94234eae55240d5eeb.jb3eznlVBtPsqVv0VJkgM6Qx7cnQxoVLo0u8tPvZ2PAscenes-app-experiments--experiment-health-debug-tab--light:- hash: v1.k794b7964.031fb28af0f7086c3c0e869b3e4368d01ba2edc8d2c3184ec7061fb2b0223ae6.OY6eoJZtfSlG9w6CbbP9HlvA16I7_J8VY31UkdS6JcY+ hash: v1.k794b7964.7990ff112e1fb79448cbb6fe0791813e4cb4196db7a9892927acfb2276cffb22.9m5Oh5rh43QLj42kZh4a20jt7ydQyTlgj3J0E8Q0pCQscenes-app-experiments--experiment-recordings-dropped-metric--dark:hash: v1.k794b7964.e0e7181f2c9e61a8324eff9aa7a9230fef25b3cf37e0b24ef875780186ed25dc.9VEvZ4iVieVJwmDol0gwtAsr3wgZYW5gj2KXAGZJfiwscenes-app-experiments--experiment-recordings-dropped-metric--light:diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex f6bd9390634c..17abd7247478 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -257,6 +257,8 @@ const resolveResultByUuid = (* wins (it covers FAILED rows AND discovery-step failures absent from `results`), falling back to a* failed row's error_message. A rejected run carries the earlier run's rows, so its error is dropped on a* metric that has a row: the banner shows the message and the cell keeps the earlier result.+ * `_shown_failure` in products/experiments/backend/health/latest_calculation.py repeats this rule for the health+ * checks, so change both together.*/const resolveErrorByUuid = (recalculation: RecalculationPayload): ResolveByUuid<MetricErrorState> => {const metricErrors = metricErrorEntries(recalculation)diff --git a/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsxindex f17c738cdb64..f446ad2fc5ad 100644--- a/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx@@ -85,6 +85,10 @@ const HEALTH_INPUTS: ExperimentHealthInputsApi = {exposure_query_fails: false,failures: [],},+ latest_calculation: {+ finished_at: '2025-01-27T09:30:00Z',+ failures: [],+ },flag_history: {checked: true,not_checked_reason: null,diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex fd613054d241..d5d0ceb00b92 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -9866,6 +9866,7 @@ export namespace Schemas {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `srm` - Sample Ratio Mismatch* * `zero_exposures` - Zero Exposures@@ -9887,6 +9888,7 @@ export namespace Schemas {| "no_metric"| "metric_event_not_ingested"| "metric_cannot_compile"+ | "metric_calculation_failed"| "exposure_criteria_cannot_match"| "srm"| "zero_exposures"@@ -9938,6 +9940,7 @@ export namespace Schemas {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `srm` - Sample Ratio Mismatch* * `zero_exposures` - Zero Exposures@@ -9995,6 +9998,7 @@ export namespace Schemas {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `early_significance` - Early Significance* * `zero_exposures` - Zero Exposures@@ -10014,6 +10018,7 @@ export namespace Schemas {| "no_metric"| "metric_event_not_ingested"| "metric_cannot_compile"+ | "metric_calculation_failed"| "exposure_criteria_cannot_match"| "early_significance"| "zero_exposures"@@ -10046,6 +10051,7 @@ export namespace Schemas {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `early_significance` - Early Significance* * `zero_exposures` - Zero Exposuresdiff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.pyindex 1c533f34818a..2cce87d6804e 100644--- a/products/experiments/backend/facade/contracts.py+++ b/products/experiments/backend/facade/contracts.py@@ -128,6 +128,7 @@ class ExperimentHealthFindingCode(LabeledStrEnum):NO_METRIC = "no_metric"METRIC_EVENT_NOT_INGESTED = "metric_event_not_ingested"METRIC_CANNOT_COMPILE = "metric_cannot_compile"+ METRIC_CALCULATION_FAILED = "metric_calculation_failed"EXPOSURE_CRITERIA_CANNOT_MATCH = "exposure_criteria_cannot_match"SRM = "srm", "Sample Ratio Mismatch"ZERO_EXPOSURES = "zero_exposures"@@ -231,6 +232,7 @@ class ExperimentHealthCheckKey(LabeledStrEnum):NO_METRIC = "no_metric"METRIC_EVENT_NOT_INGESTED = "metric_event_not_ingested"METRIC_CANNOT_COMPILE = "metric_cannot_compile"+ METRIC_CALCULATION_FAILED = "metric_calculation_failed"EXPOSURE_CRITERIA_CANNOT_MATCH = "exposure_criteria_cannot_match"EARLY_SIGNIFICANCE = "early_significance"ZERO_EXPOSURES = "zero_exposures"diff --git a/products/experiments/backend/health/checks/metric_calculation_failed.py b/products/experiments/backend/health/checks/metric_calculation_failed.pynew file mode 100644index 000000000000..cfc2a1246d68--- /dev/null+++ b/products/experiments/backend/health/checks/metric_calculation_failed.py@@ -0,0 +1,340 @@+"""+Metrics whose latest calculation failed, so the results page shows an error in place of their results. Pure+functions, no I/O.++The page shows the stored error text, which is often the raw text of an exception. The finding says in words what+kind of failure it was and what to do next. It repeats a message only when PostHog's query builder wrote it for+users, as the message of a validation error. It doesn't repeat HogQL's text, which the calculation writes without the+reader's warehouse access, or the text of other exceptions, which is written for engineers.+"""++import re+from dataclasses import replace+from enum import StrEnum++from posthog.dataclasses import frozen+from posthog.exceptions import ClickHouseClusterMemoryLimitExceeded++from products.experiments.backend.facade.contracts import (+ ExperimentHealthFinding,+ ExperimentHealthFindingCode,+ ExperimentHealthFindingSeverity,+ ExperimentHealthMetricCompileErrorKind,+)+from products.experiments.backend.health.checks.metric_cannot_compile import MetricCompileError, word_compile_error+from products.experiments.backend.health.context import HealthContext, MetricCalculationFailure+from products.experiments.backend.health.skips import (+ NOT_ON_ARCHIVED,+ RUNS_AFTER_LAUNCH,+ CheckOutcome,+ no_calculated_metric,+ not_applicable,+ not_checked,+)+from products.experiments.backend.hogql_queries.error_handling import ERROR_TYPE_MESSAGES+from products.experiments.backend.recalculation import RECALCULATION_WINDOW_TOO_LONG_MESSAGE+from products.experiments.backend.temporal.models import RECALCULATION_WINDOW_TOO_LONG_ERROR_TYPE+from products.experiments.stats.shared.statistics import StatisticError+++class MetricCalculationFailureKind(StrEnum):+ # pinned: the finding's subcode and `evidence.metric_N_failure`.+ BUSY = "busy"+ QUERY_LIMIT = "query_limit"+ SETTINGS = "settings"+ NOT_ENOUGH_DATA = "not_enough_data"+ EXPERIMENT_TOO_OLD = "experiment_too_old"+ UNEXPECTED_ERROR = "unexpected_error"+++# The kinds that a change of the metric or the experiment fixes. The others go away with time or a retry.+_NEEDS_A_FIX = frozenset(+ {+ MetricCalculationFailureKind.QUERY_LIMIT,+ MetricCalculationFailureKind.SETTINGS,+ MetricCalculationFailureKind.EXPERIMENT_TOO_OLD,+ }+)+_MAX_EVIDENCE_MESSAGE_LENGTH = 300+_LIMIT_NEEDS = {+ "read_limit": "needed to read more data",+ "memory_limit": "needed more memory",+ "time_limit": "took longer",+}+_QUERY_SIZE_LIMIT = "query_size"++# A failure stored before calculations stored the class of the error has only its message, and some classes are too+# wide, so these rules read the message. They follow the messages of `ClickHouseAtCapacity`, of the ClickHouse+# limits, of the calculation's own time limit and of the friendly texts in `ERROR_TYPE_MESSAGES`.+# A socket timeout is stored as a timeout, but PostHog words it as a temporary problem of the database, so it counts as+# busy.+_BUSY_MESSAGE = re.compile(+ r"too busy|Too many queries|maximum concurrency|temporary problem|while (?:reading from|writing to) socket",+ re.IGNORECASE,+)+# Stored as out of memory, because the class subclasses the memory limit of one query, but the cluster was full and the+# query can be fine, so it counts as busy. The rule reads the class's own text, so a change of the wording can't turn+# the failure into a query limit.+_CLUSTER_MEMORY_FULL = str(ClickHouseClusterMemoryLimitExceeded.default_detail)+_QUERY_SIZE = re.compile(r"query size exceeded", re.IGNORECASE)+_READ_LIMIT = re.compile(r"Limit for rows or bytes to read exceeded")+_MEMORY_LIMIT = re.compile(r"ran out of memory|using too much memory|memory limit", re.IGNORECASE)+_TIME_LIMIT = re.compile(r"max execution time|ran out of time", re.IGNORECASE)+# A DRF validation error is stored as the `repr` of its detail list.+_VALIDATION_ERROR = re.compile(+ r"^\[ErrorDetail\(string=(?P<quote>['\"])(?P<text>.*?)(?P=quote), code='(?P<code>[^']*)'\)", re.DOTALL+)+# pydantic's text for a stored definition that its schema rejects. The rest of the text quotes the stored values.+_SCHEMA_ERROR = re.compile(r"^\d+ validation errors? for (?P<model>\w+)")+_TYPE_MISMATCH = re.compile(r"There is no supertype for types|Cannot convert string .* to type")+_NO_DATA = re.compile(r"No control variant found|No exposures for the '.*' variant yet")+# Django's text when the query names a cohort that was deleted. It names no cohort, so the wording can't say where.+_DELETED_COHORT = re.compile(r"Cohort matching query does not exist")+_NOT_ENOUGH_DATA_TEXTS = frozenset({ERROR_TYPE_MESSAGES[StatisticError], ERROR_TYPE_MESSAGES[ZeroDivisionError]})+++@frozen+class _Wording:+ kind: MetricCalculationFailureKind+ # The class of the error inside the kind, such as the limit or the family of a setting. None when the kind is all.+ error: str | None+ # What went wrong and what to do, after the sentence that names the metric.+ explanation: str+ # The message, when PostHog wrote it for users.+ message: str | None = None+ # Whether a setting of the experiment causes the failure, which then fails every metric, so the finding says the+ # explanation once and names no metric in it.+ every_metric: bool = False+++_UNEXPECTED = _Wording(+ kind=MetricCalculationFailureKind.UNEXPECTED_ERROR,+ error=None,+ explanation="Its query failed with an unexpected error. Try again, and contact support if it keeps failing.",+)+_BUSY = _Wording(+ kind=MetricCalculationFailureKind.BUSY,+ error=None,+ explanation="PostHog was too busy to run its query. Try again in a few minutes.",+)+# The words of the kinds above when the page has no button to try again: after the end the page shows no "Refresh+# results" button, and only an error stored as retriable gets a "Try again" button.+_WITHOUT_RETRY_AFTER_END = {+ MetricCalculationFailureKind.BUSY: "PostHog was too busy to run its query. Contact support to calculate it again.",+ MetricCalculationFailureKind.UNEXPECTED_ERROR: "Its query failed with an unexpected error. Contact support for "+ "help.",+}+_NOT_ENOUGH_DATA = _Wording(+ kind=MetricCalculationFailureKind.NOT_ENOUGH_DATA,+ error=None,+ explanation="There wasn't enough data to calculate it. Results show once each variant has more exposures and "+ "events.",+)+# After the end the experiment collects no more exposures, so the words can't promise results.+_NOT_ENOUGH_DATA_AFTER_END = "There wasn't enough data to calculate it before the experiment ended."+_EXPOSURE_QUERY = _Wording(+ kind=MetricCalculationFailureKind.SETTINGS,+ error="exposure_query",+ explanation="The experiment's exposure criteria or the project's test account filters can't be built into a "+ "query, so no metric can be calculated. Check them, or contact support if they look right.",+ every_metric=True,+)+++def metric_calculation_failed(ctx: HealthContext) -> CheckOutcome:+ if ctx.archived:+ return not_applicable(NOT_ON_ARCHIVED)+ if not ctx.is_launched:+ return not_applicable(RUNS_AFTER_LAUNCH)+ calculation = ctx.latest_calculation+ if calculation is None:+ return not_checked("Couldn't check because the latest calculation couldn't be read")+ if calculation.metric_count == 0:+ return no_calculated_metric(ctx)+ if calculation.finished_at is None:+ return not_applicable("Runs once a calculation of the metrics has finished")+ if not calculation.failures:+ return None+ compiles = ctx.metric_compiles+ # A metric whose query doesn't compile fails every calculation, and the metric queries check words that better.+ not_compiling = {failure.metric_id for failure in compiles.failures} if compiles else set()+ exposure_query_fails = compiles is not None and compiles.exposure_query_fails+ worded = [+ (failure, _word(failure, ended=ctx.has_ended, exposure_query_fails=exposure_query_fails))+ for failure in calculation.failures+ if failure.metric_id not in not_compiling+ ]+ if not worded:+ return not_applicable("The metric queries check reports the metric that failed")+ worded.sort(key=lambda item: (item[0].role != "primary", item[1].kind not in _NEEDS_A_FIX))+ count = len(worded)+ return ExperimentHealthFinding(+ code=ExperimentHealthFindingCode.METRIC_CALCULATION_FAILED,+ subcode=worded[0][1].kind.value,+ # A retry or more data fixes the other kinds. A kind that needs a fix stays a warning after the end, because+ # the calculation after the fix reads the events up to the end and brings back the results.+ severity=ExperimentHealthFindingSeverity.WARNING+ if any(failure.role == "primary" and wording.kind in _NEEDS_A_FIX for failure, wording in worded)+ else ExperimentHealthFindingSeverity.INFO,+ title=f"Latest calculation failed for {count} {'metric' if count == 1 else 'metrics'}",+ detail=" ".join(dict.fromkeys(_sentence(failure, wording) for failure, wording in worded)),+ evidence={"calculated_at": calculation.finished_at.isoformat(), **_evidence(worded)},+ # No action opens a given metric.+ actions=(),+ diagnostic_ref=None,+ )+++def _evidence(worded: list[tuple[MetricCalculationFailure, _Wording]]) -> dict[str, str | None]:+ evidence: dict[str, str | None] = {}+ for number, (failure, wording) in enumerate(worded, start=1):+ evidence[f"metric_{number}"] = failure.name+ evidence[f"metric_{number}_role"] = failure.role+ evidence[f"metric_{number}_failure"] = wording.kind.value+ evidence[f"metric_{number}_error"] = wording.error+ evidence[f"metric_{number}_message"] = (+ wording.message[:_MAX_EVIDENCE_MESSAGE_LENGTH] if wording.message else None+ )+ return evidence+++def _sentence(failure: MetricCalculationFailure, wording: _Wording) -> str:+ if wording.every_metric:+ return wording.explanation+ return f'The latest calculation of the {failure.role} metric "{failure.name}" failed. {wording.explanation}'+++def _word(failure: MetricCalculationFailure, *, ended: bool, exposure_query_fails: bool) -> _Wording:+ wording = _word_error(failure, exposure_query_fails=exposure_query_fails)+ if not ended:+ return wording+ if wording.kind == MetricCalculationFailureKind.NOT_ENOUGH_DATA:+ return replace(wording, explanation=_NOT_ENOUGH_DATA_AFTER_END)+ if wording.kind in _WITHOUT_RETRY_AFTER_END and not failure.retriable:+ return replace(wording, explanation=_WITHOUT_RETRY_AFTER_END[wording.kind])+ return wording+++def _word_error(failure: MetricCalculationFailure, *, exposure_query_fails: bool) -> _Wording:+ error_type = failure.error_type+ message = failure.message+ if error_type == "rate_limited" or _CLUSTER_MEMORY_FULL in message or _BUSY_MESSAGE.search(message):+ return _BUSY+ limit = _limit(error_type, message)+ if limit is not None:+ return _Wording(+ kind=MetricCalculationFailureKind.QUERY_LIMIT,+ error=limit,+ explanation=_limit_explanation(limit, failure),+ )+ if error_type == "insufficient_data" or (error_type is None and _NO_DATA.search(message)):+ return _NOT_ENOUGH_DATA+ if error_type == RECALCULATION_WINDOW_TOO_LONG_ERROR_TYPE:+ return _Wording(+ kind=MetricCalculationFailureKind.EXPERIMENT_TOO_OLD,+ error=None,+ explanation=RECALCULATION_WINDOW_TOO_LONG_MESSAGE,+ every_metric=True,+ )+ # The other steps fail before the query runs, for example on a metric that the calculation doesn't know yet.+ if failure.step not in (None, "calculation"):+ return _UNEXPECTED+ # The exposure query is part of every metric's query, so a metric's query fails where the exposure query fails.+ if exposure_query_fails:+ return _EXPOSURE_QUERY+ return _settings(failure) or _UNEXPECTED+++def _limit(error_type: str | None, message: str) -> str | None:+ """The limit of `_LIMIT_NEEDS`, or the limit of the query's length, that the query reached, or None."""+ if _QUERY_SIZE.search(message):+ return _QUERY_SIZE_LIMIT+ # A read limit can arrive as a validation error, so the message decides before the class does.+ if error_type == "byte_limit" or _READ_LIMIT.search(message):+ return "read_limit"+ if error_type == "out_of_memory" or _MEMORY_LIMIT.search(message):+ return "memory_limit"+ if error_type == "timeout" or _TIME_LIMIT.search(message):+ return "time_limit"+ return None+++def _limit_explanation(limit: str, failure: MetricCalculationFailure) -> str:+ if limit == _QUERY_SIZE_LIMIT:+ return (+ "Its query is longer than PostHog allows. A filter with a long list of values can cause this. Shorten "+ "the filters of the metric or of the exposure criteria, or contact support for help."+ )+ example = (+ "fewer funnel steps or narrower filters"+ if failure.definition.get("metric_type") == "funnel"+ else "narrower filters"+ )+ return (+ f"Its query {_LIMIT_NEEDS[limit]} than PostHog allows for one calculation. A query reads more data the longer "+ f"an experiment runs and the more traffic it gets. Simplify the metric, for example with {example}, or "+ "contact support for help."+ )+++def _settings(failure: MetricCalculationFailure) -> _Wording | None:+ """The words for a failure that a setting of the metric or the experiment caused, or None when the failure isn't+ known to be one."""+ message = failure.message+ validation = _VALIDATION_ERROR.match(message)+ if validation is not None:+ return _validation_error(failure, validation.group("text"), validation.group("code"))+ schema = _SCHEMA_ERROR.match(message)+ if schema is not None:+ if schema.group("model") == "ExperimentExposureCriteria":+ return _Wording(+ kind=MetricCalculationFailureKind.SETTINGS,+ error="invalid_exposure_criteria",+ explanation="The experiment's exposure criteria aren't valid, so no metric can be calculated. Edit "+ "the exposure criteria and save them again.",+ every_metric=True,+ )+ return _setting(+ MetricCompileError.INVALID_DEFINITION.value,+ "Its saved settings aren't valid. Create the metric again, or edit it to fix the setting.",+ )+ if _DELETED_COHORT.search(message):+ return _setting(+ MetricCompileError.DELETED_COHORT.value,+ "A filter uses a cohort that doesn't exist anymore. Check the cohorts in the metric's filters, the "+ "exposure criteria and the project's test account filters.",+ )+ if _TYPE_MISMATCH.search(message):+ return _setting(+ "type_mismatch",+ "A filter or an expression of the metric compares values of different types, such as text with a "+ "number. Check the types of the properties that the metric filters on.",+ )+ if not failure.can_quote_evaluation_rules:+ wording = word_compile_error(ExperimentHealthMetricCompileErrorKind.QUERY, message, failure.definition)+ if wording.error != MetricCompileError.OTHER:+ # Unlike the metric queries check, which compiles as the reader, the evidence leaves out HogQL's text.+ return _setting(wording.error.value, wording.explanation)+ if failure.error_type == "validation_error":+ return _setting(+ MetricCompileError.OTHER.value,+ "A setting of the metric makes its query fail. Check the metric's settings, or contact support if they "+ "look right.",+ )+ return None+++def _validation_error(failure: MetricCalculationFailure, text: str, code: str) -> _Wording:+ if code == "no_data":+ return _Wording(kind=MetricCalculationFailureKind.NOT_ENOUGH_DATA, error=None, explanation=text, message=text)+ if text in _NOT_ENOUGH_DATA_TEXTS:+ return _NOT_ENOUGH_DATA+ # The query runner gives these texts to errors of PostHog, not of the metric.+ if text in ERROR_TYPE_MESSAGES.values():+ return _UNEXPECTED+ wording = word_compile_error(ExperimentHealthMetricCompileErrorKind.REJECTED, text, failure.definition)+ return _setting(wording.error.value, wording.explanation, text)+++def _setting(error: str, explanation: str, message: str | None = None) -> _Wording:+ return _Wording(kind=MetricCalculationFailureKind.SETTINGS, error=error, explanation=explanation, message=message)diff --git a/products/experiments/backend/health/checks/metric_cannot_compile.py b/products/experiments/backend/health/checks/metric_cannot_compile.pyindex a24f6cdb97f6..c4c1ecfc7dda 100644--- a/products/experiments/backend/health/checks/metric_cannot_compile.py+++ b/products/experiments/backend/health/checks/metric_cannot_compile.py@@ -21,7 +21,13 @@ from products.experiments.backend.facade.contracts import (ExperimentHealthMetricCompileErrorKind,)from products.experiments.backend.health.context import HealthContext, MetricCompileFailure-from products.experiments.backend.health.skips import NOT_ON_ARCHIVED, CheckOutcome, not_applicable, not_checked+from products.experiments.backend.health.skips import (+ NOT_ON_ARCHIVED,+ CheckOutcome,+ no_calculated_metric,+ not_applicable,+ not_checked,+)class MetricCompileError(StrEnum):@@ -61,10 +67,7 @@ def metric_cannot_compile(ctx: HealthContext) -> CheckOutcome:if compiles is None:return not_checked("Couldn't check because the metric queries couldn't be built")if compiles.metric_count == 0:- # The calculation leaves out a metric in the legacy format, which the no-metric check counts.- if ctx.primary_metric_count + ctx.secondary_metric_count:- return not_applicable("Runs once the experiment has a metric in the current format")- return not_applicable("Runs once the experiment has a metric")+ return no_calculated_metric(ctx)if compiles.exposure_query_fails:return not_checked("Couldn't check because the exposure criteria can't be built into a query")if not compiles.failures:@@ -81,10 +84,10 @@ def metric_cannot_compile(ctx: HealthContext) -> CheckOutcome:return ExperimentHealthFinding(code=ExperimentHealthFindingCode.METRIC_CANNOT_COMPILE,subcode=worded[0][1].error.value,- # The metric fails every calculation, so the warning holds before launch too. After the end the experiment- # collects nothing more, so the finding is info.+ # The metric fails every calculation, so the warning holds before launch too. It holds after the end, because+ # the calculation after the fix reads the events up to the end and brings back the results.severity=ExperimentHealthFindingSeverity.WARNING- if not ctx.has_ended and any(failure.role == "primary" for failure in failures)+ if any(failure.role == "primary" for failure in failures)else ExperimentHealthFindingSeverity.INFO,title="PostHog can't calculate a metric"if len(failures) == 1@@ -116,8 +119,14 @@ def _evidence(worded: list[tuple[MetricCompileFailure, _Wording]]) -> dict[str,def _word(failure: MetricCompileFailure) -> _Wording:- message = failure.message- match failure.kind:+ return word_compile_error(failure.kind, failure.message, failure.definition)+++def word_compile_error(+ kind: ExperimentHealthMetricCompileErrorKind, message: str | None, definition: Mapping[str, Any]+) -> _Wording:+ """The words for an error that building the query of a metric with `definition` raised."""+ match kind:case ExperimentHealthMetricCompileErrorKind.DEFINITION if message is not None:return _Wording(error=MetricCompileError.INVALID_DEFINITION,@@ -144,7 +153,7 @@ def _word(failure: MetricCompileFailure) -> _Wording:case ExperimentHealthMetricCompileErrorKind.QUERY if message is not None:for pattern, subject, word in _QUERY_RULES:found = pattern.search(message)- if found and (subject is None or _mentions(failure.definition, found.group(subject))):+ if found and (subject is None or _mentions(definition, found.group(subject))):return word(found, message)return _Wording(error=MetricCompileError.OTHER,diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.pyindex f03148b4c4aa..c554b04249b3 100644--- a/products/experiments/backend/health/context.py+++ b/products/experiments/backend/health/context.py@@ -247,6 +247,7 @@ class MetricEvents:class MetricCompileFailure:"""A metric whose query doesn't compile, so every calculation of the metric fails."""+ metric_id: strname: strrole: MetricRolekind: ExperimentHealthMetricCompileErrorKind@@ -271,6 +272,42 @@ class MetricCompiles:exposure_query_fails: bool+@frozen+class MetricCalculationFailure:+ """A metric whose latest calculation failed, with the error that the calculation stored for it."""++ metric_id: str+ name: str+ role: MetricRole+ # The class that `classify_experiment_query_error` gave the error, or the class of a rejected calculation. None+ # for a failure that stores no class, such as one stored before calculations stored it.+ error_type: str | None+ step: str | None+ # The message as the results page shows it, without the names that HogQL suggests and the list of a scope's+ # fields. It can be the raw text of a ClickHouse or Python exception.+ message: str+ # Whether a HogQL message can quote the evaluation rules that the markers keep out of the browser, because the+ # definition holds a marker.+ can_quote_evaluation_rules: bool+ # Whether the results page shows a "Try again" button for the failure, which it does only for an error stored as+ # retriable.+ retriable: bool+ # The effective definition now, in which the wording looks for the names that the message gives.+ definition: Mapping[str, Any]+++@frozen+class LatestCalculation:+ """The latest finished calculation of the experiment's metrics, whose results and errors the results page+ shows."""++ metric_count: int+ # None when no calculation has finished, so the page shows no stored error.+ finished_at: datetime | None+ # The metrics of the experiment now whose latest calculation failed, in calculation order.+ failures: tuple[MetricCalculationFailure, ...]++@frozenclass FlagKeyFilter:"""An event property filter of the exposure criteria on `$feature_flag`, the key of the called flag."""@@ -342,17 +379,20 @@ class HealthContext:# None when not loaded. The health endpoint loads it. The exposure answer loads it only when the sample ratio test# fails, because the load can query the exposures and `srm` is the only exposure check that reads it.flag_history: FlagHistory | FlagHistoryNotChecked | None- # None when not loaded or unknown. Only the health endpoint loads it, because it queries the events.+ # None when not loaded or unknown. Only the health endpoints load it, because it queries the events.condition_set_traffic: ConditionSetTraffic | None- # None when not loaded or unknown. Only the health endpoint loads it, and only for a paused experiment.+ # None when not loaded or unknown. Only the health endpoints load it, and only for a paused experiment.pause_history: PauseHistory | None- # None when not loaded, unknown, or the experiment calculates no primary metric. Only the health endpoint loads it,+ # None when not loaded, unknown, or the experiment calculates no primary metric. Only the health endpoints load it,# and only for a launched experiment.primary_metric: PrimaryMetric | None# The variants that the analysis leaves out of the results.excluded_variant_keys: frozenset[str]- # None when not loaded or unknown. Only the health endpoint loads it, as the reader.+ # None when not loaded or unknown. Only the health endpoints load it, as the reader.metric_compiles: MetricCompiles | None+ # None when not loaded or unknown. Only the health endpoints load it, and only for a launched experiment that+ # isn't archived.+ latest_calculation: LatestCalculation | Nonedef parse_flag_state(@@ -655,4 +695,5 @@ def load_health_context(primary_metric=None,excluded_variant_keys=frozenset(experiment.excluded_variants or []),metric_compiles=None,+ latest_calculation=None,)diff --git a/products/experiments/backend/health/inputs_payload.py b/products/experiments/backend/health/inputs_payload.pyindex 35ab326a09aa..50ab6b106bff 100644--- a/products/experiments/backend/health/inputs_payload.py+++ b/products/experiments/backend/health/inputs_payload.py@@ -17,6 +17,7 @@ from products.experiments.backend.health.context import (FlagHistory,FlagHistoryNotChecked,FlagState,+ LatestCalculation,MetricCompiles,)from products.experiments.backend.health.exposure_inputs import ExposureInputs@@ -219,6 +220,23 @@ def _health_inputs_metric_compiles(compiles: MetricCompiles) -> dict[str, Any]:}+def _health_inputs_latest_calculation(calculation: LatestCalculation) -> dict[str, Any]:+ return {+ "finished_at": calculation.finished_at,+ "failures": [+ {+ "name": failure.name,+ "role": failure.role,+ "error_type": failure.error_type,+ "step": failure.step,+ "retriable": failure.retriable,+ "message": None if failure.can_quote_evaluation_rules else failure.message,+ }+ for failure in calculation.failures+ ],+ }++def health_inputs_payload(inputs: HealthInputs) -> dict[str, Any]:"""The inputs as plain data in the shape of `ExperimentHealthInputsSerializer`, so the presentation layer rendersthem without reading the health package's types."""@@ -248,6 +266,9 @@ def health_inputs_payload(inputs: HealthInputs) -> dict[str, Any]:else None,"events_received": dict(ctx.events_received),"metric_compiles": _health_inputs_metric_compiles(ctx.metric_compiles) if ctx.metric_compiles else None,+ "latest_calculation": _health_inputs_latest_calculation(ctx.latest_calculation)+ if ctx.latest_calculation+ else None,"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/latest_calculation.py b/products/experiments/backend/health/latest_calculation.pynew file mode 100644index 000000000000..ee7bf4ac1fd9--- /dev/null+++ b/products/experiments/backend/health/latest_calculation.py@@ -0,0 +1,94 @@+import re+from typing import Any++from posthog.exceptions_capture import capture_exception++from products.experiments.backend.health.context import LatestCalculation, MetricCalculationFailure+from products.experiments.backend.health.metric_compiles import can_hold_evaluation_rules, without_available_fields+from products.experiments.backend.metric_calculation.config import (+ MetricCalculationConfig,+ build_calculation_configs,+ calculation_metric_name,+ team_experiments_configs,+)+from products.experiments.backend.metric_calculation.results import MetricResultStore+from products.experiments.backend.models.experiment import Experiment, ExperimentMetricResult+from products.experiments.backend.recalculation import get_latest_recalculation+from products.experiments.backend.temporal.models import RECALCULATION_WINDOW_TOO_LONG_ERROR_TYPE++# The calculation doesn't apply the reader's warehouse access, so the names that HogQL suggests in its message can name+# a table or a column that the reader may not query.+_SUGGESTED_NAMES = re.compile(r" Did you mean: [^?]*\?")+++def load_latest_calculation(experiment: Experiment) -> LatestCalculation | None:+ """The latest finished calculation of the metrics of a launched experiment that isn't archived, or None. Never+ raises: the check that reads it then reports that it couldn't check."""+ if not experiment.is_launched or experiment.archived:+ return None+ try:+ return _load_latest_calculation(experiment)+ except Exception as error:+ capture_exception(error)+ return None+++def _load_latest_calculation(experiment: Experiment) -> LatestCalculation:+ team_config = team_experiments_configs([experiment.team_id])[experiment.team_id]+ # Metrics that share a uuid share one result and one error on the page.+ configs: dict[str, MetricCalculationConfig] = {}+ for calculation_config in build_calculation_configs(experiment, team_config=team_config):+ configs.setdefault(calculation_config.metric_id, calculation_config)+ # The results page shows the latest run that finished. Without one it shows the daily points, which hold no+ # failures, or else the run in progress, whose errors can still change, so the check waits for a finished run.+ run = get_latest_recalculation(experiment)+ if run is None:+ return LatestCalculation(metric_count=len(configs), finished_at=None, failures=())+ metric_errors = run.metric_errors if isinstance(run.metric_errors, dict) else {}+ rows = {+ row.metric_uuid: row for row in MetricResultStore(experiment_id=experiment.id).for_run(run, with_result=False)+ }+ failures = (+ _shown_failure(experiment, calculation_config, metric_errors.get(metric_id), rows.get(metric_id))+ for metric_id, calculation_config in configs.items()+ )+ return LatestCalculation(+ metric_count=len(configs),+ finished_at=run.completed_at,+ failures=tuple(failure for failure in failures if failure is not None),+ )+++def _shown_failure(+ experiment: Experiment,+ calculation_config: MetricCalculationConfig,+ entry: object,+ row: ExperimentMetricResult | None,+) -> MetricCalculationFailure | None:+ """The failure that the results page shows for one metric, or None.++ pinned: `resolveErrorByUuid` in experimentMetricsLogic.ts. The run's error entry wins over a failed row,+ because it also covers failures before the query ran. A rejected run carries the rows of the run before it, so+ its error doesn't show on a metric that has a row.+ """+ error: dict[str, Any] = entry if isinstance(entry, dict) else {}+ if error.get("error_type") == RECALCULATION_WINDOW_TOO_LONG_ERROR_TYPE and row is not None:+ error = {}+ message = error.get("message")+ if not isinstance(message, str):+ message = row.error_message if row is not None and row.status == ExperimentMetricResult.Status.FAILED else None+ if not message:+ return None+ error_type = error.get("error_type")+ step = error.get("step")+ return MetricCalculationFailure(+ metric_id=calculation_config.metric_id,+ name=calculation_metric_name(experiment, calculation_config),+ role=calculation_config.role,+ error_type=error_type if isinstance(error_type, str) else None,+ step=step if isinstance(step, str) else None,+ message=_SUGGESTED_NAMES.sub("", without_available_fields(message)),+ can_quote_evaluation_rules=can_hold_evaluation_rules(calculation_config.definition),+ retriable=error.get("retriable") is True,+ definition=calculation_config.definition,+ )diff --git a/products/experiments/backend/health/loader.py b/products/experiments/backend/health/loader.pyindex a6fe1dd4c5c6..959e5fafb5e2 100644--- a/products/experiments/backend/health/loader.py+++ b/products/experiments/backend/health/loader.py@@ -9,6 +9,7 @@ from products.experiments.backend.health.condition_set_traffic import load_condifrom products.experiments.backend.health.context import HealthContext, load_health_contextfrom products.experiments.backend.health.exposure_gate import load_flag_historyfrom products.experiments.backend.health.exposure_inputs import ExposureInputs, load_exposure_inputs+from products.experiments.backend.health.latest_calculation import load_latest_calculationfrom products.experiments.backend.health.metric_compiles import load_metric_compilesfrom products.experiments.backend.health.pause_history import load_pause_historyfrom products.experiments.backend.health.primary_metric import load_primary_metric@@ -34,9 +35,9 @@ class HealthInputs:def load_experiment_health_context(*, team_id: int, experiment_id: int, reader_access: ExperimentHealthReaderAccess, user: User | None) -> HealthContext:- """The context that the checks of the health endpoint read: the experiment, its flag, its linked metrics and the- compile of their queries, the changes of the flag since launch and the flag's recent calls, as far as- `reader_access` and `user`'s warehouse access allow."""+ """The context that the checks of the health endpoint read: the experiment, its flag, its linked metrics, the+ compile of their queries and their latest calculation, the changes of the flag since launch and the flag's recent+ calls, as far as `reader_access` and `user`'s warehouse access allow."""return _health_context(_load_experiment(team_id, experiment_id), reader_access, user)@@ -78,4 +79,5 @@ def _health_context(pause_history=load_pause_history(experiment, reader_access=reader_access),primary_metric=load_primary_metric(experiment),metric_compiles=load_metric_compiles(experiment, user=user),+ latest_calculation=load_latest_calculation(experiment),)diff --git a/products/experiments/backend/health/metric_compiles.py b/products/experiments/backend/health/metric_compiles.pyindex bb3d5766f547..5555d59b0ad5 100644--- a/products/experiments/backend/health/metric_compiles.py+++ b/products/experiments/backend/health/metric_compiles.py@@ -18,6 +18,7 @@ also after one of them is deleted or the reader loses access.import reimport jsonimport hashlib+from collections.abc import Mappingfrom datetime import timedeltafrom enum import StrEnumfrom typing import Any@@ -120,6 +121,7 @@ def _load_metric_compiles(experiment: Experiment, user: User | None) -> MetricCocase _Failure(kind=kind, message=message):failures.append(MetricCompileFailure(+ metric_id=calculation_config.metric_id,name=calculation_metric_name(experiment, calculation_config),role=calculation_config.role,kind=kind,@@ -136,13 +138,18 @@ def _load_metric_compiles(experiment: Experiment, user: User | None) -> MetricCo)+def can_hold_evaluation_rules(definition: Mapping[str, Any]) -> bool:+ """Whether a HogQL message about the query of a metric with `definition` can quote the team's evaluation rules."""+ # The compile replaces each marker with the team's evaluation rules, so a HogQL message can quote them.+ return mentions_evaluation_pass_markers(json.dumps(definition, default=str))++def _can_hold_evaluation_rules(kind: ExperimentHealthMetricCompileErrorKind, calculation_config: MetricCalculationConfig) -> bool:- # The compile replaces each marker with the team's evaluation rules, so a HogQL message can quote them. The query- # builder's own messages don't.- return kind != ExperimentHealthMetricCompileErrorKind.REJECTED and mentions_evaluation_pass_markers(- json.dumps(calculation_config.definition, default=str)+ # The query builder's own messages don't quote the evaluation rules.+ return kind != ExperimentHealthMetricCompileErrorKind.REJECTED and can_hold_evaluation_rules(+ calculation_config.definition)@@ -230,12 +237,16 @@ def _error_kind(error: Exception) -> ExperimentHealthMetricCompileErrorKind:_AVAILABLE_FIELDS = re.compile(r"\. Available fields: .*?\.(?= If |$)", re.DOTALL)+def without_available_fields(message: str) -> str:+ return _AVAILABLE_FIELDS.sub(".", message)++def _error_message(error: Exception) -> str:if isinstance(error, ValidationError):return get_user_friendly_message(error) or str(error)if isinstance(error, pydantic.ValidationError):return _definition_message(error)- return _AVAILABLE_FIELDS.sub(".", str(error))+ return without_available_fields(str(error))def _definition_message(error: pydantic.ValidationError) -> str:diff --git a/products/experiments/backend/health/registry.py b/products/experiments/backend/health/registry.pyindex 28cc6e6c86fd..8f514a8bbd84 100644--- a/products/experiments/backend/health/registry.py+++ b/products/experiments/backend/health/registry.py@@ -20,6 +20,7 @@ from products.experiments.backend.health.checks.flag_change_findings import flagfrom products.experiments.backend.health.checks.flag_state import flag_statefrom products.experiments.backend.health.checks.flag_variants import flag_variants_mismatchfrom products.experiments.backend.health.checks.forced_variant import forced_variant_release_condition+from products.experiments.backend.health.checks.metric_calculation_failed import metric_calculation_failedfrom products.experiments.backend.health.checks.metric_cannot_compile import metric_cannot_compilefrom products.experiments.backend.health.checks.metric_event_not_ingested import metric_event_not_ingestedfrom products.experiments.backend.health.checks.multiple_variants import multiple_variants_share@@ -95,6 +96,11 @@ EXPERIMENT_HEALTH_CHECKS: tuple[HealthCheck, ...] = (name="Metric queries",run=metric_cannot_compile,),+ HealthCheck(+ key=ExperimentHealthCheckKey.METRIC_CALCULATION_FAILED,+ name="Metric results",+ run=metric_calculation_failed,+ ),HealthCheck(key=ExperimentHealthCheckKey.EXPOSURE_CRITERIA_CANNOT_MATCH,name="Exposure criteria",diff --git a/products/experiments/backend/health/skips.py b/products/experiments/backend/health/skips.pyindex 305033c08bca..f853f8a7ab3e 100644--- a/products/experiments/backend/health/skips.py+++ b/products/experiments/backend/health/skips.py@@ -32,6 +32,14 @@ def not_checked(reason: str) -> CheckSkip:return CheckSkip(status=ExperimentHealthCheckStatus.NOT_CHECKED, reason=reason)+def no_calculated_metric(ctx: HealthContext) -> CheckSkip:+ """Why a check of the metrics that the experiment calculates doesn't look when it calculates none."""+ # The calculation leaves out a metric in the legacy format, which the no-metric check counts.+ if ctx.primary_metric_count + ctx.secondary_metric_count:+ return not_applicable("Runs once the experiment has a metric in the current format")+ return not_applicable("Runs once the experiment has a metric")++def flag_to_check(ctx: HealthContext, *, before_launch: bool) -> FlagState | CheckSkip:"""The flag that a check of the flag's setup reads, or why the check doesn't look. After the end the flag oftenholds the shipped decision, not the setup of the run, so these checks stop there."""diff --git a/products/experiments/backend/health/test/factories.py b/products/experiments/backend/health/test/factories.pyindex 96e6e5319fed..d21ad4655f11 100644--- a/products/experiments/backend/health/test/factories.py+++ b/products/experiments/backend/health/test/factories.py@@ -44,6 +44,7 @@ RUNNING_CONTEXT = HealthContext(primary_metric=None,excluded_variant_keys=frozenset(),metric_compiles=None,+ latest_calculation=None,)diff --git a/products/experiments/backend/health/test/test_metric_calculation_failed.py b/products/experiments/backend/health/test/test_metric_calculation_failed.pynew file mode 100644index 000000000000..68df1dd433fb--- /dev/null+++ b/products/experiments/backend/health/test/test_metric_calculation_failed.py@@ -0,0 +1,506 @@+from dataclasses import replace+from datetime import UTC, datetime, timedelta+from typing import Any++from posthog.test.base import BaseTest+from unittest import TestCase++from django.utils import timezone++from parameterized import parameterized++from posthog.exceptions import ClickHouseClusterMemoryLimitExceeded+from posthog.models.scoping import team_scope++from products.experiments.backend.facade.api import get_experiment_health+from products.experiments.backend.facade.contracts import (+ ExperimentHealth,+ ExperimentHealthCheckKey,+ ExperimentHealthCheckStatus,+ ExperimentHealthFinding,+ ExperimentHealthFindingCode,+ ExperimentHealthFindingSeverity,+ ExperimentHealthMetricCompileErrorKind,+ ExperimentHealthReaderAccess,+)+from products.experiments.backend.health.checks.metric_calculation_failed import metric_calculation_failed+from products.experiments.backend.health.context import (+ LatestCalculation,+ MetricCalculationFailure,+ MetricCompileFailure,+ MetricCompiles,+)+from products.experiments.backend.health.skips import CheckSkip+from products.experiments.backend.health.test.factories import ENDED, RUNNING_CONTEXT+from products.experiments.backend.metric_calculation.config import get_metric_calculation_config+from products.experiments.backend.metric_calculation.results import MetricResultStore+from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation+from products.feature_flags.backend.models.feature_flag import FeatureFlag++CODE = ExperimentHealthFindingCode.METRIC_CALCULATION_FAILED+KEY = ExperimentHealthCheckKey.METRIC_CALCULATION_FAILED+WARNING = ExperimentHealthFindingSeverity.WARNING+INFO = ExperimentHealthFindingSeverity.INFO+NO_QUERIES = ExperimentHealthReaderAccess(+ can_read_flag_history=False, can_query_events=False, denied_event_properties=frozenset()+)+FINISHED_AT = datetime(2026, 10, 26, 9, 30, tzinfo=UTC)+CLICKHOUSE_MESSAGE = (+ "Code: 215. DB::Exception: Column `properties` is not under aggregate function and not in GROUP BY keys. "+ "In query SELECT properties FROM events"+)+++def _failure(+ message: str,+ *,+ error_type: str | None,+ step: str | None = "calculation",+ role: str = "primary",+ retriable: bool = True,+ can_quote_evaluation_rules: bool = False,+) -> MetricCalculationFailure:+ return MetricCalculationFailure(+ metric_id=f"{role}-metric",+ name="Revenue",+ role="primary" if role == "primary" else "secondary",+ error_type=error_type,+ step=step,+ message=message,+ can_quote_evaluation_rules=can_quote_evaluation_rules,+ retriable=retriable,+ definition={"kind": "ExperimentMetric", "metric_type": "mean"},+ )+++def _outcome(*failures: MetricCalculationFailure, **changes: Any) -> ExperimentHealthFinding | CheckSkip | None:+ calculation = LatestCalculation(metric_count=len(failures), finished_at=FINISHED_AT, failures=failures)+ return metric_calculation_failed(replace(RUNNING_CONTEXT, latest_calculation=calculation, **changes))+++def _mean(uuid: str) -> dict[str, Any]:+ return {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": uuid,+ "name": f"Metric {uuid}",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+++class TestMetricCalculationFailed(TestCase):+ @parameterized.expand(+ [+ (+ "busy",+ _failure("Queries are a little too busy right now.", error_type="rate_limited"),+ {},+ ("busy", INFO, None, "PostHog was too busy"),+ ),+ (+ "busy_after_the_end_with_a_retry",+ _failure("Queries are a little too busy right now.", error_type="rate_limited"),+ ENDED,+ ("busy", INFO, None, "Try again in a few minutes."),+ ),+ (+ "busy_after_the_end_without_a_retry",+ _failure("Queries are a little too busy right now.", error_type=None, retriable=False),+ ENDED,+ ("busy", INFO, None, "Contact support to calculate it again."),+ ),+ (+ "cluster_out_of_memory",+ _failure(str(ClickHouseClusterMemoryLimitExceeded()), error_type="out_of_memory", retriable=False),+ {},+ ("busy", INFO, None, "PostHog was too busy"),+ ),+ (+ "read_limit_stored_as_a_builder_message",+ _failure(+ "[ErrorDetail(string='Limit for rows or bytes to read exceeded, max bytes: 2.00 GiB, current "+ "bytes: 2.10 GiB', code='invalid')]",+ error_type="validation_error",+ ),+ {},+ ("query_limit", WARNING, "read_limit", "needed to read more data than PostHog allows"),+ ),+ (+ "memory_limit_stored_without_a_class",+ _failure("This query ran out of memory before it could finish.", error_type=None),+ {},+ ("query_limit", WARNING, "memory_limit", "needed more memory than PostHog allows for one calculation"),+ ),+ (+ "query_too_long",+ _failure("Query size exceeded.", error_type="server_error"),+ {},+ ("query_limit", WARNING, "query_size", "A filter with a long list of values"),+ ),+ (+ "socket_timeout",+ _failure(+ "Code: 209. DB::NetException: Timeout exceeded while reading from socket (10.0.0.1:9000, 300000 ms)",+ error_type="timeout",+ ),+ {},+ ("busy", INFO, None, "PostHog was too busy"),+ ),+ (+ "builder_message",+ _failure(+ "[ErrorDetail(string='Data warehouse metric properties cannot contain aggregate functions; "+ "reference a column or a per-row expression instead.', code='invalid')]",+ error_type="validation_error",+ ),+ {},+ ("settings", WARNING, "rejected", "Data warehouse metric properties cannot contain aggregate"),+ ),+ (+ "builder_message_without_exposures",+ _failure(+ "[ErrorDetail(string=\"No exposures for the 'control' variant yet. Results can be calculated "+ "once it has data.\", code='no_data')]",+ error_type="validation_error",+ ),+ {},+ ("not_enough_data", INFO, None, "No exposures for the 'control' variant yet."),+ ),+ (+ "not_enough_data_after_the_end",+ _failure("No control variant found", error_type=None),+ ENDED,+ ("not_enough_data", INFO, None, "before the experiment ended"),+ ),+ (+ "error_of_posthog_stored_as_a_validation_error",+ _failure(+ "[ErrorDetail(string='Unable to retrieve experiment data. Please try refreshing the page.', "+ "code='invalid')]",+ error_type=None,+ ),+ {},+ ("unexpected_error", INFO, None, "unexpected error"),+ ),+ (+ "deleted_cohort",+ _failure("Cohort matching query does not exist.", error_type="server_error"),+ {},+ ("settings", WARNING, "deleted_cohort", "uses a cohort that doesn't exist anymore"),+ ),+ (+ "type_mismatch",+ _failure("DB::Exception: There is no supertype for types String, Float64", error_type="server_error"),+ {},+ ("settings", WARNING, "type_mismatch", "compares values of different types"),+ ),+ (+ "clickhouse_message",+ _failure(CLICKHOUSE_MESSAGE, error_type="validation_error"),+ {},+ ("settings", WARNING, "other", "A setting of the metric makes its query fail."),+ ),+ (+ "hogql_message_that_can_quote_evaluation_rules",+ _failure(+ "Invalid behavioral property filter", error_type="validation_error", can_quote_evaluation_rules=True+ ),+ {},+ ("settings", WARNING, "other", "A setting of the metric makes its query fail."),+ ),+ (+ "metric_unknown_to_the_run",+ _failure("Metric m not found in experiment 1", error_type="validation_error", step="discovery"),+ {},+ ("unexpected_error", INFO, None, "unexpected error"),+ ),+ (+ "error_of_posthog_stored_without_a_class",+ _failure("Decimal overflow while executing query.", error_type=None),+ {},+ ("unexpected_error", INFO, None, "Try again, and contact support"),+ ),+ (+ "experiment_too_old",+ _failure("This experiment started too long ago.", error_type="recalculation_window_too_long"),+ {},+ ("experiment_too_old", WARNING, None, "move the start date closer to today"),+ ),+ (+ "secondary_metric_only",+ _failure("Query has hit the max execution time.", error_type="timeout", role="secondary"),+ {},+ ("query_limit", INFO, "time_limit", 'the secondary metric "Revenue"'),+ ),+ (+ "primary_metric_after_the_end",+ _failure("Query has hit the max execution time.", error_type="timeout"),+ ENDED,+ ("query_limit", WARNING, "time_limit", "took longer"),+ ),+ ]+ )+ def test_words_why_the_latest_calculation_failed(+ self,+ _name: str,+ failure: MetricCalculationFailure,+ status: dict[str, Any],+ expected: tuple[str, ExperimentHealthFindingSeverity, str | None, str],+ ) -> None:+ finding = _outcome(failure, **status)++ assert isinstance(finding, ExperimentHealthFinding)+ subcode, severity, error, words = expected+ self.assertEqual(+ (finding.subcode, finding.severity, finding.evidence["metric_1_error"]), (subcode, severity, error)+ )+ self.assertIn(words, finding.detail)+ self.assertNotIn("DB::Exception", finding.detail + str(finding.evidence))++ def test_a_metric_that_needs_a_fix_leads_and_sets_the_severity(self) -> None:+ finding = _outcome(+ _failure("Queries are a little too busy right now.", error_type="rate_limited"),+ _failure("Limit for rows or bytes to read exceeded", error_type="byte_limit", role="secondary"),+ replace(_failure("Query has hit the max execution time.", error_type="timeout"), metric_id="third"),+ )++ assert isinstance(finding, ExperimentHealthFinding)+ self.assertEqual(+ (finding.subcode, finding.severity, finding.title, finding.evidence["calculated_at"]),+ ("query_limit", WARNING, "Latest calculation failed for 3 metrics", FINISHED_AT.isoformat()),+ )+ self.assertEqual(+ [finding.evidence[f"metric_{number}_failure"] for number in (1, 2, 3)],+ ["query_limit", "busy", "query_limit"],+ )++ @parameterized.expand(+ [+ (+ "exposure_query_does_not_compile",+ "Cohort 7 does not exist",+ "validation_error",+ True,+ ("settings", "exposure_query", "can't be built into a query"),+ ),+ (+ "experiment_too_old",+ "This experiment started too long ago.",+ "recalculation_window_too_long",+ False,+ ("experiment_too_old", None, "started too long ago"),+ ),+ ]+ )+ def test_words_a_failure_of_the_experiment_once(+ self,+ _name: str,+ message: str,+ error_type: str,+ exposure_query_fails: bool,+ expected: tuple[str, str | None, str],+ ) -> None:+ compiles = MetricCompiles(+ metric_count=2, failures=(), unknown_count=0, no_access_count=0, exposure_query_fails=exposure_query_fails+ )++ finding = _outcome(+ _failure(message, error_type=error_type),+ _failure(message, error_type=error_type, role="secondary"),+ metric_compiles=compiles,+ )++ assert isinstance(finding, ExperimentHealthFinding)+ subcode, error, words = expected+ self.assertEqual(+ (finding.subcode, finding.severity, finding.evidence["metric_1_error"], finding.evidence["metric_2_error"]),+ (subcode, WARNING, error, error),+ )+ self.assertEqual(finding.detail.count(words), 1)+ self.assertNotIn("Revenue", finding.detail)++ def test_waits_for_a_metric_that_the_experiment_calculates(self) -> None:+ calculation = LatestCalculation(metric_count=0, finished_at=None, failures=())++ outcome = metric_calculation_failed(+ replace(RUNNING_CONTEXT, latest_calculation=calculation, primary_metric_count=0, secondary_metric_count=0)+ )++ self.assertEqual(+ outcome,+ CheckSkip(+ status=ExperimentHealthCheckStatus.NOT_APPLICABLE, reason="Runs once the experiment has a metric"+ ),+ )++ def test_leaves_a_metric_whose_query_does_not_compile_to_that_check(self) -> None:+ compiles = MetricCompiles(+ metric_count=1,+ failures=(+ MetricCompileFailure(+ metric_id="primary-metric",+ name="Revenue",+ role="primary",+ kind=ExperimentHealthMetricCompileErrorKind.QUERY,+ message="Unable to resolve field: revenue",+ definition={},+ ),+ ),+ unknown_count=0,+ no_access_count=0,+ exposure_query_fails=False,+ )++ outcome = _outcome(+ _failure("Unable to resolve field: revenue", error_type="validation_error"), metric_compiles=compiles+ )++ self.assertEqual(+ outcome,+ CheckSkip(+ status=ExperimentHealthCheckStatus.NOT_APPLICABLE,+ reason="The metric queries check reports the metric that failed",+ ),+ )+++class TestMetricCalculationFailedFromStoredRuns(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="checkout-test",+ created_by=self.user,+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ },+ )+ self.experiment = Experiment.objects.create(+ team=self.team,+ name="Checkout",+ feature_flag=flag,+ start_date=timezone.now() - timedelta(days=3),+ metrics=[_mean("primary"), _mean("rejected")],+ metrics_secondary=[_mean("secondary")],+ )++ def _run(+ self,+ *,+ status: str,+ created_at: datetime,+ metric_errors: dict[str, dict[str, Any]] | None = None,+ failed_rows: tuple[str, ...] = (),+ completed_rows: tuple[str, ...] = (),+ ) -> None:+ with team_scope(self.team.id):+ query_to = created_at + timedelta(minutes=1)+ run = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=self.experiment,+ status=ExperimentMetricsRecalculation.Status.IN_PROGRESS,+ metric_uuids=["primary", "rejected", "secondary"],+ query_to=query_to,+ )+ store = MetricResultStore(experiment_id=self.experiment.id)+ for metric_uuid in failed_rows + completed_rows:+ calculation_config = get_metric_calculation_config(self.experiment, metric_uuid)+ assert calculation_config is not None+ query_from = self.experiment.start_date+ assert query_from is not None+ if metric_uuid in failed_rows:+ store.record_run_failure(+ str(run.id),+ calculation_config,+ window=query_to,+ query_from=query_from,+ error_message="Unable to resolve field: purchase. Did you mean: purchase_total?",+ query_id=None,+ )+ else:+ store.record_run_result(+ str(run.id),+ calculation_config,+ window=query_to,+ query_from=query_from,+ result={"variant_results": []},+ query_id=None,+ )+ terminal = status in (+ ExperimentMetricsRecalculation.Status.COMPLETED,+ ExperimentMetricsRecalculation.Status.FAILED,+ )+ ExperimentMetricsRecalculation.objects.filter(id=run.id).update(+ status=status,+ created_at=created_at,+ completed_at=query_to if terminal else None,+ metric_errors=metric_errors or {},+ )++ def _health(self) -> ExperimentHealth:+ return get_experiment_health(+ team_id=self.team.id, experiment_id=self.experiment.id, reader_access=NO_QUERIES, user=self.user+ )++ def test_reports_the_failures_that_the_results_page_shows(self) -> None:+ self._run(+ status=ExperimentMetricsRecalculation.Status.FAILED,+ created_at=timezone.now() - timedelta(hours=2),+ metric_errors={+ "primary": {"step": "calculation", "message": "Queries are too busy.", "error_type": "rate_limited"},+ # A rejected run keeps the earlier results, so its error doesn't show on a metric that has one.+ "rejected": {"step": "request", "message": "Too old.", "error_type": "recalculation_window_too_long"},+ "removed": {"step": "calculation", "message": "Query timed out", "error_type": "timeout"},+ },+ failed_rows=("secondary",),+ completed_rows=("rejected",),+ )++ [finding] = [finding for finding in self._health().findings if finding.code == CODE]++ self.assertEqual(+ [(finding.evidence[f"metric_{n}"], finding.evidence[f"metric_{n}_failure"]) for n in (1, 2)],+ [("Metric primary", "busy"), ("Metric secondary", "settings")],+ )+ self.assertNotIn("metric_3", finding.evidence)+ self.assertNotIn("purchase_total", finding.detail + str(finding.evidence))+ self.assertIsNone(finding.evidence["metric_2_message"])++ @parameterized.expand(+ [+ ("no_finished_calculation", None, ExperimentHealthCheckStatus.NOT_APPLICABLE),+ (+ "later_calculation_completed",+ ExperimentMetricsRecalculation.Status.COMPLETED,+ ExperimentHealthCheckStatus.PASSED,+ ),+ (+ "later_calculation_still_running",+ ExperimentMetricsRecalculation.Status.IN_PROGRESS,+ ExperimentHealthCheckStatus.FINDING,+ ),+ ]+ )+ def test_reads_the_latest_finished_calculation(+ self, _name: str, later_status: str | None, expected: ExperimentHealthCheckStatus+ ) -> None:+ now = timezone.now()+ if later_status is not None:+ self._run(+ status=ExperimentMetricsRecalculation.Status.FAILED,+ created_at=now - timedelta(hours=5),+ metric_errors={+ "primary": {"step": "calculation", "message": "Query timed out", "error_type": "timeout"}+ },+ )+ self._run(status=later_status, created_at=now - timedelta(hours=1), completed_rows=("primary",))++ statuses = {check.key: check.status for check in self._health().checks}++ self.assertEqual(statuses[KEY], expected)diff --git a/products/experiments/backend/health/test/test_metric_cannot_compile.py b/products/experiments/backend/health/test/test_metric_cannot_compile.pyindex bc40a1d887a9..8bfacf9de9c0 100644--- a/products/experiments/backend/health/test/test_metric_cannot_compile.py+++ b/products/experiments/backend/health/test/test_metric_cannot_compile.py@@ -210,7 +210,7 @@ class TestMetricCannotCompile(BaseTest):"primary_metric_after_the_end","metrics",_mean(_hogql(COMPOUND)),- ("compound_aggregation", INFO, 'the primary metric "Revenue"'),+ ("compound_aggregation", WARNING, 'the primary metric "Revenue"'),{"start_date": timezone.now() - timedelta(days=10), "end_date": timezone.now() - timedelta(days=1)},),]diff --git a/products/experiments/backend/metric_calculation/results.py b/products/experiments/backend/metric_calculation/results.pyindex b8b50b76e80a..a932515684d3 100644--- a/products/experiments/backend/metric_calculation/results.py+++ b/products/experiments/backend/metric_calculation/results.py@@ -109,8 +109,9 @@ class MetricResultStore:experiment_id: int- def for_run(self, run: ExperimentMetricsRecalculation) -> list[ExperimentMetricResult]:- """The rows of a recalculation run, one per metric uuid, ordered by metric uuid.+ def for_run(self, run: ExperimentMetricsRecalculation, *, with_result: bool = True) -> list[ExperimentMetricResult]:+ """The rows of a recalculation run, one per metric uuid, ordered by metric uuid. With `with_result=False` the+ rows don't load `result`, which for a funnel holds the sessions of each step, and reading it queries again.A run has no link to its rows. The rows are found by the salted keys of the run's metrics under thecurrent configuration of the experiment, at the run's query_to. A metric that no longer resolves on the@@ -135,6 +136,8 @@ class MetricResultStore:rows = ExperimentMetricResult.objects.filter(experiment_id=self.experiment_id, fingerprint__in=fingerprints, query_to=run.query_to)+ if not with_result:+ rows = rows.defer("result")return list(_newest_write_first(rows, "metric_uuid").distinct("metric_uuid"))def has_completed(self, calculation_config: MetricCalculationConfig, *, window: datetime) -> bool:diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 3ff3dbc84006..51d0df9128a3 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -3444,6 +3444,45 @@ class ExperimentHealthInputsMetricCompilesSerializer(serializers.Serializer):)+class ExperimentHealthInputsMetricCalculationFailureSerializer(serializers.Serializer):+ name = serializers.CharField(help_text="The metric's name as the experiment shows it.")+ role = serializers.CharField(help_text="'primary' or 'secondary'.")+ error_type = serializers.CharField(+ allow_null=True,+ help_text=(+ "The class that the calculation stored for the error, such as 'timeout' or 'rate_limited'. Null for a "+ "failure stored without a class."+ ),+ )+ step = serializers.CharField(+ allow_null=True,+ help_text="The step of the calculation that failed, such as 'calculation'. Null when the failure names none.",+ )+ retriable = serializers.BooleanField(+ help_text=(+ "Whether the results page shows a button to try the metric again, which it does for a retriable error."+ )+ )+ message = serializers.CharField(+ allow_null=True,+ help_text=(+ "The stored message as the results page shows it, without the names that HogQL suggests and the list of "+ "a scope's fields. Null when it can hold evaluation rules that the AI evaluation markers keep out of the "+ "browser."+ ),+ )+++class ExperimentHealthInputsLatestCalculationSerializer(serializers.Serializer):+ finished_at = serializers.DateTimeField(+ allow_null=True,+ help_text="When the latest calculation that the results page shows finished. Null when none has finished.",+ )+ failures = ExperimentHealthInputsMetricCalculationFailureSerializer(+ many=True, help_text="The metrics whose latest calculation failed, with the error that the results page shows."+ )++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."@@ -3586,6 +3625,13 @@ class ExperimentHealthInputsSerializer(serializers.Serializer):"every request. Null when the compile itself failed."),)+ latest_calculation = ExperimentHealthInputsLatestCalculationSerializer(+ allow_null=True,+ help_text=(+ "The latest finished calculation of the metrics, which the metric results check reads. Null before "+ "launch, on an archived experiment, or when the read failed."+ ),+ )flag_history = ExperimentHealthInputsFlagHistorySerializer(allow_null=True,help_text=(diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex c1a6edabac3f..8da06659f90d 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -988,10 +988,24 @@ class EnterpriseExperimentsViewSet(reads a warehouse table or view the caller may not query is not checked for them. The findingnames each failing metric in the `evidence` keys `metric_N`, `metric_N_role`, `metric_N_error`(the error class, which is also the subcode of the first metric) and `metric_N_message` (the- compiler's message). It is a warning when a primary metric fails before the end, and info- otherwise. A failure inside ClickHouse, such as a type that the data holds, isn't found. A- failing metric compiles again on every request. A metric that compiles is cached per caller- for a day, so a cohort or table that is deleted after a compile can take up to a day to show.+ compiler's message). It is a warning when a primary metric fails, also after the end, because+ the calculation after the fix reads the events up to the end. It is info otherwise. A failure+ inside ClickHouse, such as a type that the data holds, isn't found. A failing metric compiles+ again on every request. A metric that compiles is cached per caller for a day, so a cohort or+ table that is deleted after a compile can take up to a day to show.++ `metric_calculation_failed` reports each metric whose latest calculation failed, from the+ latest finished calculation that the results page shows. It leaves out a metric that+ `metric_cannot_compile` reports. The subcode is the kind of the first failure: `busy`,+ `query_limit` (the query reached the read, memory, time or length limit), `settings` (a setting of+ the metric or the experiment), `not_enough_data`, `experiment_too_old` (the experiment+ started too long ago to calculate again) or `unexpected_error`. Each metric is in the+ `evidence` keys `metric_N`, `metric_N_role`, `metric_N_failure` (the kind), `metric_N_error`+ (the limit, or the family of a setting) and `metric_N_message` (only a message that PostHog+ wrote for users), and `calculated_at` is when the calculation finished. It is a+ warning when a primary metric fails for a kind that a change fixes (`query_limit`,+ `settings`, `experiment_too_old`), also after the end, because the calculation after the fix+ reads the events up to the end. It is info otherwise.The severity of the `some_conditions_pinned` finding follows the largest share that theusers of the pinned release conditions make up among the users who got one variant fromdiff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 16882a160ed3..33c4b952577d 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2305,6 +2305,7 @@ export type _ExperimentApiMetricsListApi = ExperimentApiMetricApi[]* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `srm` - Sample Ratio Mismatch* * `zero_exposures` - Zero Exposures@@ -2329,6 +2330,7 @@ export const ExperimentHealthFindingCodeEnumApi = {NoMetric: 'no_metric',MetricEventNotIngested: 'metric_event_not_ingested',MetricCannotCompile: 'metric_cannot_compile',+ MetricCalculationFailed: 'metric_calculation_failed',ExposureCriteriaCannotMatch: 'exposure_criteria_cannot_match',Srm: 'srm',ZeroExposures: 'zero_exposures',@@ -2396,6 +2398,7 @@ export interface ExperimentHealthFindingApi {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `srm` - Sample Ratio Mismatch* * `zero_exposures` - Zero Exposures@@ -2445,6 +2448,7 @@ export interface ExperimentHealthFindingApi {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `early_significance` - Early Significance* * `zero_exposures` - Zero Exposures@@ -2467,6 +2471,7 @@ export const ExperimentHealthCheckKeyEnumApi = {NoMetric: 'no_metric',MetricEventNotIngested: 'metric_event_not_ingested',MetricCannotCompile: 'metric_cannot_compile',+ MetricCalculationFailed: 'metric_calculation_failed',ExposureCriteriaCannotMatch: 'exposure_criteria_cannot_match',EarlySignificance: 'early_significance',ZeroExposures: 'zero_exposures',@@ -2505,6 +2510,7 @@ export interface ExperimentHealthCheckResultApi {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `early_significance` - Early Significance* * `zero_exposures` - Zero Exposures@@ -3287,6 +3293,40 @@ export interface ExperimentHealthInputsMetricCompilesApi {failures: ExperimentHealthInputsMetricCompileFailureApi[]}+export interface ExperimentHealthInputsMetricCalculationFailureApi {+ /** The metric's name as the experiment shows it. */+ name: string+ /** 'primary' or 'secondary'. */+ role: string+ /**+ * The class that the calculation stored for the error, such as 'timeout' or 'rate_limited'. Null for a failure stored without a class.+ * @nullable+ */+ error_type: string | null+ /**+ * The step of the calculation that failed, such as 'calculation'. Null when the failure names none.+ * @nullable+ */+ step: string | null+ /** Whether the results page shows a button to try the metric again, which it does for a retriable error. */+ retriable: boolean+ /**+ * The stored message as the results page shows it, without the names that HogQL suggests and the list of a scope's fields. Null when it can hold evaluation rules that the AI evaluation markers keep out of the browser.+ * @nullable+ */+ message: string | null+}++export interface ExperimentHealthInputsLatestCalculationApi {+ /**+ * When the latest calculation that the results page shows finished. Null when none has finished.+ * @nullable+ */+ finished_at: string | null+ /** The metrics whose latest calculation failed, with the error that the results page shows. */+ failures: ExperimentHealthInputsMetricCalculationFailureApi[]+}+/*** * `split` - Split* * `bucketing` - Bucketing@@ -3704,6 +3744,8 @@ export interface ExperimentHealthInputsApi {events_received: ExperimentHealthInputsApiEventsReceived/** The compile of each metric's query without running it, as the reader, which the metric queries check reads. A metric that compiles is cached per reader for a day, and a failing metric compiles again on every request. Null when the compile itself failed. */metric_compiles: ExperimentHealthInputsMetricCompilesApi | null+ /** The latest finished calculation of the metrics, which the metric results check reads. Null before launch, on an archived experiment, or when the read failed. */+ latest_calculation: ExperimentHealthInputsLatestCalculationApi | null/** 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/generated/api.ts b/products/experiments/frontend/generated/api.tsindex 1f90f3afe2c0..72ef229607a7 100644--- a/products/experiments/frontend/generated/api.ts+++ b/products/experiments/frontend/generated/api.ts@@ -733,10 +733,24 @@ export const getExperimentsHealthRetrieveUrl = (projectId: string, id: number) =* reads a warehouse table or view the caller may not query is not checked for them. The finding* names each failing metric in the `evidence` keys `metric_N`, `metric_N_role`, `metric_N_error`* (the error class, which is also the subcode of the first metric) and `metric_N_message` (the- * compiler's message). It is a warning when a primary metric fails before the end, and info- * otherwise. A failure inside ClickHouse, such as a type that the data holds, isn't found. A- * failing metric compiles again on every request. A metric that compiles is cached per caller- * for a day, so a cohort or table that is deleted after a compile can take up to a day to show.+ * compiler's message). It is a warning when a primary metric fails, also after the end, because+ * the calculation after the fix reads the events up to the end. It is info otherwise. A failure+ * inside ClickHouse, such as a type that the data holds, isn't found. A failing metric compiles+ * again on every request. A metric that compiles is cached per caller for a day, so a cohort or+ * table that is deleted after a compile can take up to a day to show.+ *+ * `metric_calculation_failed` reports each metric whose latest calculation failed, from the+ * latest finished calculation that the results page shows. It leaves out a metric that+ * `metric_cannot_compile` reports. The subcode is the kind of the first failure: `busy`,+ * `query_limit` (the query reached the read, memory, time or length limit), `settings` (a setting of+ * the metric or the experiment), `not_enough_data`, `experiment_too_old` (the experiment+ * started too long ago to calculate again) or `unexpected_error`. Each metric is in the+ * `evidence` keys `metric_N`, `metric_N_role`, `metric_N_failure` (the kind), `metric_N_error`+ * (the limit, or the family of a setting) and `metric_N_message` (only a message that PostHog+ * wrote for users), and `calculated_at` is when the calculation finished. It is a+ * warning when a primary metric fails for a kind that a change fixes (`query_limit`,+ * `settings`, `experiment_too_old`), also after the end, because the calculation after the fix+ * reads the events up to the end. It is info otherwise.** The severity of the `some_conditions_pinned` finding follows the largest share that the* users of the pinned release conditions make up among the users who got one variant fromdiff --git a/products/experiments/frontend/health/debug/healthDebugInputs.ts b/products/experiments/frontend/health/debug/healthDebugInputs.tsindex c817bd0dc7e7..f6ea002826b0 100644--- a/products/experiments/frontend/health/debug/healthDebugInputs.ts+++ b/products/experiments/frontend/health/debug/healthDebugInputs.ts@@ -322,9 +322,31 @@ export function buildMetricFacts(label: `Doesn't compile: ${failure.name} (${failure.role})`,value: `${failure.kind}: ${failure.message ?? 'message hidden, it can hold evaluation rules'}`,})),+ {+ label: 'Latest calculation',+ value: serverValue(state, (inputs) => describeLatestCalculation(inputs.latest_calculation)),+ help: 'The metric results check reads the latest finished calculation, which the results page shows.',+ },+ ...(state.inputs?.latest_calculation?.failures ?? []).map((failure) => ({+ label: `Failed: ${failure.name} (${failure.role})`,+ value: `${failure.error_type ?? 'no class'}${failure.retriable ? ', retriable' : ''}: ${+ failure.message ?? 'message hidden, it can hold evaluation rules'+ }`,+ })),]}+function describeLatestCalculation(calculation: ExperimentHealthInputsApi['latest_calculation']): string {+ if (!calculation) {+ return 'Not read: the experiment is not launched or is archived, or the read failed'+ }+ if (!calculation.finished_at) {+ return 'No calculation has finished'+ }+ const failed = calculation.failures.length+ return `Finished ${formatTimestamp(calculation.finished_at)}, ${failed} ${failed === 1 ? 'metric' : 'metrics'} failed`+}+function describeMetricCompiles(compiles: ExperimentHealthInputsApi['metric_compiles']): string {if (!compiles) {return 'Not compiled: the compile failed'diff --git a/products/experiments/frontend/health/debug/healthDebugReport.ts b/products/experiments/frontend/health/debug/healthDebugReport.tsindex 910f94795f18..fbd44cdcc86c 100644--- a/products/experiments/frontend/health/debug/healthDebugReport.ts+++ b/products/experiments/frontend/health/debug/healthDebugReport.ts@@ -240,6 +240,13 @@ function metricCompileNote({ evidence }: ExperimentHealthFindingApi): string {return `Doesn't compile: ${errors.join(', ')}.`}+function metricCalculationNote({ evidence }: ExperimentHealthFindingApi): string {+ const failures = Object.entries(evidence)+ .filter(([key]) => /^metric_\d+_failure$/.test(key))+ .map(([, value]) => value)+ return `Failed: ${failures.join(', ')}. Calculated at ${evidence.calculated_at}.`+}+function exposureCriteriaNote({ subcode, evidence }: ExperimentHealthFindingApi): string {return subcode === 'filter_on_another_flag'? `The query requires ${evidence.flag_key}, a filter requires ${evidence.filter_flag_keys}.`@@ -344,6 +351,7 @@ export function buildHealthDebugChecks(input: HealthDebugInput): HealthDebugChecnoMetricCheck(input),serverOnlyCheck(input, 'metric_event_not_ingested', metricEventNote, ['metrics', 'project']),serverOnlyCheck(input, 'metric_cannot_compile', metricCompileNote, ['metrics', 'experiment']),+ serverOnlyCheck(input, 'metric_calculation_failed', metricCalculationNote, ['metrics']),serverOnlyCheck(input, 'exposure_criteria_cannot_match', exposureCriteriaNote, ['experiment', 'project']),serverOnlyCheck(input, 'early_significance', null, ['experiment', 'metrics']),...exposureChecks(input),diff --git a/products/experiments/frontend/health/experimentHealthFindingEvents.ts b/products/experiments/frontend/health/experimentHealthFindingEvents.tsindex 56cc5427649a..02fb4fb5b909 100644--- a/products/experiments/frontend/health/experimentHealthFindingEvents.ts+++ b/products/experiments/frontend/health/experimentHealthFindingEvents.ts@@ -25,6 +25,7 @@ export type ExperimentHealthFindingCode =| 'no_metric'| 'metric_event_not_ingested'| 'metric_cannot_compile'+ | 'metric_calculation_failed'| 'exposure_criteria_cannot_match'| 'forced_variant_release_condition'| 'flag_variants_mismatch'diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex dc557db4b84b..5bdb30011a68 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -47345,6 +47345,7 @@ export namespace Schemas {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `srm` - Sample Ratio Mismatch* * `zero_exposures` - Zero Exposures@@ -47369,6 +47370,7 @@ export namespace Schemas {NoMetric: 'no_metric',MetricEventNotIngested: 'metric_event_not_ingested',MetricCannotCompile: 'metric_cannot_compile',+ MetricCalculationFailed: 'metric_calculation_failed',ExposureCriteriaCannotMatch: 'exposure_criteria_cannot_match',Srm: 'srm',ZeroExposures: 'zero_exposures',@@ -47436,6 +47438,7 @@ export namespace Schemas {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `srm` - Sample Ratio Mismatch* * `zero_exposures` - Zero Exposures@@ -47485,6 +47488,7 @@ export namespace Schemas {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `early_significance` - Early Significance* * `zero_exposures` - Zero Exposures@@ -47507,6 +47511,7 @@ export namespace Schemas {NoMetric: 'no_metric',MetricEventNotIngested: 'metric_event_not_ingested',MetricCannotCompile: 'metric_cannot_compile',+ MetricCalculationFailed: 'metric_calculation_failed',ExposureCriteriaCannotMatch: 'exposure_criteria_cannot_match',EarlySignificance: 'early_significance',ZeroExposures: 'zero_exposures',@@ -47545,6 +47550,7 @@ export namespace Schemas {* * `no_metric` - No Metric* * `metric_event_not_ingested` - Metric Event Not Ingested* * `metric_cannot_compile` - Metric Cannot Compile+ * * `metric_calculation_failed` - Metric Calculation Failed* * `exposure_criteria_cannot_match` - Exposure Criteria Cannot Match* * `early_significance` - Early Significance* * `zero_exposures` - Zero Exposures@@ -48278,6 +48284,40 @@ export namespace Schemas {failures: ExperimentHealthInputsMetricCompileFailure[];}+ export interface ExperimentHealthInputsMetricCalculationFailure {+ /** The metric's name as the experiment shows it. */+ name: string;+ /** 'primary' or 'secondary'. */+ role: string;+ /**+ * The class that the calculation stored for the error, such as 'timeout' or 'rate_limited'. Null for a failure stored without a class.+ * @nullable+ */+ error_type: string | null;+ /**+ * The step of the calculation that failed, such as 'calculation'. Null when the failure names none.+ * @nullable+ */+ step: string | null;+ /** Whether the results page shows a button to try the metric again, which it does for a retriable error. */+ retriable: boolean;+ /**+ * The stored message as the results page shows it, without the names that HogQL suggests and the list of a scope's fields. Null when it can hold evaluation rules that the AI evaluation markers keep out of the browser.+ * @nullable+ */+ message: string | null;+ }++ export interface ExperimentHealthInputsLatestCalculation {+ /**+ * When the latest calculation that the results page shows finished. Null when none has finished.+ * @nullable+ */+ finished_at: string | null;+ /** The metrics whose latest calculation failed, with the error that the results page shows. */+ failures: ExperimentHealthInputsMetricCalculationFailure[];+ }+export interface ExperimentHealthInputsFlagChange {/** The kind of change. A bucketing change is a change of a setting that decides the variant draw.*@@ -48682,6 +48722,8 @@ export namespace Schemas {events_received: ExperimentHealthInputsEventsReceived;/** The compile of each metric's query without running it, as the reader, which the metric queries check reads. A metric that compiles is cached per reader for a day, and a failing metric compiles again on every request. Null when the compile itself failed. */metric_compiles: ExperimentHealthInputsMetricCompiles | null;+ /** The latest finished calculation of the metrics, which the metric results check reads. Null before launch, on an archived experiment, or when the read failed. */+ latest_calculation: ExperimentHealthInputsLatestCalculation | null;/** 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.