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): Emit terminal metric-load failures from the backend (#67769)

Juraj Majerik9a33e3132c51
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 0176a361aec3..c62278c5fb90 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -745,40 +745,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
queryId,
context,
}),
- reportExperimentMetricError: (
- experimentId: ExperimentIdType,
- metric: ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery,
- teamId: number | null | undefined,
- queryId: string | null,
- context: {
- duration_ms: number
- metric_index: number
- is_primary: boolean
- is_retry: boolean
- refresh_id: string
- metric_kind: string
- error_type:
- | 'timeout'
- | 'out_of_memory'
- | 'server_error'
- | 'network_error'
- | 'not_found'
- | 'authentication'
- | 'authorization'
- | 'validation_error'
- | 'unknown'
- error_code: string | null
- error_message: string | null
- error_detail: string | null
- status_code: number | null
- }
- ) => ({
- experimentId,
- metric,
- teamId,
- queryId,
- context,
- }),
reportExperimentResultsRefreshCompleted: (
experimentId: ExperimentIdType,
teamId: number | null | undefined,
@@ -1906,15 +1872,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
...context,
})
},
- reportExperimentMetricError: ({ experimentId, metric, teamId, queryId, context }) => {
- posthog.capture('experiment metric error', {
- experiment_id: experimentId,
- team_id: teamId,
- query_id: queryId,
- ...getEventPropertiesForMetric(metric),
- ...context,
- })
- },
reportExperimentResultsRefreshCompleted: ({ experimentId, teamId, context }) => {
posthog.capture('experiment results refresh completed', {
experiment_id: experimentId,
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index d5807b7bd10b..5d9913e39a9b 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -19,14 +19,7 @@ import {
import { initKeaTests } from '~/test/init'
import { Experiment, MultivariateFlagVariant } from '~/types'
-import {
- ExperimentSavedMetric,
- ExperimentWarning,
- classifyError,
- experimentLogic,
- extractErrorDetailString,
- getDisplayOrderedIndices,
-} from './experimentLogic'
+import { ExperimentSavedMetric, ExperimentWarning, experimentLogic, getDisplayOrderedIndices } from './experimentLogic'
jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
lemonToast: {
@@ -1927,83 +1920,6 @@ describe('experimentLogic', () => {
})
})
- describe('classifyError', () => {
- it.each([
- // [description, errorDetail, errorMessage, errorCode, statusCode, expected]
- ['504 gateway timeout', null, null, null, 504, 'timeout'],
- ['408 request timeout', null, null, null, 408, 'timeout'],
- ['query timeout body marker', 'Query timed out', null, null, 200, 'timeout'],
- ['memory-limit error code', null, null, 'memory_limit_exceeded', 500, 'out_of_memory'],
- ['OOM message pattern', null, 'Memory limit exceeded while running', null, 500, 'out_of_memory'],
- ['generic 500', null, null, null, 500, 'server_error'],
- ['503 unavailable', null, null, null, 503, 'server_error'],
- ['status 0 is network', null, null, null, 0, 'network_error'],
- ['TypeError: Failed to fetch', null, 'TypeError: Failed to fetch', null, null, 'network_error'],
- ['TypeError: Load failed', null, 'TypeError: Load failed', null, null, 'network_error'],
- [
- "TypeError: Failed to execute 'fetch'",
- null,
- "TypeError: Failed to execute 'fetch' on 'Window'",
- null,
- null,
- 'network_error',
- ],
- ['NetworkError with null status', null, 'NetworkError when fetching', null, null, 'network_error'],
- ['404 not_found', null, 'Experiment with id 123 not found', 'not_found', 404, 'not_found'],
- ['401 unauthenticated', null, null, null, 401, 'authentication'],
- ['403 not_authenticated code', null, null, 'not_authenticated', 403, 'authentication'],
- ['403 permission_denied', null, null, 'permission_denied', 403, 'authorization'],
- ['plain 403', null, null, null, 403, 'authorization'],
- ['400 parse_error', null, null, 'parse_error', 400, 'validation_error'],
- ['400 invalid_input', null, null, 'invalid_input', 400, 'validation_error'],
- ['null status, no marker', null, 'Something odd', null, null, 'unknown'],
- ['418 teapot falls through', null, null, null, 418, 'unknown'],
- ] as const)('%s', (_desc, errorDetail, errorMessage, errorCode, statusCode, expected) => {
- expect(classifyError(errorDetail, errorMessage, errorCode, statusCode)).toEqual(expected)
- })
-
- it('prefers timeout over 5xx server_error (504 overlap)', () => {
- expect(classifyError(null, null, null, 504)).toEqual('timeout')
- })
-
- it('prefers out_of_memory over generic server_error', () => {
- expect(classifyError(null, null, 'query_memory_limit_exceeded', 500)).toEqual('out_of_memory')
- })
-
- it('does not treat fetch-style messages as network errors when an HTTP status was returned', () => {
- // A 400 response whose body happens to mention "Failed to fetch" should still classify by status, not network.
- expect(classifyError(null, 'Failed to fetch remote config', null, 400)).toEqual('validation_error')
- })
- })
-
- describe('extractErrorDetailString', () => {
- it.each([
- ['null → null', null, null],
- ['undefined → null', undefined, null],
- ['string passes through', 'Experiment with id 79259 not found', 'Experiment with id 79259 not found'],
- ['DRF {detail: "..."} unwraps the inner string', { detail: 'Not found.' }, 'Not found.'],
- [
- 'object without string detail falls back to JSON',
- { 'no-exposures': true, 'no-control-variant': false },
- '{"no-exposures":true,"no-control-variant":false}',
- ],
- [
- 'nested detail that is not a string falls back to JSON',
- { detail: { nested: 1 } },
- '{"detail":{"nested":1}}',
- ],
- ['array falls back to JSON', [1, 2, 3], '[1,2,3]'],
- ] as const)('%s', (_desc, input, expected) => {
- expect(extractErrorDetailString(input)).toEqual(expected)
- })
-
- it('returns null for values that cannot be stringified (circular refs)', () => {
- const circular: Record<string, unknown> = {}
- circular.self = circular
- expect(extractErrorDetailString(circular)).toBeNull()
- })
- })
-
describe('excluded variants', () => {
it('excludedVariants selector reads the excluded_variants column', async () => {
await expectLogic(logic, () => {
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 95be31a128df..3d4289d82729 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -36,7 +36,7 @@ import { urls } from 'scenes/urls'
import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { cohortsModel } from '~/models/cohortsModel'
import { groupsModel } from '~/models/groupsModel'
-import { QUERY_TIMEOUT_ERROR_MESSAGE, performQuery } from '~/queries/query'
+import { performQuery } from '~/queries/query'
import {
AnyEntityNode,
Breakdown,
@@ -241,16 +241,6 @@ interface MetricLoadingSummary {
cachedCount: number
}
-const OUT_OF_MEMORY_ERROR_CODES = new Set(['memory_limit_exceeded', 'query_memory_limit_exceeded'])
-
-function isOutOfMemoryError(errorCode: string | null, errorMessage: string | null): boolean {
- if (errorCode && OUT_OF_MEMORY_ERROR_CODES.has(errorCode)) {
- return true
- }
-
- return !!errorMessage && /(out of memory|memory limit exceeded|exceeded memory limit)/i.test(errorMessage)
-}
-
function parseMetricErrorDetail(error: any): { detail: any; hasDiagnostics: boolean } {
const errorDetailText = typeof error.detail === 'string' ? error.detail : null
const errorDetailMatch = errorDetailText?.match(/\{.*\}/)
@@ -266,88 +256,6 @@ function parseMetricErrorDetail(error: any): { detail: any; hasDiagnostics: bool
}
}
-// Coerces the parsed error detail into a flat string suitable for telemetry:
-// prefers DRF's `{"detail": "..."}` shape over a raw JSON blob so values group
-// readably in property breakdowns.
-export function extractErrorDetailString(errorDetail: unknown): string | null {
- if (errorDetail == null) {
- return null
- }
- if (typeof errorDetail === 'string') {
- return errorDetail
- }
- if (typeof errorDetail === 'object' && typeof (errorDetail as { detail?: unknown }).detail === 'string') {
- return (errorDetail as { detail: string }).detail
- }
- try {
- return JSON.stringify(errorDetail)
- } catch {
- return null
- }
-}
-
-function isTimeoutError(errorDetail: unknown, errorMessage: string | null, statusCode: number | null): boolean {
- if (statusCode === 504 || statusCode === 408) {
- return true
- }
-
- return errorDetail === QUERY_TIMEOUT_ERROR_MESSAGE || errorMessage === QUERY_TIMEOUT_ERROR_MESSAGE
-}
-
-const NETWORK_ERROR_MESSAGE_PATTERN = /(NetworkError|Failed to fetch|Load failed|Failed to execute 'fetch')/i
-
-function isNetworkError(errorCode: string | null, errorMessage: string | null, statusCode: number | null): boolean {
- if (errorCode === 'network_error' || statusCode === 0) {
- return true
- }
- // Only treat as network error when no HTTP response was received
- return statusCode === null && !!errorMessage && NETWORK_ERROR_MESSAGE_PATTERN.test(errorMessage)
-}
-
-export type ExperimentMetricErrorType =
- | 'timeout'
- | 'out_of_memory'
- | 'server_error'
- | 'network_error'
- | 'not_found'
- | 'authentication'
- | 'authorization'
- | 'validation_error'
- | 'unknown'
-
-export function classifyError(
- errorDetail: unknown,
- errorMessage: string | null,
- errorCode: string | null,
- statusCode: number | null
-): ExperimentMetricErrorType {
- if (isTimeoutError(errorDetail, errorMessage, statusCode)) {
- return 'timeout'
- }
- if (isOutOfMemoryError(errorCode, errorMessage)) {
- return 'out_of_memory'
- }
- if (statusCode !== null && statusCode >= 500) {
- return 'server_error'
- }
- if (isNetworkError(errorCode, errorMessage, statusCode)) {
- return 'network_error'
- }
- if (statusCode === 404) {
- return 'not_found'
- }
- if (statusCode === 401 || errorCode === 'not_authenticated') {
- return 'authentication'
- }
- if (statusCode === 403 || errorCode === 'permission_denied') {
- return 'authorization'
- }
- if (statusCode === 400) {
- return 'validation_error'
- }
- return 'unknown'
-}
-
/**
* Returns metric indices in display order. Metrics whose UUID appears in
* orderedUuids come first (in that order), followed by any remaining metrics
@@ -483,18 +391,10 @@ const loadMetrics = async ({
}
)
} catch (error: any) {
- const durationMs = Math.round(performance.now() - startTime)
const errorCode = typeof error.code === 'string' ? error.code : null
const statusCode = typeof error.status === 'number' ? error.status : null
- const errorMessage =
- typeof error.detail === 'string'
- ? error.detail
- : typeof error.message === 'string'
- ? error.message
- : null
const { detail: errorDetail, hasDiagnostics } = parseMetricErrorDetail(error)
const queryId = response?.query_status?.id || error.queryId || null
- const errorType = classifyError(errorDetail, errorMessage, errorCode, statusCode)
currentErrors[originalIndex] = {
detail: errorDetail,
@@ -508,19 +408,9 @@ const loadMetrics = async ({
erroredCount++
- eventUsageLogic.actions.reportExperimentMetricError(experimentId, metric, teamId, queryId, {
- duration_ms: durationMs,
- metric_index: metricIndex,
- is_primary: isPrimary,
- is_retry: isRetry,
- refresh_id: refreshId,
- metric_kind: metricKind,
- error_type: errorType,
- error_code: errorCode,
- error_message: errorMessage,
- error_detail: extractErrorDetailString(errorDetail),
- status_code: statusCode,
- })
+ // No telemetry here: the terminal `experiment metric error` event is emitted by the
+ // backend (see products/experiments/backend/hogql_queries/error_handling.py), which
+ // classifies from typed exceptions instead of HTTP status codes.
onSetResults([...results])
}
diff --git a/frontend/src/scenes/experiments/legacy/legacyExperimentLogic.tsx b/frontend/src/scenes/experiments/legacy/legacyExperimentLogic.tsx
index fb2b1acb52d8..98bd2fa75b72 100644
--- a/frontend/src/scenes/experiments/legacy/legacyExperimentLogic.tsx
+++ b/frontend/src/scenes/experiments/legacy/legacyExperimentLogic.tsx
@@ -3,7 +3,6 @@ import { actions, connect, kea, key, listeners, path, props, reducers, selectors
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { runWithLimit } from 'scenes/dashboard/dashboardUtils'
-import { classifyError, extractErrorDetailString } from 'scenes/experiments/experimentLogic'
import { isLegacyExperimentQuery, isLegacySharedMetric } from 'scenes/experiments/utils'
import { teamLogic } from 'scenes/teamLogic'
@@ -259,18 +258,10 @@ const loadLegacyMetrics = async ({
}
)
} catch (error: any) {
- const durationMs = Math.round(performance.now() - startTime)
const errorCode = typeof error.code === 'string' ? error.code : null
const statusCode = typeof error.status === 'number' ? error.status : null
- const errorMessage =
- typeof error.detail === 'string'
- ? error.detail
- : typeof error.message === 'string'
- ? error.message
- : null
const { detail: errorDetail, hasDiagnostics } = parseMetricErrorDetail(error)
const queryId = response?.query_status?.id || error.queryId || null
- const errorType = classifyError(errorDetail, errorMessage, errorCode, statusCode)
currentErrors[originalIndex] = {
detail: errorDetail,
@@ -284,19 +275,7 @@ const loadLegacyMetrics = async ({
erroredCount++
- eventUsageLogic.actions.reportExperimentMetricError(experimentId, metric, teamId, queryId, {
- duration_ms: durationMs,
- metric_index: metricIndex,
- is_primary: isPrimary,
- is_retry: isRetry,
- refresh_id: refreshId,
- metric_kind: metricKind,
- error_type: errorType,
- error_code: errorCode,
- error_message: errorMessage,
- error_detail: extractErrorDetailString(errorDetail),
- status_code: statusCode,
- })
+ // No telemetry here: the terminal `experiment metric error` event is emitted by the backend.
legacyResults[originalIndex] = null
onSetLegacyResults([...legacyResults])
diff --git a/posthog/management/commands/populate_experiment_timeseries.py b/posthog/management/commands/populate_experiment_timeseries.py
index b53cd76b3d89..676e842e063d 100644
--- a/posthog/management/commands/populate_experiment_timeseries.py
+++ b/posthog/management/commands/populate_experiment_timeseries.py
@@ -128,8 +128,11 @@ class Command(BaseCommand):
metric=metric_obj,
)
- # Evaluate the experiment as of query_to_utc (clamped to end_date inside the runner)
- query_runner = ExperimentQueryRunner(query=experiment_query, team=experiment.team, as_of=query_to_utc)
+ # Evaluate the experiment as of query_to_utc (clamped to end_date inside the runner).
+ # error_event_context=None: an ops backfill is not user-visible pain.
+ query_runner = ExperimentQueryRunner(
+ query=experiment_query, team=experiment.team, as_of=query_to_utc, error_event_context=None
+ )
result = query_runner._calculate()
result_data = result.model_dump()
diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.py
index 7ca81c3216dd..6bdf84286d8b 100644
--- a/posthog/temporal/experiments/activities.py
+++ b/posthog/temporal/experiments/activities.py
@@ -16,6 +16,7 @@ from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat_sync import HeartbeaterSync
from posthog.temporal.experiments.models import (
+ TIMESERIES_METRIC_MAX_ATTEMPTS,
ExperimentRegularMetricInput,
ExperimentRegularMetricResult,
ExperimentSavedMetricInput,
@@ -28,6 +29,7 @@ from posthog.temporal.experiments.utils import (
)
from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_end
+from products.experiments.backend.hogql_queries.error_handling import capture_experiment_metric_error_event
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
@@ -118,6 +120,7 @@ def _calculate_experiment_regular_metric_sync(
experiment_id: int,
metric_uuid: str,
fingerprint: str,
+ attempt: int = 1,
) -> ExperimentRegularMetricResult:
close_old_connections()
@@ -199,6 +202,10 @@ def _calculate_experiment_regular_metric_sync(
# Scheduled recalc has no request user. Attribute the query to the experiment's creator so
# warehouse HogQL access control is enforced.
user=experiment.created_by,
+ # Internal caller: keep exceptions raw so the except branches below see original types
+ # (StatisticError must not arrive pre-converted to ValidationError). Also silences the
+ # runner-level error event — this activity emits its own, on the final attempt.
+ user_facing=False,
)
# .run() writes to the response cache. The "warming/*" trigger tells
# run() this is a scheduled job, not a user query, so it skips logging
@@ -262,6 +269,18 @@ def _calculate_experiment_regular_metric_sync(
error=str(e),
)
+ # Permanent failure, returned (not raised) — terminal on the first attempt.
+ capture_experiment_metric_error_event(
+ team=experiment.team,
+ error=e,
+ context="scheduled",
+ mechanism="orchestrated",
+ experiment_id=experiment_id,
+ metric_uuid=metric_uuid,
+ metric_kind=metric_type,
+ user=experiment.created_by,
+ )
+
return ExperimentRegularMetricResult(
experiment_id=experiment_id,
metric_uuid=metric_uuid,
@@ -292,6 +311,20 @@ def _calculate_experiment_regular_metric_sync(
metric_uuid=metric_uuid,
)
+ # Temporal retries this activity; emit only when retries are exhausted so a transient
+ # failure that recovers on a later attempt is never counted.
+ if attempt >= TIMESERIES_METRIC_MAX_ATTEMPTS:
+ capture_experiment_metric_error_event(
+ team=experiment.team,
+ error=e,
+ context="scheduled",
+ mechanism="orchestrated",
+ experiment_id=experiment_id,
+ metric_uuid=metric_uuid,
+ metric_kind=metric_type,
+ user=experiment.created_by,
+ )
+
raise
@@ -302,7 +335,9 @@ async def calculate_experiment_regular_metric(
fingerprint: str,
) -> ExperimentRegularMetricResult:
"""Calculate timeseries results for a single experiment-metric combination."""
- return await _calculate_experiment_regular_metric_sync(experiment_id, metric_uuid, fingerprint)
+ return await _calculate_experiment_regular_metric_sync(
+ experiment_id, metric_uuid, fingerprint, attempt=temporalio.activity.info().attempt
+ )
@database_sync_to_async
@@ -376,6 +411,7 @@ def _calculate_experiment_saved_metric_sync(
experiment_id: int,
metric_uuid: str,
fingerprint: str,
+ attempt: int = 1,
) -> ExperimentSavedMetricResult:
close_old_connections()
@@ -471,6 +507,10 @@ def _calculate_experiment_saved_metric_sync(
# Scheduled recalc has no request user. Attribute the query to the experiment's creator so
# warehouse HogQL access control is enforced.
user=experiment.created_by,
+ # Internal caller: keep exceptions raw so the except branches below see original types
+ # (StatisticError must not arrive pre-converted to ValidationError). Also silences the
+ # runner-level error event — this activity emits its own, on the final attempt.
+ user_facing=False,
)
# .run() writes to the response cache. The "warming/*" trigger tells
# run() this is a scheduled job, not a user query, so it skips logging
@@ -534,6 +574,18 @@ def _calculate_experiment_saved_metric_sync(
error=str(e),
)
+ # Permanent failure, returned (not raised) — terminal on the first attempt.
+ capture_experiment_metric_error_event(
+ team=experiment.team,
+ error=e,
+ context="scheduled",
+ mechanism="orchestrated",
+ experiment_id=experiment_id,
+ metric_uuid=metric_uuid,
+ metric_kind=metric_type,
+ user=experiment.created_by,
+ )
+
return ExperimentSavedMetricResult(
experiment_id=experiment_id,
metric_uuid=metric_uuid,
@@ -564,6 +616,20 @@ def _calculate_experiment_saved_metric_sync(
metric_uuid=metric_uuid,
)
+ # Temporal retries this activity; emit only when retries are exhausted so a transient
+ # failure that recovers on a later attempt is never counted.
+ if attempt >= TIMESERIES_METRIC_MAX_ATTEMPTS:
+ capture_experiment_metric_error_event(
+ team=experiment.team,
+ error=e,
+ context="scheduled",
+ mechanism="orchestrated",
+ experiment_id=experiment_id,
+ metric_uuid=metric_uuid,
+ metric_kind=metric_type,
+ user=experiment.created_by,
+ )
+
raise
@@ -574,7 +640,9 @@ async def calculate_experiment_saved_metric(
fingerprint: str,
) -> ExperimentSavedMetricResult:
"""Calculate timeseries results for a single experiment-saved metric combination."""
- return await _calculate_experiment_saved_metric_sync(experiment_id, metric_uuid, fingerprint)
+ return await _calculate_experiment_saved_metric_sync(
+ experiment_id, metric_uuid, fingerprint, attempt=temporalio.activity.info().attempt
+ )
def _backfill_experiment_metric_sync(recalculation_id: str) -> dict[str, Any]:
@@ -635,6 +703,8 @@ def _backfill_experiment_metric_sync(recalculation_id: str) -> dict[str, Any]:
# Scheduled backfill has no request user. Attribute the query to the experiment's creator
# so warehouse HogQL access control is enforced.
user=experiment.created_by,
+ # Backfilling historical points is not user-visible pain — no terminal error event.
+ error_event_context=None,
)
result = query_runner._calculate()
diff --git a/posthog/temporal/experiments/models.py b/posthog/temporal/experiments/models.py
index 3c959e47809c..26c19b97bc39 100644
--- a/posthog/temporal/experiments/models.py
+++ b/posthog/temporal/experiments/models.py
@@ -1,5 +1,10 @@
import dataclasses
+# Temporal retry ceiling for the per-metric calc activities. Shared with the activity code, which emits the
+# terminal `experiment metric error` analytics event only on the final attempt — keep the RetryPolicy in
+# workflows.py and this constant in lockstep or terminal failures get emitted early / not at all.
+TIMESERIES_METRIC_MAX_ATTEMPTS = 3
+
@dataclasses.dataclass
class ExperimentRegularMetricsWorkflowInputs:
diff --git a/posthog/temporal/experiments/workflows.py b/posthog/temporal/experiments/workflows.py
index bc351bd5f5d5..c7221dcfd243 100644
--- a/posthog/temporal/experiments/workflows.py
+++ b/posthog/temporal/experiments/workflows.py
@@ -15,6 +15,7 @@ with temporalio.workflow.unsafe.imports_passed_through():
get_experiment_saved_metrics_for_hour,
)
from posthog.temporal.experiments.models import (
+ TIMESERIES_METRIC_MAX_ATTEMPTS,
ExperimentRegularMetricsWorkflowInputs,
ExperimentSavedMetricsWorkflowInputs,
ExperimentTimeseriesRecalculationWorkflowInputs,
@@ -66,7 +67,7 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):
args=[em.experiment_id, em.metric_uuid, em.fingerprint],
start_to_close_timeout=timedelta(minutes=15),
retry_policy=RetryPolicy(
- maximum_attempts=3,
+ maximum_attempts=TIMESERIES_METRIC_MAX_ATTEMPTS,
initial_interval=timedelta(seconds=10),
maximum_interval=timedelta(seconds=60),
),
@@ -138,7 +139,7 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):
args=[em.experiment_id, em.metric_uuid, em.fingerprint],
start_to_close_timeout=timedelta(minutes=15),
retry_policy=RetryPolicy(
- maximum_attempts=3,
+ maximum_attempts=TIMESERIES_METRIC_MAX_ATTEMPTS,
initial_interval=timedelta(seconds=10),
maximum_interval=timedelta(seconds=60),
),
diff --git a/products/experiments/backend/experiment_summary_data_service.py b/products/experiments/backend/experiment_summary_data_service.py
index d5992cca0a4c..3bd68aa8bd71 100644
--- a/products/experiments/backend/experiment_summary_data_service.py
+++ b/products/experiments/backend/experiment_summary_data_service.py
@@ -205,6 +205,7 @@ class ExperimentSummaryDataService:
limit_context=LimitContext.QUERY_ASYNC,
# Runs for the requesting Max user, so warehouse access is enforced against them.
user=self._user,
+ error_event_context="agent",
)
result = query_runner.run(
execution_mode=execution_mode,
@@ -257,6 +258,7 @@ class ExperimentSummaryDataService:
query=exposure_query,
team=experiment.team,
limit_context=LimitContext.QUERY_ASYNC,
+ error_event_context="agent",
)
exposure_result = exposure_runner.run(
execution_mode=execution_mode,
diff --git a/products/experiments/backend/hogql_queries/error_handling.py b/products/experiments/backend/hogql_queries/error_handling.py
index 5466ad562750..abe69f591692 100644
--- a/products/experiments/backend/hogql_queries/error_handling.py
+++ b/products/experiments/backend/hogql_queries/error_handling.py
@@ -5,24 +5,39 @@ while technical details are logged for engineers.
import functools
from collections.abc import Callable
-from typing import Any, TypeVar, cast
+from typing import TYPE_CHECKING, Any, Optional, TypeVar, cast
import structlog
+from clickhouse_driver.errors import ServerException
from rest_framework.exceptions import ValidationError
from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError
-from posthog.errors import ExposedCHQueryError
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
+from posthog.errors import ExposedCHQueryError, QueryErrorCategory, look_up_clickhouse_error_code_meta
+from posthog.event_usage import groups
+from posthog.exceptions import (
+ ClickHouseAtCapacity,
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQueryTimeOut,
+)
from posthog.exceptions_capture import capture_exception
+from posthog.ph_client import ph_scoped_capture
from products.experiments.stats.shared.statistics import StatisticError
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+ from posthog.models.user import User
+
# Map error types to their error codes for the API response
ERROR_TYPE_TO_CODE: dict[type, str] = {
ClickHouseQueryMemoryLimitExceeded: "memory_limit_exceeded",
}
+_MAX_ERROR_EVENT_MESSAGE_LENGTH = 500
+
logger = structlog.get_logger(__name__)
F = TypeVar("F", bound=Callable[..., Any])
@@ -80,6 +95,121 @@ def get_user_friendly_message(error: Exception) -> str | None:
return None
+def classify_experiment_query_error(error: Exception) -> str:
+ """Single failure taxonomy for the `experiment metric error` event, derived from the typed
+ exceptions `posthog/errors.py` already produces — never from message parsing or HTTP status.
+
+ Values: timeout · out_of_memory · byte_limit · rate_limited · insufficient_data ·
+ validation_error · server_error (catch-all).
+ """
+ if isinstance(error, (StatisticError, ZeroDivisionError)):
+ return "insufficient_data"
+ if isinstance(error, (ValidationError, ExposedHogQLError)):
+ return "validation_error"
+ if isinstance(error, (ClickHouseQueryTimeOut, ClickHouseEstimatedQueryExecutionTimeTooLong)):
+ return "timeout"
+ if isinstance(error, ClickHouseQueryMemoryLimitExceeded):
+ return "out_of_memory"
+ if isinstance(error, (ClickHouseAtCapacity, ConcurrencyLimitExceeded)):
+ return "rate_limited"
+ if isinstance(error, ServerException):
+ meta = look_up_clickhouse_error_code_meta(error)
+ if meta.name in ("TIMEOUT_EXCEEDED", "SOCKET_TIMEOUT"):
+ return "timeout"
+ if meta.name == "MEMORY_LIMIT_EXCEEDED":
+ return "out_of_memory"
+ if meta.name in ("TOO_MANY_BYTES", "TOO_MANY_ROWS", "TOO_MANY_ROWS_OR_BYTES"):
+ return "byte_limit"
+ if meta.get_category() == QueryErrorCategory.RATE_LIMITED:
+ return "rate_limited"
+ return "server_error"
+
+
+def capture_experiment_metric_error_event(
+ *,
+ team: "Team",
+ error: Exception,
+ context: str,
+ mechanism: str,
+ experiment_id: int | None,
+ metric_uuid: str | None = None,
+ metric_kind: str | None = None,
+ query_kind: str | None = None,
+ user: Optional["User"] = None,
+ extra_properties: dict[str, Any] | None = None,
+) -> None:
+ """Emit the terminal `experiment metric error` product analytics event.
+
+ Call this exactly once per user-visible failure, from the layer that owns retries for its
+ execution path (the runner where nothing above retries; the orchestrator's final attempt
+ otherwise). Telemetry must never fail the caller, so any capture error is swallowed.
+ """
+ try:
+ distinct_id = user.distinct_id if user is not None and user.distinct_id else f"team_{team.id}"
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=distinct_id,
+ event="experiment metric error",
+ properties={
+ "experiment_id": experiment_id,
+ "team_id": team.id,
+ "metric_uuid": metric_uuid,
+ "metric_kind": metric_kind,
+ "query_kind": query_kind,
+ "error_type": classify_experiment_query_error(error),
+ "error_message": str(error)[:_MAX_ERROR_EVENT_MESSAGE_LENGTH],
+ "context": context,
+ "mechanism": mechanism,
+ **(extra_properties or {}),
+ },
+ groups=groups(organization=team.organization, team=team),
+ )
+ except Exception:
+ logger.warning(
+ "experiment_metric_error_event_capture_failed",
+ experiment_id=experiment_id,
+ metric_uuid=metric_uuid,
+ exc_info=True,
+ )
+
+
+def _emit_runner_terminal_error_event(runner: Any, error: Exception) -> None:
+ """Emit the terminal failure event for a query runner on the direct (in-request) path.
+
+ Gated on the runner's `error_event_context` ("ui"/"agent"; None = silent) AND `user_facing`
+ (internal callers — recalc, canary, warming — own their retries, so a runner-level emit there
+ would count non-terminal attempts). One runner execution is terminal on every direct path:
+ the frontend has no automatic retry loop and the async Celery task swallows failures
+ (no retry passes back through the runner).
+ """
+ if runner is None:
+ return
+ context = getattr(runner, "error_event_context", None)
+ if not context or not getattr(runner, "user_facing", True):
+ return
+ team = getattr(runner, "team", None)
+ if team is None:
+ return
+
+ experiment_id = getattr(runner, "experiment_id", None)
+ if experiment_id is None:
+ experiment_id = getattr(getattr(runner, "experiment", None), "id", None)
+ metric = getattr(runner, "metric", None)
+ query = getattr(runner, "query", None)
+
+ capture_experiment_metric_error_event(
+ team=team,
+ error=error,
+ context=context,
+ mechanism="direct",
+ experiment_id=experiment_id,
+ metric_uuid=getattr(metric, "uuid", None),
+ metric_kind=getattr(metric, "metric_type", None),
+ query_kind=type(query).__name__ if query is not None else None,
+ user=getattr(runner, "user", None),
+ )
+
+
def experiment_error_handler(method: F) -> F:
"""
Decorator that catches technical errors, logs them for engineers,
@@ -90,8 +220,10 @@ def experiment_error_handler(method: F) -> F:
def wrapper(*args, **kwargs):
try:
return method(*args, **kwargs)
- except (ValidationError, ExposedHogQLError):
- # ValidationErrors and ExposedHogQLErrors are already user-facing, let them through
+ except (ValidationError, ExposedHogQLError) as e:
+ # ValidationErrors and ExposedHogQLErrors are already user-facing, let them through.
+ # Still terminal user pain (the metric fails to load every time), so still counted.
+ _emit_runner_terminal_error_event(args[0] if args else None, e)
raise
except Exception as e:
# Get context for logging
@@ -134,6 +266,8 @@ def experiment_error_handler(method: F) -> F:
},
)
+ _emit_runner_terminal_error_event(self, e)
+
# If this is not user-facing, re-raise the original exception after logging/capturing
user_facing = True
if self is not None:
diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
index fbe8b16c4fe4..f8e3bd22b899 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
@@ -58,8 +58,10 @@ class ExperimentExposuresQueryRunner(QueryRunner):
query: ExperimentExposureQuery
cached_response: CachedExperimentExposureQueryResponse
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args, error_event_context: str | None = "ui", **kwargs):
super().__init__(*args, **kwargs)
+ # See ExperimentQueryRunner.__init__ — tags the terminal error event; None = silent.
+ self.error_event_context = error_event_context
if not self.query.experiment_id:
raise ValidationError("experiment_id is required")
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 03971dae2c4f..6fbee6183dda 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -135,12 +135,18 @@ class ExperimentQueryRunner(QueryRunner):
user_facing: bool = True,
max_execution_time: Optional[int] = None,
bypass_warehouse_access_control: bool = False,
+ error_event_context: Optional[str] = "ui",
**kwargs,
):
super().__init__(*args, **kwargs)
self.user_facing = user_facing
self.max_execution_time = max_execution_time if max_execution_time is not None else MAX_EXECUTION_TIME
self.bypass_warehouse_access_control = bypass_warehouse_access_control
+ # Tags the terminal `experiment metric error` event with where the load came from. Defaults to "ui"
+ # because the generic /query API path constructs runners without kwargs; internal callers that own
+ # their own retries/telemetry (recalc, warming, canary, backfills) must pass None or user_facing=False
+ # so the error boundary stays silent for them. See error_handling._emit_runner_terminal_error_event.
+ self.error_event_context = error_event_context
if not self.query.experiment_id:
raise ValidationError("experiment_id is required")
diff --git a/products/experiments/backend/hogql_queries/test/test_error_handling.py b/products/experiments/backend/hogql_queries/test/test_error_handling.py
index 38dc04290425..a64b4d36131f 100644
--- a/products/experiments/backend/hogql_queries/test/test_error_handling.py
+++ b/products/experiments/backend/hogql_queries/test/test_error_handling.py
@@ -1,19 +1,45 @@
"""Tests for experiment error handling decorator and error message mapping."""
+from contextlib import contextmanager
from typing import cast
from posthog.test.base import BaseTest
from unittest.mock import Mock, patch
+from clickhouse_driver.errors import ServerException
+from parameterized import parameterized
from rest_framework.exceptions import ErrorDetail, ValidationError
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded
+from posthog.hogql.errors import ExposedHogQLError
+
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
from products.experiments.backend.hogql_queries.error_handling import (
ERROR_TYPE_TO_CODE,
+ classify_experiment_query_error,
experiment_error_handler,
get_user_friendly_message,
)
+from products.experiments.stats.shared.statistics import StatisticError
+
+
+@contextmanager
+def _record_captures():
+ captured: list[dict] = []
+
+ def _fake_capture(*args, **kwargs) -> None:
+ captured.append(kwargs)
+
+ @contextmanager
+ def _fake_scoped_capture():
+ yield _fake_capture
+
+ with patch(
+ "products.experiments.backend.hogql_queries.error_handling.ph_scoped_capture",
+ _fake_scoped_capture,
+ ):
+ yield captured
class TestExperimentErrorHandling(BaseTest):
@@ -124,3 +150,92 @@ class TestExperimentErrorHandling(BaseTest):
"""Test that ClickHouseQueryMemoryLimitExceeded has a code mapping."""
self.assertIn(ClickHouseQueryMemoryLimitExceeded, ERROR_TYPE_TO_CODE)
self.assertEqual(ERROR_TYPE_TO_CODE[ClickHouseQueryMemoryLimitExceeded], "memory_limit_exceeded")
+
+ @parameterized.expand(
+ [
+ ("wrapped_timeout", ClickHouseQueryTimeOut(), "timeout"),
+ ("ch_timeout_code", ServerException("timed out", code=159), "timeout"),
+ ("wrapped_oom", ClickHouseQueryMemoryLimitExceeded(), "out_of_memory"),
+ ("ch_memory_limit_code", ServerException("memory limit", code=241), "out_of_memory"),
+ ("ch_too_many_bytes_code", ServerException("too many bytes", code=307), "byte_limit"),
+ ("wrapped_at_capacity", ClickHouseAtCapacity(), "rate_limited"),
+ ("app_concurrency_limit", ConcurrencyLimitExceeded("app:query:per-org"), "rate_limited"),
+ ("ch_too_many_queries_code", ServerException("too many queries", code=202), "rate_limited"),
+ ("statistic_error", StatisticError("not enough data"), "insufficient_data"),
+ ("zero_division", ZeroDivisionError(), "insufficient_data"),
+ ("validation_error", ValidationError("bad metric config"), "validation_error"),
+ ("exposed_hogql_error", ExposedHogQLError("unknown property"), "validation_error"),
+ ("anything_else", RuntimeError("kaboom"), "server_error"),
+ ]
+ )
+ def test_classify_experiment_query_error(self, _name, error, expected):
+ # The taxonomy contract behind every 'experiment metric error' emitter. byte_limit (307) and
+ # rate_limited (202) are the buckets that historically collapsed into server_error, hiding the
+ # two biggest real failure modes — a regression here makes them invisible again.
+ self.assertEqual(classify_experiment_query_error(error), expected)
+
+
+class _FakeRunner:
+ """Minimal stand-in exposing the attributes the error boundary reads off a query runner."""
+
+ def __init__(self, team, *, error, error_event_context="ui", user_facing=True):
+ self.team = team
+ self.error_event_context = error_event_context
+ self.user_facing = user_facing
+ self.experiment_id = 42
+ self.metric = None
+ self.query = None
+ self.user = None
+ self._error = error
+
+ @experiment_error_handler
+ def _calculate(self):
+ raise self._error
+
+
+class TestTerminalErrorEventEmission(BaseTest):
+ """The error boundary is the single terminal emitter for direct (in-request) paths. Over-emission
+ double-counts retried orchestrated attempts; under-emission makes UI/agent failures invisible."""
+
+ def test_emits_terminal_event_with_context_and_mechanism(self):
+ runner = _FakeRunner(self.team, error=ServerException("too many bytes", code=307))
+
+ with _record_captures() as captured, self.assertRaises(ServerException):
+ runner._calculate()
+
+ assert len(captured) == 1
+ assert captured[0]["event"] == "experiment metric error"
+ props = captured[0]["properties"]
+ assert props["error_type"] == "byte_limit"
+ assert props["context"] == "ui"
+ assert props["mechanism"] == "direct"
+ assert props["experiment_id"] == 42
+ assert props["team_id"] == self.team.id
+ assert captured[0]["distinct_id"] == f"team_{self.team.id}"
+
+ def test_user_facing_validation_errors_still_emit(self):
+ # ValidationError/ExposedHogQLError pass through the boundary unconverted, but a misconfigured
+ # metric fails every load — terminal user pain that must be counted, tagged validation_error.
+ runner = _FakeRunner(self.team, error=ValidationError("bad metric"))
+
+ with _record_captures() as captured, self.assertRaises(ValidationError):
+ runner._calculate()
+
+ assert len(captured) == 1
+ assert captured[0]["properties"]["error_type"] == "validation_error"
+
+ @parameterized.expand(
+ [
+ ("no_context", {"error_event_context": None, "user_facing": True}),
+ ("internal_caller", {"error_event_context": "ui", "user_facing": False}),
+ ]
+ )
+ def test_internal_callers_stay_silent(self, _name, runner_kwargs):
+ # Recalc, canary, warming, and backfills own their retries and telemetry; a runner-level emit
+ # there would count non-terminal attempts (or double-count next to the orchestrator's emit).
+ runner = _FakeRunner(self.team, error=RuntimeError("kaboom"), **runner_kwargs)
+
+ with _record_captures() as captured, self.assertRaises(RuntimeError):
+ runner._calculate()
+
+ assert captured == []
diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.py
index 0cd56a376a3e..149b1b8d0b8e 100644
--- a/products/experiments/backend/temporal/models.py
+++ b/products/experiments/backend/temporal/models.py
@@ -18,6 +18,19 @@ MAX_CANARY_DETAIL_LENGTH = 1000
# each extra attempt adds backoff (5s, 10s, 20s, ...) to the tail of a fully-failing run.
MAX_METRIC_ATTEMPTS = 3
+# Per-attempt ceiling for the calc activity (its start_to_close_timeout). The activity has no heartbeat, so
+# this is the real per-attempt limit — when it fires, Temporal kills the attempt from the outside and nothing
+# inside the activity (result persistence, the terminal error event) runs.
+METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS = 300
+
+# ClickHouse max_execution_time for the recalc metric query. Deliberately below
+# METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS (minus headroom for metric build, stats, and persistence) so a slow
+# query fails INSIDE the activity with a typed ClickHouse error (159 TIMEOUT_EXCEEDED) instead of the activity
+# being killed by Temporal — which would lose the error type, the FAILED result row, and the terminal event.
+# A query needing more than this was already doomed to lose its attempt at the 5-minute kill; failing fast
+# also stops the orphaned query from burning ClickHouse for the full default 600s.
+METRIC_CALC_MAX_EXECUTION_TIME_SECONDS = 270
+
@dataclasses.dataclass
class ExperimentMetricsRecalculationWorkflowInputs:
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 01631485fc14..222c3287f333 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -13,20 +13,13 @@ from django.db import close_old_connections, transaction
from django.utils import timezone
import structlog
-from clickhouse_driver.errors import ServerException
from temporalio.exceptions import ApplicationError
from posthog.schema import ExperimentQuery
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.errors import look_up_clickhouse_error_code_meta
from posthog.event_usage import groups
-from posthog.exceptions import (
- ClickHouseEstimatedQueryExecutionTimeTooLong,
- ClickHouseQueryMemoryLimitExceeded,
- ClickHouseQueryTimeOut,
-)
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models.scoping import team_scope
@@ -34,6 +27,7 @@ from posthog.ph_client import ph_scoped_capture
from posthog.sync import database_sync_to_async
from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_end
+from products.experiments.backend.hogql_queries.error_handling import classify_experiment_query_error
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
@@ -44,6 +38,7 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.temporal.metric_resolution import build_metric, find_metric_dict
from products.experiments.backend.temporal.models import (
+ METRIC_CALC_MAX_EXECUTION_TIME_SECONDS,
ExperimentMetricToRecalculate,
MetricRecalculationResult,
RecalculationProgressUpdate,
@@ -75,6 +70,7 @@ class _RecalcState:
experiment_id: int
metric_uuids: list[str]
query_to: datetime | None
+ trigger: str | None
def _get_recalc_state(recalculation_id: str) -> _RecalcState:
@@ -82,7 +78,7 @@ def _get_recalc_state(recalculation_id: str) -> _RecalcState:
row = (
ExperimentMetricsRecalculation.objects.unscoped()
.filter(id=recalculation_id)
- .values("team_id", "experiment_id", "metric_uuids", "query_to")
+ .values("team_id", "experiment_id", "metric_uuids", "query_to", "trigger")
.first()
)
if row is None:
@@ -97,6 +93,7 @@ def _get_recalc_state(recalculation_id: str) -> _RecalcState:
experiment_id=row["experiment_id"],
metric_uuids=row["metric_uuids"] or [],
query_to=row["query_to"],
+ trigger=row["trigger"],
)
@@ -381,6 +378,7 @@ def _capture_experiment_metric_event(
metric_dict: dict | None,
event: str,
extra_properties: dict[str, Any],
+ trigger: str | None = None,
) -> None:
"""Emit a per-metric product analytics event. Telemetry must never fail the activity, so any error
is swallowed. Attributed to the experiment creator, falling back to a team-scoped distinct_id.
@@ -388,6 +386,9 @@ def _capture_experiment_metric_event(
`metric_type` is the primary/secondary classification carried from discovery
(`ExperimentMetricToRecalculate.metric_type`), threaded through the workflow + activity args so the
capture path doesn't have to re-query the M2M to resolve it.
+
+ Every recalc trigger is user-originated (manual click, page load, stale/auto refresh), so context is
+ "ui" with mechanism "orchestrated"; `trigger` carries the finer-grained origin.
"""
try:
team = experiment.team
@@ -407,6 +408,9 @@ def _capture_experiment_metric_event(
"metric_kind": (metric_dict or {}).get("metric_type"),
"is_primary": metric_type == "primary",
"execution_mode": "recalculation",
+ "context": "ui",
+ "mechanism": "orchestrated",
+ "trigger": trigger,
**extra_properties,
},
groups=groups(organization=team.organization, team=team),
@@ -421,22 +425,6 @@ def _capture_experiment_metric_event(
)
-# error_type values mirror the client-side `classifyError` taxonomy (experimentLogic.tsx) so
-# recalculation failures land on the same dashboards as the legacy client events.
-def _classify_query_error_type(e: Exception) -> str:
- if isinstance(e, (ClickHouseQueryTimeOut, ClickHouseEstimatedQueryExecutionTimeTooLong)):
- return "timeout"
- if isinstance(e, ClickHouseQueryMemoryLimitExceeded):
- return "out_of_memory"
- if isinstance(e, ServerException):
- name = look_up_clickhouse_error_code_meta(e).name
- if name in ("TIMEOUT_EXCEEDED", "SOCKET_TIMEOUT"):
- return "timeout"
- if name == "MEMORY_LIMIT_EXCEEDED":
- return "out_of_memory"
- return "server_error"
-
-
# ---------------------------------------------------------------------------
# Calculation
# ---------------------------------------------------------------------------
@@ -545,6 +533,13 @@ def _calculate_experiment_metric_for_recalculation_sync(
# Userless background recompute. Warehouse access is enforced when the metric is authored,
# so resolve warehouse tables here instead of failing closed.
bypass_warehouse_access_control=True,
+ # Internal caller: keep exceptions raw so the except branches below see the original types
+ # (StatisticError must not arrive pre-converted to ValidationError), and keep the runner's
+ # own error event silent — this activity emits the terminal event itself, on the final attempt.
+ user_facing=False,
+ error_event_context=None,
+ # Must fail typed inside the activity before Temporal's start_to_close kill — see models.py.
+ max_execution_time=METRIC_CALC_MAX_EXECUTION_TIME_SECONDS,
)
# Attribute CH load back to this team + product so query_log analysis can tell whose recalc is
@@ -577,6 +572,7 @@ def _calculate_experiment_metric_for_recalculation_sync(
metric_dict,
"experiment metric finished",
{"duration_ms": round((time.perf_counter() - calc_started_at) * 1000)},
+ trigger=state.trigger,
)
return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)
@@ -611,6 +607,7 @@ def _calculate_experiment_metric_for_recalculation_sync(
"error_type": "insufficient_data",
"error_message": message,
},
+ trigger=state.trigger,
)
return _fail(recalculation_id, metric_uuid, "calculation", message)
@@ -653,9 +650,10 @@ def _calculate_experiment_metric_for_recalculation_sync(
"experiment metric error",
{
"duration_ms": round((time.perf_counter() - calc_started_at) * 1000),
- "error_type": _classify_query_error_type(e),
+ "error_type": classify_experiment_query_error(e),
"error_message": message,
},
+ trigger=state.trigger,
)
logger.exception(
"Experiment metric recalculation failed",
diff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.py
index baf2fefe60db..6a0a2d90f9a2 100644
--- a/products/experiments/backend/temporal/recalculation_workflow.py
+++ b/products/experiments/backend/temporal/recalculation_workflow.py
@@ -12,6 +12,7 @@ from posthog.temporal.common.base import PostHogWorkflow
with temporalio.workflow.unsafe.imports_passed_through():
from products.experiments.backend.temporal.models import (
MAX_METRIC_ATTEMPTS,
+ METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS,
ExperimentMetricsRecalculationWorkflowInputs,
ExperimentMetricToRecalculate,
RecalculationProgressUpdate,
@@ -175,7 +176,9 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):
],
# No heartbeat: the activity's only long-running step is one blocking ClickHouse query
# with no progress hooks, so start_to_close_timeout is the real per-attempt ceiling.
- start_to_close_timeout=timedelta(minutes=5),
+ # The query's ClickHouse max_execution_time is capped below this (see models.py) so
+ # slow queries fail typed inside the activity instead of being killed from outside.
+ start_to_close_timeout=timedelta(seconds=METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS),
# One attempt per invocation; the workflow owns requeue + backoff (see block comment).
retry_policy=RetryPolicy(maximum_attempts=1),
)
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 9cc2a9f64c8f..c93b3ffb9315 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -12,7 +12,7 @@ from clickhouse_driver.errors import ServerException
from parameterized import parameterized
from temporalio.exceptions import ApplicationError
-from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
@@ -889,16 +889,19 @@ class TestRecalculationAnalytics(BaseTest):
[
("wrapped_oom", ClickHouseQueryMemoryLimitExceeded(), "out_of_memory"),
("wrapped_timeout", ClickHouseQueryTimeOut(), "timeout"),
+ ("wrapped_at_capacity", ClickHouseAtCapacity(), "rate_limited"),
("ch_timeout_code", ServerException("timed out", code=159), "timeout"),
("ch_socket_timeout_code", ServerException("socket timed out", code=209), "timeout"),
("ch_memory_limit_code", ServerException("memory limit exceeded", code=241), "out_of_memory"),
+ ("ch_too_many_bytes_code", ServerException("too many bytes", code=307), "byte_limit"),
+ ("ch_too_many_queries_code", ServerException("too many queries", code=202), "rate_limited"),
("other", RuntimeError("kaboom"), "server_error"),
]
)
def test_terminal_failure_emits_metric_error_event(self, name, exc, expected_error_type):
# On the terminal attempt (retries exhausted) an infra failure emits 'experiment metric error'
- # with the client-side error_type taxonomy, so recalc failures land on the same dashboards.
- # Covers both the wrapped exception classes and the raw ServerException code-lookup arm.
+ # with the shared backend error_type taxonomy — including byte_limit (307) and rate_limited (202),
+ # the two real failure modes that used to collapse into server_error and stay invisible.
exp = self._experiment(flag_key=f"an-terminal-{name}", metrics=[_mean_metric("m1")])
recalc = self._recalc(exp, metric_uuids=["m1"])
@@ -915,6 +918,9 @@ class TestRecalculationAnalytics(BaseTest):
props = captured[0]["properties"]
assert props["error_type"] == expected_error_type
assert props["execution_mode"] == "recalculation"
+ assert props["context"] == "ui"
+ assert props["mechanism"] == "orchestrated"
+ assert props["trigger"] == "manual"
def test_results_refresh_completed_event_on_finish(self):
exp = self._experiment(flag_key="an-finish", metrics=[_mean_metric("m1")])