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.

fix(experiments): apply shared metric link overrides everywhere (#108232)

Andersbad067a40222
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentExecutionPathComparison.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentExecutionPathComparison.tsx
index c685d7eac85e..fa69477b9c08 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentExecutionPathComparison.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentExecutionPathComparison.tsx
@@ -22,9 +22,10 @@ import {
} from '~/queries/schema/schema-general'
import { setLatestVersionsOnQuery } from '~/queries/utils'
-import { experimentLogic, ExperimentSavedMetric } from '../experimentLogic'
+import { experimentLogic } from '../experimentLogic'
import { getExperimentRefreshMode } from '../metricQueryUtils'
import { getDefaultMetricTitle } from '../MetricsView/shared/utils'
+import { type ExperimentSavedMetric, sharedMetricsToExperimentMetrics } from '../utils'
const COMPARISON_CONCURRENCY_LIMIT = 10
@@ -293,15 +294,9 @@ function ExperimentExecutionPathComparison({ experimentId }: { experimentId: num
const [results, setResults] = useState<Record<string, { direct: PathResult; precomputed: PathResult }>>({})
const [runAllInProgress, setRunAllInProgress] = useState(false)
- const sharedPrimaryMetrics: ExperimentMetric[] =
- (experiment.saved_metrics as ExperimentSavedMetric[] | undefined)
- ?.filter(({ metadata }) => metadata.type === 'primary')
- .map(({ query }) => query) ?? []
-
- const sharedSecondaryMetrics: ExperimentMetric[] =
- (experiment.saved_metrics as ExperimentSavedMetric[] | undefined)
- ?.filter(({ metadata }) => metadata.type === 'secondary')
- .map(({ query }) => query) ?? []
+ const savedMetrics = experiment.saved_metrics as ExperimentSavedMetric[] | undefined
+ const sharedPrimaryMetrics = sharedMetricsToExperimentMetrics(savedMetrics, 'primary')
+ const sharedSecondaryMetrics = sharedMetricsToExperimentMetrics(savedMetrics, 'secondary')
const primaryMetrics = [...(experiment.metrics || []), ...sharedPrimaryMetrics].filter(
(m): m is ExperimentMetric => m.kind === NodeKind.ExperimentMetric
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
index 322eb0294983..6b3a8717125a 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts
@@ -79,9 +79,9 @@ import { visionScannersList } from 'products/replay_vision/frontend/generated/ap
import type { ScannerTypeEnumApi } from 'products/replay_vision/frontend/generated/api.schemas'
import type { ExperimentIdType } from '../../../types'
-import type { ExperimentSavedMetric } from '../experimentLogic'
import { getDefaultMetricTitle } from '../MetricsView/shared/utils'
import {
+ type ExperimentSavedMetric,
getExperimentVariants,
getExposureLinkabilityEventName,
getFunnelDropoffReason,
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 3a3df934fdbc..9a3d10a4a338 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -22,7 +22,8 @@ import {
import { initKeaTests } from '~/test/init'
import { Experiment, MultivariateFlagVariant } from '~/types'
-import { ExperimentSavedMetric, ExperimentWarning, experimentLogic } from './experimentLogic'
+import { ExperimentWarning, experimentLogic } from './experimentLogic'
+import type { ExperimentSavedMetric } from './utils'
jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
lemonToast: {
@@ -598,7 +599,7 @@ describe('experimentLogic', () => {
metric_type: ExperimentMetricType.MEAN,
source: { kind: NodeKind.EventsNode, event: '$pageview' },
},
- metadata: { type: 'primary', breakdowns: [breakdown] },
+ metadata: { type: 'primary', breakdowns: [breakdown], breakdown_limit: 20 },
created_at: '2024-01-01T00:00:00Z',
} as unknown as ExperimentSavedMetric
@@ -625,7 +626,7 @@ describe('experimentLogic', () => {
metric_type: ExperimentMetricType.MEAN,
source: { kind: NodeKind.EventsNode, event: '$pageview' },
name: 'Shared conversion metric (copy)',
- breakdownFilter: { breakdowns: [breakdown] },
+ breakdownFilter: { breakdowns: [breakdown], breakdown_limit: 20 },
},
])
// The original shared metric link is left untouched
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 74fcd7df0384..72a897ed3d24 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -59,7 +59,6 @@ import {
ExperimentTrendsQuery,
FunnelsQuery,
InsightVizNode,
- isExperimentFunnelMetric,
NodeKind,
TrendsQuery,
} from '~/queries/schema/schema-general'
@@ -127,6 +126,7 @@ import { modalsLogic } from './modalsLogic'
import { SharedMetric } from './SharedMetrics/sharedMetricLogic'
import { sharedMetricsLogic } from './SharedMetrics/sharedMetricsLogic'
import {
+ type ExperimentSavedMetric,
type ExperimentUpdatePayload,
getDisplayOrderedIndices,
getExperimentVariants,
@@ -134,6 +134,8 @@ import {
conflictPreservedFields,
isExperimentConflictError,
isLegacyExperiment,
+ resolveSharedMetric,
+ sharedMetricsToExperimentMetrics,
toConcurrencyPayload,
toFlagVariantsInput,
withoutProjectedFlagConfig,
@@ -418,53 +420,6 @@ export function experimentResultsAreStale(
return dayjs().diff(freshest, 'minute', true) >= staleAfterMinutes
}
-const sharedMetricsToExperimentMetrics = (
- sharedMetrics: ExperimentSavedMetric[],
- type: 'primary' | 'secondary'
-): ExperimentMetric[] =>
- sharedMetrics
- .filter(({ metadata }) => metadata.type === type)
- .map(({ query, metadata }) => ({
- ...query,
- /**
- * for funnel shared metrics, merge the breakdown attribution from metadata into the query
- */
- ...(metadata?.breakdownAttributionType !== undefined &&
- isExperimentFunnelMetric(query) && {
- breakdownAttributionType: metadata.breakdownAttributionType,
- breakdownAttributionValue: metadata.breakdownAttributionValue,
- }),
- // Merge breakdowns from metadata into the query
- /**
- * merge breakdown limits from metadata into the query
- */
- breakdownFilter: {
- ...query?.breakdownFilter,
- breakdowns: metadata?.breakdowns || [],
- ...(metadata?.breakdown_limit !== undefined && { breakdown_limit: metadata.breakdown_limit }),
- },
- }))
-
-/**
- * We need a proper Saved Metric type. This is what comes back from the API.
- * TODO: We should probably refactor this for more general use.
- */
-export type ExperimentSavedMetric = {
- id: number
- experiment: number
- saved_metric: number
- metadata: {
- type: 'primary' | 'secondary'
- breakdowns?: Breakdown[]
- breakdownAttributionType?: BreakdownAttributionType
- breakdownAttributionValue?: number
- breakdown_limit?: number
- }
- created_at: string
- query: ExperimentMetric
- name: string
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentLogicValues {
billing: BillingType | null // billingLogic
@@ -1815,19 +1770,10 @@ export const experimentLogic = kea<experimentLogicType>([
const query = savedMetric.query
const name = `${savedMetric.name || getDefaultMetricTitle(query)} (copy)`
- /**
- * Build a single-use (inline) copy of the shared metric. The shared metric's
- * breakdowns live on the join metadata, so merge them into breakdownFilter here
- * the same way we do when rendering shared metrics.
- */
const newMetric = {
- ...query,
+ ...resolveSharedMetric(savedMetric),
uuid: newUuid,
name,
- breakdownFilter: {
- ...query?.breakdownFilter,
- breakdowns: savedMetric.metadata?.breakdowns || [],
- },
}
metrics.push(newMetric)
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
index 95e16fcc569e..7660413b5dd4 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -8,7 +8,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { projectLogic } from 'scenes/projectLogic'
import type { FeatureFlagsSet } from '~/lib/logic/featureFlagLogic'
-import type { Breakdown, CachedNewExperimentQueryResponse, ExperimentMetric } from '~/queries/schema/schema-general'
+import type { CachedNewExperimentQueryResponse, ExperimentMetric } from '~/queries/schema/schema-general'
import { Experiment } from '~/types'
import type { ExperimentIdType } from '~/types'
@@ -24,6 +24,8 @@ import type {
ExperimentMetricsRecalculationTriggerEnumApi,
} from 'products/experiments/frontend/generated/api.schemas'
+import { type ExperimentSavedMetric, sharedMetricsToExperimentMetrics } from './utils'
+
function reportExperimentMetricRecalculation(
status: 'triggered' | 'completed' | 'failed',
properties: {
@@ -50,14 +52,6 @@ export type RecalculationPayload = Omit<ExperimentMetricsRecalculationJobApi, 'i
Pick<ExperimentMetricsRecalculationRunApi, 'metric_retries' | 'results' | 'rows_read' | 'estimated_rows_total'>
>
-type ExperimentSavedMetric = {
- metadata: {
- type: 'primary' | 'secondary'
- breakdowns?: Breakdown[]
- }
- query: ExperimentMetric
-}
-
/**
* This logic can only handle state when an experiment is present.
*/
@@ -91,23 +85,6 @@ export interface MetricRetryInfo {
next_retry_at?: string
}
-/**
- * transform shared metrics into experiment metrics.
- */
-const sharedMetricsToExperimentMetrics = (
- sharedMetrics: ExperimentSavedMetric[],
- type: 'primary' | 'secondary'
-): ExperimentMetric[] =>
- sharedMetrics
- .filter(({ metadata }) => metadata.type === type)
- .map(({ query, metadata }) => ({
- ...query,
- breakdownFilter: {
- ...query?.breakdownFilter,
- breakdowns: metadata?.breakdowns || [],
- },
- }))
-
/**
* One metric type's metrics (inline + shared) in the order results are positionally mapped against.
*/
diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.ts
index ac3de993af64..63769e8316fd 100644
--- a/frontend/src/scenes/experiments/utils.test.ts
+++ b/frontend/src/scenes/experiments/utils.test.ts
@@ -10,6 +10,7 @@ import {
} from '~/queries/schema/schema-general'
import {
AccessControlLevel,
+ BreakdownAttributionType,
Experiment,
ExperimentMetricMathType,
FeatureFlagBucketingIdentifier,
@@ -22,6 +23,7 @@ import {
import { filterToMetricConfig } from './metricQueryUtils'
import { getNiceTickValues } from './MetricsView/shared/utils'
import {
+ type ExperimentSavedMetric,
FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,
FUNNEL_SERVER_SIDE_COMPLETION_REASON,
NOT_A_FUNNEL_REASON,
@@ -39,6 +41,7 @@ import {
isLegacyExperimentQuery,
metricResults,
percentageDistribution,
+ resolveSharedMetric,
toConcurrencyPayload,
toExperimentWritePayload,
withoutProjectedFlagConfig,
@@ -968,6 +971,103 @@ describe('getOrderedMetricsWithResults', () => {
expect(secondaryOrdered).toHaveLength(1)
expect(secondaryOrdered[0].metric.uuid).toBe('secondary-uuid')
})
+
+ // Same cases as test_saved_metric_override_precedence in the backend resolver tests.
+ const funnelWithSavedOverrides = {
+ uuid: 'saved-funnel',
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.FUNNEL,
+ series: [],
+ breakdownAttributionType: BreakdownAttributionType.Step,
+ breakdownAttributionValue: 2,
+ breakdownFilter: { breakdown_limit: 5, breakdowns: [{ property: '$os', type: 'event' }] },
+ } as ExperimentMetric
+ const savedMean = {
+ uuid: 'saved-mean',
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.MEAN,
+ source: { kind: NodeKind.EventsNode, event: 'test' },
+ } as ExperimentMetric
+
+ it.each([
+ [
+ 'omitted overrides keep saved values but not saved breakdowns',
+ funnelWithSavedOverrides,
+ {},
+ { breakdownAttributionType: BreakdownAttributionType.Step, breakdownAttributionValue: 2 },
+ { breakdown_limit: 5, breakdowns: [] },
+ ],
+ [
+ 'null overrides count as omitted',
+ funnelWithSavedOverrides,
+ { breakdownAttributionType: null, breakdownAttributionValue: null, breakdown_limit: null },
+ { breakdownAttributionType: BreakdownAttributionType.Step, breakdownAttributionValue: 2 },
+ { breakdown_limit: 5, breakdowns: [] },
+ ],
+ [
+ 'link values replace saved values',
+ funnelWithSavedOverrides,
+ {
+ breakdownAttributionType: BreakdownAttributionType.LastTouch,
+ breakdown_limit: 20,
+ breakdowns: [{ property: '$browser', type: 'event' }],
+ },
+ { breakdownAttributionType: BreakdownAttributionType.LastTouch },
+ { breakdown_limit: 20, breakdowns: [{ property: '$browser', type: 'event' }] },
+ ],
+ [
+ 'attribution step zero is explicit',
+ funnelWithSavedOverrides,
+ {
+ breakdownAttributionType: BreakdownAttributionType.Step,
+ breakdownAttributionValue: 0,
+ breakdowns: [{ property: '$browser', type: 'event' }],
+ },
+ { breakdownAttributionType: BreakdownAttributionType.Step, breakdownAttributionValue: 0 },
+ { breakdown_limit: 5, breakdowns: [{ property: '$browser', type: 'event' }] },
+ ],
+ [
+ 'attribution on a mean metric is ignored',
+ savedMean,
+ {
+ breakdownAttributionType: BreakdownAttributionType.LastTouch,
+ breakdownAttributionValue: 1,
+ breakdowns: [{ property: '$browser', type: 'event' }],
+ },
+ {},
+ { breakdowns: [{ property: '$browser', type: 'event' }] },
+ ],
+ [
+ 'limit and attribution without link breakdowns are ignored',
+ funnelWithSavedOverrides,
+ { breakdownAttributionType: BreakdownAttributionType.LastTouch, breakdown_limit: 20, breakdowns: [] },
+ { breakdownAttributionType: BreakdownAttributionType.Step, breakdownAttributionValue: 2 },
+ { breakdown_limit: 5, breakdowns: [] },
+ ],
+ [
+ 'a link whose query has not loaded resolves without its saved values',
+ undefined as unknown as ExperimentMetric,
+ { breakdowns: [{ property: '$browser', type: 'event' }], breakdown_limit: 20 },
+ {},
+ { breakdown_limit: 20, breakdowns: [{ property: '$browser', type: 'event' }] },
+ ],
+ ])('resolves link overrides: %s', (_name, query, overrides, expectedAttribution, expectedBreakdownFilter) => {
+ const resolved: Record<string, unknown> = {
+ ...resolveSharedMetric({
+ query,
+ metadata: { type: 'primary', ...overrides } as ExperimentSavedMetric['metadata'],
+ }),
+ }
+
+ const attribution = Object.fromEntries(
+ ['breakdownAttributionType', 'breakdownAttributionValue']
+ .filter((key) => resolved[key] !== undefined)
+ .map((key) => [key, resolved[key]])
+ )
+ expect(attribution).toEqual(expectedAttribution)
+ expect(resolved.breakdownFilter).toEqual(expectedBreakdownFilter)
+ expect(resolved.uuid).toBe(query?.uuid)
+ })
})
describe('mixed inline and shared metrics', () => {
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index 9746541b9004..6798a1fbf630 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -9,6 +9,7 @@ import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFil
import {
AnyDataWarehouseNode,
AnyEntityNode,
+ Breakdown,
CachedNewExperimentQueryResponse,
EventsNode,
ExperimentEventExposureConfig,
@@ -31,6 +32,7 @@ import {
} from '~/queries/schema/schema-general'
import { isFunnelsQuery, isNodeWithSource, isTrendsQuery, isValidQueryForExperiment } from '~/queries/utils'
import {
+ BreakdownAttributionType,
ChartDisplayType,
Experiment,
ExperimentMetricGoal,
@@ -1015,27 +1017,61 @@ export function getDisplayOrderedIndices(
return ordered
}
+export type ExperimentSavedMetric = {
+ id: number
+ experiment: number
+ saved_metric: number
+ metadata: {
+ type: 'primary' | 'secondary'
+ breakdowns?: Breakdown[]
+ breakdownAttributionType?: BreakdownAttributionType
+ breakdownAttributionValue?: number
+ breakdown_limit?: number
+ }
+ created_at: string
+ query: ExperimentMetric
+ name: string
+}
+
/**
- * Reshape a saved/shared metric into the inline ExperimentMetric shape, merging the
- * per-experiment link metadata (breakdown attribution, breakdowns) into the query.
+ * The effective definition of a shared metric on one experiment: the saved query with the link overrides
+ * applied. The backend calculates and fingerprints the same definition with `resolve_saved_metric_definition`
+ * in products/experiments/backend/metric_resolution.py, so a change here must change it there too,
+ * or the results the page queries and the stored results describe different metrics.
*/
-function enrichSharedMetric(sharedMetric: Experiment['saved_metrics'][number]): ExperimentMetric {
+export function resolveSharedMetric({
+ query,
+ metadata,
+}: Pick<ExperimentSavedMetric, 'query' | 'metadata'>): ExperimentMetric {
+ const breakdowns = metadata?.breakdowns || []
+ const hasBreakdowns = breakdowns.length > 0
return {
- ...sharedMetric.query,
+ ...query,
+ ...(hasBreakdowns &&
+ query?.metric_type === ExperimentMetricType.FUNNEL &&
+ metadata?.breakdownAttributionType != null && {
+ breakdownAttributionType: metadata.breakdownAttributionType,
+ breakdownAttributionValue: metadata.breakdownAttributionValue ?? undefined,
+ }),
+ breakdownFilter: {
+ ...query?.breakdownFilter,
+ breakdowns,
+ ...(hasBreakdowns && metadata?.breakdown_limit != null && { breakdown_limit: metadata.breakdown_limit }),
+ },
+ } as ExperimentMetric
+}
+
+export const sharedMetricsToExperimentMetrics = (
+ sharedMetrics: ExperimentSavedMetric[] | undefined,
+ type: 'primary' | 'secondary'
+): ExperimentMetric[] => (sharedMetrics || []).filter(({ metadata }) => metadata.type === type).map(resolveSharedMetric)
+
+function enrichSharedMetric(sharedMetric: ExperimentSavedMetric): ExperimentMetric {
+ return {
+ ...resolveSharedMetric(sharedMetric),
name: sharedMetric.name,
sharedMetricId: sharedMetric.saved_metric,
isSharedMetric: true,
- ...(sharedMetric.metadata?.breakdownAttributionType !== undefined && {
- breakdownAttributionType: sharedMetric.metadata.breakdownAttributionType,
- breakdownAttributionValue: sharedMetric.metadata.breakdownAttributionValue,
- }),
- breakdownFilter: {
- ...sharedMetric.query?.breakdownFilter,
- breakdowns: sharedMetric.metadata?.breakdowns || [],
- ...(sharedMetric.metadata?.breakdown_limit !== undefined && {
- breakdown_limit: sharedMetric.metadata.breakdown_limit,
- }),
- },
} as ExperimentMetric
}
diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.py
index 1d16fdcf414f..e19c79c8e35f 100644
--- a/posthog/temporal/experiments/activities.py
+++ b/posthog/temporal/experiments/activities.py
@@ -36,7 +36,7 @@ from products.experiments.backend.facade.timeseries import (
backfill_experiment_timeseries,
build_metric,
is_daily_timeseries_metric,
- merge_saved_metric_breakdowns,
+ resolve_saved_metric_definition,
sync_timeseries_recalculation,
)
from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_end
@@ -398,11 +398,11 @@ def _get_experiment_saved_metrics_for_hour_sync(hour: int) -> list[ExperimentSav
)
continue
- # Fingerprint the effective config (with link-metadata breakdowns), the same dict the calc
+ # Fingerprint the effective definition (with the link overrides), the same dict the calc
# activity computes and every reader (timeseries sync, chart read) resolves. Hashing the raw
- # saved query here would file breakdown-configured metrics under a hash no reader looks up.
+ # saved query here would file override-configured metrics under a hash no reader looks up.
fingerprint = compute_metric_fingerprint(
- merge_saved_metric_breakdowns(saved_metric.query, exp_to_saved_metric.metadata),
+ resolve_saved_metric_definition(saved_metric.query, exp_to_saved_metric.metadata),
experiment.start_date,
get_experiment_stats_method(experiment),
experiment.exposure_criteria,
@@ -479,12 +479,12 @@ def _calculate_experiment_saved_metric_sync(
)
# The frontend receives saved metrics with two extra fields injected before
- # they get posted back to /query: a breakdownFilter wrapper (from the link
- # metadata, via sharedMetricsToExperimentMetrics in experimentLogic.tsx) and
+ # they get posted back to /query: the link overrides (via resolveSharedMetric
+ # in experiments/utils.ts, which mirrors resolve_saved_metric_definition) and
# a fingerprint (added by the experiment API serializer). The activity must
# apply both or the response cache key diverges from /query's.
query = {
- **merge_saved_metric_breakdowns(saved_metric.query, saved_metric_metadata),
+ **resolve_saved_metric_definition(saved_metric.query, saved_metric_metadata),
"fingerprint": fingerprint,
}
metric_type = query.get("metric_type")
diff --git a/posthog/temporal/experiments/utils.py b/posthog/temporal/experiments/utils.py
index 7564b30ae710..48d613f00a9d 100644
--- a/posthog/temporal/experiments/utils.py
+++ b/posthog/temporal/experiments/utils.py
@@ -9,6 +9,7 @@ from posthog.schema import ExperimentFunnelMetric, ExperimentMeanMetric, Experim
from posthog.cdp.internal_events import InternalEventEvent, produce_internal_event
+from products.experiments.backend.facade.timeseries import resolve_saved_metric_definition
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentMetricResult as ExperimentMetricResultModel,
@@ -122,7 +123,7 @@ def _find_metric_dict(experiment: Experiment, metric_uuid: str) -> dict | None:
for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():
query = link.saved_metric.query
if isinstance(query, dict) and query.get("uuid") == metric_uuid:
- return query
+ return resolve_saved_metric_definition(query, link.metadata)
return None
diff --git a/products/dashboards/backend/api/test/test_experiment_widgets.py b/products/dashboards/backend/api/test/test_experiment_widgets.py
index f61b9a5a196a..3170a9d89c47 100644
--- a/products/dashboards/backend/api/test/test_experiment_widgets.py
+++ b/products/dashboards/backend/api/test/test_experiment_widgets.py
@@ -23,7 +23,12 @@ from products.dashboards.backend.widgets.experiment_results import (
run_experiment_results_widget,
)
from products.dashboards.backend.widgets.experiments_list import run_experiments_list_widget
-from products.experiments.backend.models.experiment import EXPOSURE_FROZEN_GROUP_KEY, Experiment
+from products.experiments.backend.models.experiment import (
+ EXPOSURE_FROZEN_GROUP_KEY,
+ Experiment,
+ ExperimentSavedMetric,
+ ExperimentToSavedMetric,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -384,6 +389,25 @@ class TestExperimentResultsWidget(APIBaseTest):
# The cap is per-section, so a fully-loaded widget runs at most 2x the constant.
assert mock_runner_cls.return_value.run.call_count == 2 * MAX_EXPERIMENT_RESULTS_WIDGET_METRICS
+ @patch("products.dashboards.backend.widgets.experiment_results.ExperimentQueryRunner")
+ def test_computes_a_shared_metric_with_its_link_overrides(self, mock_runner_cls: MagicMock) -> None:
+ mock_runner_cls.return_value.run.return_value = MagicMock(model_dump=lambda mode="json": {})
+ experiment = self._create_experiment(start_date=timezone.now())
+ saved_metric = ExperimentSavedMetric.objects.create(
+ team=self.team, name="Shared metric", query=_experiment_metric("shared-1", "")
+ )
+ ExperimentToSavedMetric.objects.create(
+ experiment=experiment,
+ saved_metric=saved_metric,
+ metadata={"type": "primary", "breakdowns": [{"property": "$browser", "type": "event"}]},
+ )
+
+ result = run_experiment_results_widget(self.team, {"experimentId": experiment.id}, user=self.user)
+
+ assert [entry["name"] for entry in result["metrics"]] == ["Shared metric"]
+ calculated_metric = mock_runner_cls.call_args.kwargs["query"].metric
+ assert [breakdown.property for breakdown in calculated_metric.breakdownFilter.breakdowns] == ["$browser"]
+
def test_legacy_metric_reports_unsupported_error(self) -> None:
experiment = self._create_experiment(
start_date=timezone.now(),
diff --git a/products/dashboards/backend/widgets/experiment_results.py b/products/dashboards/backend/widgets/experiment_results.py
index d9e144738b07..7bc4874f8845 100644
--- a/products/dashboards/backend/widgets/experiment_results.py
+++ b/products/dashboards/backend/widgets/experiment_results.py
@@ -62,6 +62,10 @@ def _collect_metric_dicts(experiment: Experiment) -> tuple[list[dict[str, Any]],
The saved-metric link set is read once and split here so a widget render issues a single query for it.
"""
+ from products.experiments.backend.facade.timeseries import ( # noqa: PLC0415 — circular import
+ resolve_saved_metric_definition,
+ )
+
primary: list[dict[str, Any]] = [dict(metric) for metric in (experiment.metrics or [])]
secondary: list[dict[str, Any]] = [dict(metric) for metric in (experiment.metrics_secondary or [])]
@@ -69,7 +73,10 @@ def _collect_metric_dicts(experiment: Experiment) -> tuple[list[dict[str, Any]],
saved_query = link.saved_metric.query
if not saved_query:
continue
- metric_dict = {**saved_query, "name": saved_query.get("name") or link.saved_metric.name}
+ metric_dict = {
+ **resolve_saved_metric_definition(saved_query, link.metadata),
+ "name": saved_query.get("name") or link.saved_metric.name,
+ }
# Links default to primary when untyped; an unrecognized type belongs to neither section.
metric_type = (link.metadata or {}).get("type", "primary")
if metric_type == "secondary":
diff --git a/products/experiments/backend/admin/recalculation_panel.py b/products/experiments/backend/admin/recalculation_panel.py
index 0cff9c1159fd..701ab76e0cec 100644
--- a/products/experiments/backend/admin/recalculation_panel.py
+++ b/products/experiments/backend/admin/recalculation_panel.py
@@ -7,7 +7,7 @@ order stays in one place, matching the frontend resolver in experimentMetricsLog
"""
from datetime import datetime
-from typing import cast
+from typing import Any, cast
from django.conf import settings
from django.contrib import messages
@@ -18,7 +18,7 @@ from django.utils.html import format_html
from posthog.models.user import User
from products.experiments.backend.metric_events import _default_metric_title
-from products.experiments.backend.metric_resolution import build_metric, find_metric_dict
+from products.experiments.backend.metric_resolution import build_metric, scheduled_metric_definitions
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentMetricResult,
@@ -52,10 +52,10 @@ def format_duration(started_at: datetime | None, completed_at: datetime | None)
return " ".join(parts)
-def _metric_name(experiment: Experiment, metric_uuid: str) -> str:
+def _metric_name(definitions: dict[str, dict[str, Any]], metric_uuid: str) -> str:
"""Resolve a metric_uuid to the title a user sees, falling back to the uuid for a metric that no
longer resolves on the experiment (removed after the run)."""
- metric_dict = find_metric_dict(experiment, metric_uuid)
+ metric_dict = definitions.get(metric_uuid)
if metric_dict is None:
return metric_uuid
if metric_dict.get("name"):
@@ -80,6 +80,7 @@ def _resolve_failures(recalc: ExperimentMetricsRecalculation, results: list[dict
# Union of every uuid that failed either way, so a discovery-step failure with no result row still shows.
failed_uuids = set(metric_errors.keys()) | set(failed_row_message.keys())
+ definitions = scheduled_metric_definitions(recalc.experiment) if failed_uuids else {}
failures = []
for metric_uuid in failed_uuids:
error = None
@@ -92,7 +93,7 @@ def _resolve_failures(recalc: ExperimentMetricsRecalculation, results: list[dict
failures.append(
{
"metric_uuid": metric_uuid,
- "metric_name": _metric_name(recalc.experiment, metric_uuid),
+ "metric_name": _metric_name(definitions, metric_uuid),
"error": error,
}
)
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index cd6213768f5b..973f7ac72793 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -65,6 +65,7 @@ from products.experiments.backend.metric_validation import (
extract_entity_nodes,
parse_and_validate_metric,
validate_metric_action_ids,
+ validate_saved_metric_link_overrides,
)
from products.experiments.backend.models.experiment import (
EXPOSURE_FROZEN_COHORT_KEY,
@@ -966,7 +967,7 @@ class ExperimentService:
if not isinstance(saved_metrics_ids, list):
raise ValidationError("Saved metrics must be a list")
- for saved_metric in saved_metrics_ids:
+ for i, saved_metric in enumerate(saved_metrics_ids):
if not isinstance(saved_metric, dict):
raise ValidationError("Saved metric must be an object")
if "id" not in saved_metric:
@@ -975,6 +976,10 @@ class ExperimentService:
raise ValidationError("Metadata must be an object")
if "metadata" in saved_metric and "type" not in saved_metric["metadata"]:
raise ValidationError("Metadata must have a type key")
+ if "metadata" in saved_metric:
+ validate_saved_metric_link_overrides(
+ saved_metric["metadata"], error_prefix=f"Invalid saved metric metadata at index {i}: "
+ )
saved_metrics = ExperimentSavedMetric.objects.filter(
id__in=[saved_metric["id"] for saved_metric in saved_metrics_ids],
diff --git a/products/experiments/backend/experiment_summary_data_service.py b/products/experiments/backend/experiment_summary_data_service.py
index 9baa04a42de5..e0605076d8af 100644
--- a/products/experiments/backend/experiment_summary_data_service.py
+++ b/products/experiments/backend/experiment_summary_data_service.py
@@ -32,7 +32,11 @@ from products.experiments.backend.facade.contracts import MAX_METRICS_TO_SUMMARI
from products.experiments.backend.hogql_queries.experiment_exposures_query_runner import ExperimentExposuresQueryRunner
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
-from products.experiments.backend.metric_resolution import METRIC_BUILDERS, ExperimentMetric
+from products.experiments.backend.metric_resolution import (
+ METRIC_BUILDERS,
+ ExperimentMetric,
+ resolve_saved_metric_definition,
+)
from products.experiments.backend.metric_utils import get_default_metric_title
from products.experiments.backend.models.experiment import Experiment, get_experiment_rule, metric_display_rank
@@ -268,6 +272,7 @@ class ExperimentSummaryDataService:
query = link.saved_metric.query
if not query:
continue
+ query = resolve_saved_metric_definition(query, link.metadata)
# The display name lives on the saved metric model, not in its query dict —
# without it the summary falls back to raw event names.
if link.saved_metric.name:
diff --git a/products/experiments/backend/facade/timeseries.py b/products/experiments/backend/facade/timeseries.py
index 0cf3fe248fb7..f79e3470ad5d 100644
--- a/products/experiments/backend/facade/timeseries.py
+++ b/products/experiments/backend/facade/timeseries.py
@@ -3,7 +3,7 @@
from products.experiments.backend.metric_resolution import (
build_metric,
is_daily_timeseries_metric,
- merge_saved_metric_breakdowns,
+ resolve_saved_metric_definition,
)
from products.experiments.backend.timeseries_backfill import backfill_experiment_timeseries
from products.experiments.backend.timeseries_sync import sync_timeseries_recalculation
@@ -12,6 +12,6 @@ __all__ = [
"backfill_experiment_timeseries",
"build_metric",
"is_daily_timeseries_metric",
- "merge_saved_metric_breakdowns",
+ "resolve_saved_metric_definition",
"sync_timeseries_recalculation",
]
diff --git a/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py b/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py
index 0040be2cd08a..0f7cdf1e86ac 100644
--- a/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py
+++ b/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py
@@ -24,7 +24,7 @@ def _strip_empty_breakdowns(clean_metric: dict) -> None:
"""Remove a breakdownFilter that carries no breakdowns before hashing.
An empty breakdown list is the same metric config as no breakdowns, but the two dict shapes hash to
- different values. Saved-metric resolution (`merge_saved_metric_breakdowns`) injects
+ different values. Saved-metric resolution (`resolve_saved_metric_definition`) injects
`breakdownFilter.breakdowns = []` when the experiment link has none, so without this normalization the
merged dict would hash away from an identical config stored without a breakdownFilter, and rows written
under one shape would be invisible to readers hashing the other.
diff --git a/products/experiments/backend/legacy_migration.py b/products/experiments/backend/legacy_migration.py
index 8cf619bcf09b..0b7a61b876a4 100644
--- a/products/experiments/backend/legacy_migration.py
+++ b/products/experiments/backend/legacy_migration.py
@@ -3,6 +3,8 @@ from uuid import uuid4
from django.db import transaction
+from rest_framework.exceptions import ValidationError
+
from posthog.dataclasses import frozen
from posthog.models.utils import convert_legacy_metric, convert_legacy_metrics
@@ -32,6 +34,15 @@ class ExperimentMigration:
migrated_saved_metric_ids: list[int]
+def _validation_reason(error: ValidationError) -> str:
+ """The message of a metric validation error, as the clause that ends a migration error. The
+ migrate endpoint adds its own closing sentence, so the reason carries no final period."""
+ detail = error.detail
+ messages = detail if isinstance(detail, list) else [detail]
+ reason = " ".join(str(message) for message in messages)
+ return reason.removeprefix("Invalid metric: ").rstrip(".")
+
+
def migrate_saved_metric(saved_metric_id: int, team_id: int) -> ExperimentSavedMetric:
"""Create a new-engine copy of a legacy shared metric, or return the copy made earlier."""
with transaction.atomic():
@@ -40,12 +51,19 @@ def migrate_saved_metric(saved_metric_id: int, team_id: int) -> ExperimentSavedM
if existing := _migrated_target(original, team_id):
return existing
+ try:
+ # Through the service, so the new query gets the uuid every new-engine metric needs.
+ query = ExperimentSavedMetricService.normalize_query_for_write(convert_legacy_metric(original.query))
+ except ValidationError as e:
+ raise LegacyMigrationError(
+ f'The shared metric "{original.name}" (id {original.id}) is not valid: {_validation_reason(e)}'
+ ) from e
+
new_metric = ExperimentSavedMetric.objects.create(
name=original.name,
team=original.team,
created_by=original.created_by,
- # Through the service, so the new query gets the uuid every new-engine metric needs.
- query=ExperimentSavedMetricService.normalize_query_for_write(convert_legacy_metric(original.query)),
+ query=query,
metadata={"migrated_from": original.id},
)
diff --git a/products/experiments/backend/metric_events.py b/products/experiments/backend/metric_events.py
index 009e0a1f4af1..ead78d62a61f 100644
--- a/products/experiments/backend/metric_events.py
+++ b/products/experiments/backend/metric_events.py
@@ -45,7 +45,7 @@ from posthog.models.user import User
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries.base_query_utils import event_or_action_to_filter
-from products.experiments.backend.metric_resolution import ExperimentMetric, build_metric, iter_metric_dicts
+from products.experiments.backend.metric_resolution import ExperimentMetric, build_metric, scheduled_metric_definitions
from products.experiments.backend.models.experiment import Experiment
logger = logging.getLogger(__name__)
@@ -242,7 +242,7 @@ def resolve_metric_events(experiment: Experiment) -> list[MetricEventSource]:
never fail the whole surface.
"""
metric_sources: list[MetricEventSource] = []
- for metric_dict in iter_metric_dicts(experiment):
+ for metric_dict in scheduled_metric_definitions(experiment).values():
try:
metric = build_metric(metric_dict)
except (KeyError, pydantic.ValidationError):
diff --git a/products/experiments/backend/metric_resolution.py b/products/experiments/backend/metric_resolution.py
index ce914b43cd89..b10a865b24f3 100644
--- a/products/experiments/backend/metric_resolution.py
+++ b/products/experiments/backend/metric_resolution.py
@@ -1,10 +1,11 @@
-"""Shared helpers for resolving experiment metric definitions across inline and saved/shared metrics.
+"""Resolve the metrics of an experiment across inline and saved/shared metrics.
-Used by the recalculation workflow and the precompute canary workflow, which both pass metric uuids between
-activities and re-resolve the definition at the point of use.
+Calculation (daily timeseries and recalculation), discovery, fingerprints and the API all read a metric's
+effective definition from here, so that they calculate and hash the same metric. Workflows pass metric
+uuids between activities and re-resolve the definition at the point of use.
"""
-from typing import Any
+from typing import Any, Literal
from posthog.schema import (
ExperimentFunnelMetric,
@@ -13,7 +14,9 @@ from posthog.schema import (
ExperimentRetentionMetric,
)
-from products.experiments.backend.models.experiment import Experiment
+from posthog.dataclasses import frozen
+
+from products.experiments.backend.models.experiment import Experiment, ExperimentToSavedMetric
ExperimentMetric = ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
@@ -36,21 +39,58 @@ def is_daily_timeseries_metric(metric: dict[str, Any] | None) -> bool:
return bool(metric and metric.get("metric_type") in DAILY_TIMESERIES_METRIC_TYPES)
-def merge_saved_metric_breakdowns(saved_query: dict[str, Any], metadata: dict[str, Any] | None) -> dict[str, Any]:
- """Merge per-experiment breakdowns from the M2M link metadata into the saved query.
+MetricRole = Literal["primary", "secondary"]
+
+
+@frozen
+class ResolvedExperimentMetric:
+ """A metric as it applies to one experiment: an inline definition, or a saved definition with the
+ link's per-experiment overrides applied."""
+
+ uuid: str
+ role: MetricRole
+ # The effective definition. It is the only dict that may feed `compute_metric_fingerprint` or a
+ # query for this metric. A caller that uses the raw saved query calculates a different metric and
+ # files or looks up results under a different hash than every other caller.
+ definition: dict[str, Any]
+
+
+def resolve_saved_metric_definition(saved_query: dict[str, Any], metadata: dict[str, Any] | None) -> dict[str, Any]:
+ """Apply the per-experiment overrides from the link metadata to a saved query.
- This is the effective config of a saved metric on an experiment, and the only dict that may feed
- `compute_metric_fingerprint` for one. A caller that fingerprints the raw saved query files or looks up
- results under a different hash than every other caller, so breakdown-configured metrics silently miss
- each other's rows (daily points invisible to the timeseries sync and to the chart read)."""
+ - `breakdowns` always comes from the link. A link without breakdowns has none, whatever the saved
+ query holds.
+ - `breakdown_limit` replaces the saved value when the link sets it.
+ - `breakdownAttributionType` and `breakdownAttributionValue` are one override: when the link sets a
+ type, both come from the link, so a link type without a value drops the saved step value. Only
+ funnel metrics have these fields.
+
+ The limit and the attribution are breakdown settings, so a link without breakdowns applies neither.
+ Applying them would change the fingerprint of a metric whose results cannot change, and the stored
+ results of that metric would become unreachable.
+
+ A key that is absent or null is an omitted override. Step 0 is an explicit value.
+ """
metadata = metadata or {}
- return {
- **saved_query,
- "breakdownFilter": {
- **(saved_query.get("breakdownFilter") or {}),
- "breakdowns": metadata.get("breakdowns") or [],
- },
- }
+ resolved = {**saved_query}
+
+ breakdowns = metadata.get("breakdowns") or []
+ breakdown_filter = {**(saved_query.get("breakdownFilter") or {}), "breakdowns": breakdowns}
+ if breakdowns and metadata.get("breakdown_limit") is not None:
+ breakdown_filter["breakdown_limit"] = metadata["breakdown_limit"]
+ resolved["breakdownFilter"] = breakdown_filter
+
+ if (
+ breakdowns
+ and saved_query.get("metric_type") == "funnel"
+ and metadata.get("breakdownAttributionType") is not None
+ ):
+ resolved["breakdownAttributionType"] = metadata["breakdownAttributionType"]
+ resolved.pop("breakdownAttributionValue", None)
+ if metadata.get("breakdownAttributionValue") is not None:
+ resolved["breakdownAttributionValue"] = metadata["breakdownAttributionValue"]
+
+ return resolved
def is_scheduled_metric(metric: dict[str, Any] | None) -> bool:
@@ -61,33 +101,84 @@ def is_scheduled_metric(metric: dict[str, Any] | None) -> bool:
return bool(metric and metric.get("uuid") and metric.get("metric_type") in METRIC_BUILDERS)
-def iter_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:
- """All metric definition dicts for an experiment: inline primary + secondary, then saved/shared metrics.
-
- Inline metrics are dicts in experiment.metrics / metrics_secondary. Saved metrics live on the M2M
- through-model and carry their definition (with uuid) in saved_metric.query; per-experiment breakdown
- overrides from the link metadata are merged in.
- """
- dicts: list[dict[str, Any]] = [
- metric
- for metric in (experiment.metrics or []) + (experiment.metrics_secondary or [])
- if is_scheduled_metric(metric)
- ]
+def _resolve_inline_metrics(experiment: Experiment) -> list[ResolvedExperimentMetric]:
+ """Inline primary metrics, then inline secondary metrics. Metrics without a uuid cannot be addressed
+ and are skipped. Reads no rows."""
+ sections: tuple[tuple[MetricRole, list | None], ...] = (
+ ("primary", experiment.metrics),
+ ("secondary", experiment.metrics_secondary),
+ )
+ resolved: list[ResolvedExperimentMetric] = []
+ for role, metrics in sections:
+ for metric in metrics or []:
+ if isinstance(metric, dict) and metric.get("uuid"):
+ resolved.append(ResolvedExperimentMetric(uuid=metric["uuid"], role=role, definition=metric))
+ return resolved
+
+
+def saved_metric_links(experiment: Experiment) -> list[ExperimentToSavedMetric]:
+ """The experiment's links to saved/shared metrics, in id order. The join leaves the row order
+ unspecified, and the link order is what puts the shared metrics in order on the experiment."""
# Calling select_related on the manager would clone the queryset and discard a caller's
# prefetch cache, re-querying per experiment. Join saved_metric only when nothing is prefetched.
links = experiment.experimenttosavedmetric_set.all()
if "experimenttosavedmetric_set" not in getattr(experiment, "_prefetched_objects_cache", {}):
links = links.select_related("saved_metric")
- for link in links:
+ return sorted(links, key=lambda link: link.id)
+
+
+def _resolve_saved_metrics(experiment: Experiment) -> list[ResolvedExperimentMetric]:
+ """Saved/shared metrics linked to the experiment, with the link overrides applied. The link's
+ metadata["type"] holds the role, and a missing type means primary."""
+ resolved: list[ResolvedExperimentMetric] = []
+ for link in saved_metric_links(experiment):
saved_query = link.saved_metric.query
- if is_scheduled_metric(saved_query):
- dicts.append(merge_saved_metric_breakdowns(saved_query, link.metadata))
- return dicts
+ if not isinstance(saved_query, dict) or not saved_query.get("uuid"):
+ continue
+ metadata = link.metadata or {}
+ resolved.append(
+ ResolvedExperimentMetric(
+ uuid=saved_query["uuid"],
+ role="secondary" if metadata.get("type") == "secondary" else "primary",
+ definition=resolve_saved_metric_definition(saved_query, metadata),
+ )
+ )
+ return resolved
+
+
+def resolve_experiment_metrics(experiment: Experiment) -> list[ResolvedExperimentMetric]:
+ """Every addressable metric on the experiment: inline primary, inline secondary, then saved/shared.
+
+ Callers apply their own eligibility, for example `is_scheduled_metric` or `is_daily_timeseries_metric`.
+ """
+ return _resolve_inline_metrics(experiment) + _resolve_saved_metrics(experiment)
+
+
+def resolve_scheduled_metrics(experiment: Experiment) -> list[ResolvedExperimentMetric]:
+ """The scheduled metrics of the experiment in resolution order, resolved with at most one query.
+
+ Results are addressed by uuid, so metrics that share a uuid share one definition: the first in
+ resolution order, which makes an inline metric win over a saved metric. Each of them still has
+ its own entry, because `total_metrics` counts entries.
+ """
+ definitions: dict[str, dict[str, Any]] = {}
+ scheduled: list[ResolvedExperimentMetric] = []
+ for metric in resolve_experiment_metrics(experiment):
+ if is_scheduled_metric(metric.definition):
+ definition = definitions.setdefault(metric.uuid, metric.definition)
+ scheduled.append(ResolvedExperimentMetric(uuid=metric.uuid, role=metric.role, definition=definition))
+ return scheduled
+
+
+def scheduled_metric_definitions(experiment: Experiment) -> dict[str, dict[str, Any]]:
+ """The effective definition of each scheduled metric, keyed by uuid in resolution order. Use it
+ instead of calling `find_metric_dict` once per metric."""
+ return {metric.uuid: metric.definition for metric in resolve_scheduled_metrics(experiment)}
def find_metric_dict(experiment: Experiment, metric_uuid: str) -> dict[str, Any] | None:
- """Resolve a metric_uuid to its definition dict, across inline AND saved/shared metrics."""
- return next((metric for metric in iter_metric_dicts(experiment) if metric.get("uuid") == metric_uuid), None)
+ """Resolve a scheduled metric_uuid to its effective definition, across inline AND saved/shared metrics."""
+ return scheduled_metric_definitions(experiment).get(metric_uuid)
def build_metric(metric_dict: dict[str, Any]) -> ExperimentMetric:
diff --git a/products/experiments/backend/metric_validation.py b/products/experiments/backend/metric_validation.py
index 6973554e3fd6..114cce9fc7ab 100644
--- a/products/experiments/backend/metric_validation.py
+++ b/products/experiments/backend/metric_validation.py
@@ -11,6 +11,8 @@ import structlog
from rest_framework.exceptions import ValidationError
from posthog.schema import (
+ Breakdown,
+ BreakdownAttributionType,
ExperimentFunnelMetric,
ExperimentMeanMetric,
ExperimentMetric as ExperimentMetricUnion,
@@ -138,6 +140,30 @@ def parse_and_validate_metric(metric: object, *, error_prefix: str) -> Experimen
return parsed
+class _SavedMetricLinkOverrides(pydantic.BaseModel):
+ """The link metadata keys that `resolve_saved_metric_definition` applies to the saved query, typed
+ as the metric schema types them. Other keys, such as `type`, are not overrides."""
+
+ model_config = pydantic.ConfigDict(extra="ignore")
+
+ breakdowns: list[Breakdown] | None = pydantic.Field(default=None, max_length=3)
+ breakdown_limit: int | None = None
+ breakdownAttributionType: BreakdownAttributionType | None = None
+ breakdownAttributionValue: int | None = None
+
+
+def validate_saved_metric_link_overrides(metadata: dict, *, error_prefix: str) -> None:
+ """Validate the per-experiment overrides on a saved metric link.
+
+ Every calculation applies the overrides to the saved query. An override that the metric schema
+ rejects makes each calculation of that metric fail until someone edits the link.
+ """
+ try:
+ _SavedMetricLinkOverrides.model_validate(metadata)
+ except pydantic.ValidationError as e:
+ raise ValidationError(f"{error_prefix}{_pydantic_error_message(e)}")
+
+
def extract_entity_nodes(metrics: list[dict] | None) -> tuple[set[str], set[int]]:
"""Extract event names and action IDs from all EventsNode/ActionsNode refs in metrics."""
event_names: set[str] = set()
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index e9a970a1c705..9d14aa2353a8 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -43,7 +43,7 @@ from products.access_control.backend.presentation.access_control import UserAcce
from products.ai_observability.backend.models.llm_prompt import LLMPrompt
from products.experiments.backend.experiment_service import ExperimentService
from products.experiments.backend.facade.contracts import CreateExperimentInput
-from products.experiments.backend.facade.timeseries import merge_saved_metric_breakdowns
+from products.experiments.backend.facade.timeseries import resolve_saved_metric_definition
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.exposure_query_logic import resolve_default_exposure_event
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
@@ -606,6 +606,14 @@ class ExperimentSerializer(ExperimentBaseSerializer):
# launched today, which is what the setup UI needs to show.
return resolve_default_exposure_event(obj.team, obj.start_date or timezone.now())
+ @staticmethod
+ def _stored_saved_metric_queries(instance: Experiment) -> dict[int, dict[str, Any]]:
+ links = instance.experimenttosavedmetric_set.all()
+ # Calling select_related on the manager would discard a prefetch cache and query again.
+ if "experimenttosavedmetric_set" not in getattr(instance, "_prefetched_objects_cache", {}):
+ links = links.select_related("saved_metric")
+ return {link.id: link.saved_metric.query for link in links}
+
@tracer.start_as_current_span("ExperimentSerializer.to_representation")
def to_representation(self, instance):
data = super().to_representation(instance)
@@ -636,16 +644,19 @@ class ExperimentSerializer(ExperimentBaseSerializer):
saved_metrics = data.get("saved_metrics", [])
with tracer.start_as_current_span("ExperimentSerializer.saved_metric_fingerprints") as span:
span.set_attribute("saved_metric_count", len(saved_metrics))
+ stored_queries = self._stored_saved_metric_queries(instance) if saved_metrics else {}
for saved_metric in saved_metrics:
if saved_metric.get("query"):
apply_metric_date_range(saved_metric["query"], new_date_range)
# Add fingerprint to saved metric returned from API so that the frontend knows what
- # timeseries records to query. Computed on the effective config (with link-metadata
- # breakdowns), the same dict the daily discovery fingerprints, so the chart read finds
- # the rows the daily workflow wrote.
+ # timeseries records to query. Computed on the effective definition (with the link
+ # overrides), the same dict the daily discovery fingerprints, so the chart read finds
+ # the rows the daily workflow wrote. The action names are part of the hash, and the
+ # serialized query carries the refreshed names, so the hash reads the stored query.
+ stored_query = stored_queries.get(saved_metric["id"]) or saved_metric["query"]
saved_metric["query"]["fingerprint"] = compute_metric_fingerprint(
- merge_saved_metric_breakdowns(saved_metric["query"], saved_metric.get("metadata")),
+ resolve_saved_metric_definition(stored_query, saved_metric.get("metadata")),
instance.start_date,
get_experiment_stats_method(instance),
instance.exposure_criteria,
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index de29b32e9d7a..bc7eea4dfe6d 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -32,6 +32,7 @@ from posthog.temporal.common.client import sync_connect
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
+from products.experiments.backend.metric_resolution import resolve_scheduled_metrics, scheduled_metric_definitions
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentMetricResult,
@@ -40,7 +41,7 @@ from products.experiments.backend.models.experiment import (
from products.experiments.backend.result_serialization import strip_step_sessions
from products.experiments.backend.temporal.models import ExperimentMetricsRecalculationWorkflowInputs
from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint
-from products.experiments.backend.temporal.recalculation_logic import discover_experiment_metrics, find_metric_dict
+from products.experiments.backend.temporal.recalculation_logic import discover_experiment_metrics
# How long an active (PENDING/IN_PROGRESS) row blocks new recalculations. Beyond this, the row is treated as
# stale and a fresh recalc is allowed. Sized to be safely above the workflow's worst-case end-to-end runtime
@@ -384,9 +385,10 @@ def _recalc_fingerprints_for_run(experiment: Experiment, recalc: ExperimentMetri
ExperimentMetricResult" — the snapshot lives in the fingerprint, not in a stored column.
"""
stats_method = get_experiment_stats_method(experiment)
+ definitions = scheduled_metric_definitions(experiment)
fingerprints: dict[str, str] = {}
for metric_uuid in recalc.metric_uuids or []:
- metric_dict = find_metric_dict(experiment, metric_uuid)
+ metric_dict = definitions.get(metric_uuid)
if metric_dict is None:
continue
config_fp = compute_metric_fingerprint(
@@ -445,18 +447,15 @@ def build_timeseries_cold_start_payload(experiment: Experiment) -> dict | None:
and completed_at both pin to the freshest point's date. GET never triggers anything itself.
"""
with team_scope(experiment.team_id, canonical=True):
- metrics = discover_experiment_metrics(experiment)
+ metrics = resolve_scheduled_metrics(experiment)
stats_method = get_experiment_stats_method(experiment)
now = timezone.now()
results: list[dict] = []
latest_query_to = None
for metric in metrics:
- metric_dict = find_metric_dict(experiment, metric.metric_uuid)
- if metric_dict is None:
- continue
config_fp = compute_metric_fingerprint(
- metric_dict,
+ metric.definition,
experiment.start_date,
stats_method,
experiment.exposure_criteria,
@@ -466,7 +465,7 @@ def build_timeseries_cold_start_payload(experiment: Experiment) -> dict | None:
row = (
ExperimentMetricResult.objects.filter(
experiment=experiment,
- metric_uuid=metric.metric_uuid,
+ metric_uuid=metric.uuid,
fingerprint=config_fp,
status=ExperimentMetricResult.Status.COMPLETED,
# Bounded on both sides: the backfill writes end-of-day points, so today's point can carry
diff --git a/products/experiments/backend/temporal/canary_logic.py b/products/experiments/backend/temporal/canary_logic.py
index 96e73d2ee490..e731d0b6ba6e 100644
--- a/products/experiments/backend/temporal/canary_logic.py
+++ b/products/experiments/backend/temporal/canary_logic.py
@@ -60,7 +60,7 @@ from products.experiments.backend.metric_resolution import (
ExperimentMetric,
build_metric,
find_metric_dict,
- iter_metric_dicts,
+ scheduled_metric_definitions,
)
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
@@ -150,7 +150,11 @@ def _eligible_experiments() -> list[Experiment]:
def _experiment_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:
with team_scope(experiment.team_id, canonical=True):
- return [m for m in iter_metric_dicts(experiment) if m.get("metric_type") in ELIGIBLE_METRIC_TYPES]
+ return [
+ m
+ for m in scheduled_metric_definitions(experiment).values()
+ if m.get("metric_type") in ELIGIBLE_METRIC_TYPES
+ ]
def _uses_data_warehouse(metric_dict: dict[str, Any]) -> bool:
diff --git a/products/experiments/backend/temporal/enrollment_census_logic.py b/products/experiments/backend/temporal/enrollment_census_logic.py
index dad8343e992b..352735b71c81 100644
--- a/products/experiments/backend/temporal/enrollment_census_logic.py
+++ b/products/experiments/backend/temporal/enrollment_census_logic.py
@@ -181,10 +181,10 @@ def fetch_direct_scan_stats(window_days: int) -> list[TeamDirectScanStats]:
def running_experiment_load(team_ids: list[int]) -> dict[int, TeamRunningLoad]:
"""Per team: running experiment count and scheduled metric count across them.
- Mirrors iter_metric_dicts (inline primary + secondary + saved-metric links, filtered by
+ Mirrors discover_experiment_metrics (inline primary + secondary + saved-metric links, filtered by
the shared is_scheduled_metric predicate) so the projected build load matches what
nightly recalculation would actually schedule. Counts in two bulk queries instead of
- calling iter_metric_dicts per experiment, so a team running thousands of experiments
+ resolving the metrics of each experiment, so a team running thousands of experiments
cannot amplify the census into thousands of saved-metric queries.
"""
load: dict[int, TeamRunningLoad] = {}
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 4c9bd92223d5..755a5216e9cf 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -39,7 +39,7 @@ from products.experiments.backend.hogql_queries.error_handling import (
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, sanitize_non_finite
-from products.experiments.backend.metric_resolution import build_metric, find_metric_dict, is_scheduled_metric
+from products.experiments.backend.metric_resolution import build_metric, find_metric_dict, resolve_scheduled_metrics
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentMetricResult,
@@ -127,32 +127,10 @@ def discover_experiment_metrics(experiment: Experiment) -> list[ExperimentMetric
``recalculation_activities.py`` shares the name but takes a ``recalculation_id`` — disambiguate by
import path and argument type at the call site.
"""
- metrics_to_recalculate: list[ExperimentMetricToRecalculate] = []
-
- def _add(metric_uuid: str | None, metric_type: str) -> None:
- if metric_uuid:
- metrics_to_recalculate.append(
- ExperimentMetricToRecalculate(
- experiment_id=experiment.id, metric_uuid=metric_uuid, metric_type=metric_type
- )
- )
-
- # Inline metrics carry their uuid directly on the dict; the metric_type is the source list.
- for source, metric_type in [(experiment.metrics, "primary"), (experiment.metrics_secondary, "secondary")]:
- for metric in source or []:
- if is_scheduled_metric(metric):
- _add(metric.get("uuid"), metric_type)
-
- # Saved (shared) metrics live in the M2M through-model: uuid is on saved_metric.query["uuid"], and
- # primary/secondary is recorded on the link's metadata["type"] (default "primary").
- for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():
- saved_query = link.saved_metric.query
- if not is_scheduled_metric(saved_query):
- continue
- metric_type = link.metadata.get("type", "primary") if link.metadata else "primary"
- _add(saved_query.get("uuid"), metric_type)
-
- return metrics_to_recalculate
+ return [
+ ExperimentMetricToRecalculate(experiment_id=experiment.id, metric_uuid=metric.uuid, metric_type=metric.role)
+ for metric in resolve_scheduled_metrics(experiment)
+ ]
@database_sync_to_async_pool
diff --git a/products/experiments/backend/temporal/test_discovery_fingerprints.py b/products/experiments/backend/temporal/test_discovery_fingerprints.py
index 3d6ff48aed28..ee84d82df6a2 100644
--- a/products/experiments/backend/temporal/test_discovery_fingerprints.py
+++ b/products/experiments/backend/temporal/test_discovery_fingerprints.py
@@ -1,4 +1,5 @@
import datetime
+from typing import Any
from zoneinfo import ZoneInfo
import pytest
@@ -8,22 +9,32 @@ from parameterized import parameterized
from posthog.models import Organization, Team, User
from posthog.temporal.experiments.activities import (
+ _calculate_experiment_saved_metric_sync,
_get_experiment_regular_metrics_for_hour_sync,
_get_experiment_saved_metrics_for_hour_sync,
)
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
-from products.experiments.backend.metric_resolution import find_metric_dict
+from products.experiments.backend.metric_resolution import build_metric, find_metric_dict
from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
from products.feature_flags.backend.models.feature_flag import FeatureFlag
METRIC_UUID = "metric-uuid-1"
METRIC = {"metric_type": "mean", "uuid": METRIC_UUID, "source": {"kind": "EventsNode", "event": "test"}}
+SAVED_FUNNEL: dict[str, Any] = {
+ "kind": "ExperimentMetric",
+ "metric_type": "funnel",
+ "uuid": "saved-funnel-uuid",
+ "series": [{"kind": "EventsNode", "event": "signup"}, {"kind": "EventsNode", "event": "purchase"}],
+ "breakdownAttributionType": "first_touch",
+ "breakdownFilter": {"breakdown_limit": 5},
+}
# Access the underlying sync functions, patching out close_old_connections which kills the test DB connection
_raw_regular_sync = _get_experiment_regular_metrics_for_hour_sync.func # type: ignore[attr-defined]
_raw_saved_sync = _get_experiment_saved_metrics_for_hour_sync.func # type: ignore[attr-defined]
+_raw_saved_calc = _calculate_experiment_saved_metric_sync.func # type: ignore[attr-defined]
@pytest.mark.django_db
@@ -83,31 +94,44 @@ class TestDiscoveryFingerprints:
[
("no_breakdowns", {}),
("with_breakdowns", {"type": "primary", "breakdowns": [{"type": "event", "property": "$os_name"}]}),
+ (
+ "with_attribution_and_limit_overrides",
+ {
+ "type": "primary",
+ "breakdowns": [{"type": "event", "property": "$os_name"}],
+ "breakdownAttributionType": "step",
+ "breakdownAttributionValue": 0,
+ "breakdown_limit": 20,
+ },
+ ),
]
)
- def test_saved_metric_discovery_fingerprint_matches_recalculation_resolution(
- self, _name: str, metadata: dict
- ) -> None:
- """The readers (timeseries sync, cold-start fallback, chart read) resolve a saved metric through
- find_metric_dict, which merges the link-metadata breakdowns. Discovery must fingerprint the same
- merged dict, or the daily points are filed under a hash no reader looks up and daily results are
- never published for that metric."""
+ def test_saved_metric_calculation_uses_the_fingerprinted_definition(self, _name: str, metadata: dict) -> None:
experiment, user = self._create_experiment(metrics=[])
saved_metric = ExperimentSavedMetric.objects.create(
team=experiment.team,
name="Saved metric",
- query=METRIC,
+ query=SAVED_FUNNEL,
created_by=user,
)
ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved_metric, metadata=metadata)
- with patch("posthog.temporal.experiments.activities.close_old_connections"):
+ with (
+ patch("posthog.temporal.experiments.activities.close_old_connections"),
+ patch("posthog.temporal.experiments.activities.ExperimentQueryRunner") as mock_runner_class,
+ ):
+ mock_runner_class.return_value.run.return_value.model_dump.return_value = {"variant_results": []}
results = _raw_saved_sync(hour=2)
-
- discovery_fingerprints = [r.fingerprint for r in results if r.experiment_id == experiment.id]
- merged_dict = find_metric_dict(experiment, METRIC_UUID)
- assert merged_dict is not None
- assert discovery_fingerprints == [self._expected_fingerprint(experiment, merged_dict)]
+ [discovered] = [r for r in results if r.experiment_id == experiment.id]
+ outcome = _raw_saved_calc(experiment.id, discovered.metric_uuid, discovered.fingerprint)
+
+ assert outcome.success, outcome.error_message
+ effective = find_metric_dict(experiment, SAVED_FUNNEL["uuid"])
+ assert effective is not None
+ assert discovered.fingerprint == self._expected_fingerprint(experiment, effective)
+ calculated_metric = mock_runner_class.call_args.kwargs["query"].metric
+ assert calculated_metric == build_metric({**effective, "fingerprint": discovered.fingerprint})
+ assert calculated_metric.breakdownFilter.breakdown_limit == metadata.get("breakdown_limit", 5)
@pytest.mark.parametrize(
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 4ce91cfb19c3..4852d425d559 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -758,6 +758,21 @@ class TestExperimentService(APIBaseTest):
("non_object", [[1]], "Saved metric must be an object"),
("metadata_not_object", [{"id": 1, "metadata": "primary"}], "Metadata must be an object"),
("metadata_missing_type", [{"id": 1, "metadata": {"xxx": "primary"}}], "Metadata must have a type key"),
+ (
+ "breakdown_limit_not_a_number",
+ [{"id": 1, "metadata": {"type": "primary", "breakdown_limit": "abc"}}],
+ "Invalid saved metric metadata at index 0: [{'loc': ('breakdown_limit',)",
+ ),
+ (
+ "unknown_attribution_type",
+ [{"id": 1, "metadata": {"type": "primary", "breakdownAttributionType": "bogus"}}],
+ "Invalid saved metric metadata at index 0: [{",
+ ),
+ (
+ "breakdown_without_property",
+ [{"id": 1, "metadata": {"type": "primary", "breakdowns": [{"type": "event"}]}}],
+ "Invalid saved metric metadata at index 0: [{'loc': ('breakdowns', 0, 'property')",
+ ),
]
)
def test_create_experiment_validates_saved_metrics_payload(
diff --git a/products/experiments/backend/test/test_legacy_migration.py b/products/experiments/backend/test/test_legacy_migration.py
index 122a88924ce8..eb9945c90063 100644
--- a/products/experiments/backend/test/test_legacy_migration.py
+++ b/products/experiments/backend/test/test_legacy_migration.py
@@ -113,6 +113,24 @@ class TestExperimentMigrateEndpoint(APILicensedTest):
assert Experiment.objects.filter(team=self.team).count() == 2
assert ExperimentSavedMetric.objects.filter(team=self.team).count() == 2
+ def test_names_the_shared_metric_that_converts_to_an_invalid_metric(self) -> None:
+ ExperimentSavedMetric.objects.filter(pk=self.shared_metric.pk).update(
+ query={"kind": "ExperimentFunnelsQuery", "funnels_query": {"series": []}}
+ )
+
+ response = self._migrate()
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["detail"] == (
+ "Couldn't migrate this experiment: "
+ f'The shared metric "Legacy shared metric" (id {self.shared_metric.id}) is not valid: '
+ "funnel metrics require at least one step. "
+ "The experiment exposure event is added as the initial step automatically. "
+ "Contact support if it keeps happening."
+ )
+ assert Experiment.objects.filter(team=self.team).count() == 1
+ assert ExperimentSavedMetric.objects.filter(team=self.team).count() == 1
+
def test_rejects_an_experiment_that_is_already_on_the_new_engine(self) -> None:
Experiment.objects.filter(pk=self.experiment.pk).update(metrics=[])
ExperimentToSavedMetric.objects.filter(experiment=self.experiment).delete()
diff --git a/products/experiments/backend/test/test_metric_resolution.py b/products/experiments/backend/test/test_metric_resolution.py
index f4772408b9aa..35878acdfb69 100644
--- a/products/experiments/backend/test/test_metric_resolution.py
+++ b/products/experiments/backend/test/test_metric_resolution.py
@@ -1,9 +1,17 @@
import uuid
+from typing import Any
import pytest
from posthog.test.base import BaseTest
-from products.experiments.backend.metric_resolution import find_metric_dict, iter_metric_dicts
+from parameterized import parameterized
+
+from products.experiments.backend.metric_resolution import (
+ find_metric_dict,
+ resolve_experiment_metrics,
+ resolve_saved_metric_definition,
+ scheduled_metric_definitions,
+)
from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -40,19 +48,39 @@ class TestMetricResolution(BaseTest):
assert resolved is not None
assert resolved["source"] == "inline"
- def test_resolution_order_is_primary_secondary_saved(self):
+ def test_resolution_order_and_roles(self):
primary = {"uuid": str(uuid.uuid4()), "metric_type": "mean"}
secondary = {"uuid": str(uuid.uuid4()), "metric_type": "mean"}
experiment = self._experiment(metrics=[primary], metrics_secondary=[secondary])
- saved_uuid = str(uuid.uuid4())
- self._attach_saved(experiment, {"uuid": saved_uuid, "metric_type": "mean"})
+ saved_secondary_uuid = str(uuid.uuid4())
+ saved_untyped_uuid = str(uuid.uuid4())
+ self._attach_saved(experiment, {"uuid": saved_secondary_uuid, "metric_type": "mean"}, {"type": "secondary"})
+ self._attach_saved(experiment, {"uuid": saved_untyped_uuid, "metric_type": "mean"})
- assert [m["uuid"] for m in iter_metric_dicts(experiment)] == [
- primary["uuid"],
- secondary["uuid"],
- saved_uuid,
+ assert [(m.uuid, m.role) for m in resolve_experiment_metrics(experiment)] == [
+ (primary["uuid"], "primary"),
+ (secondary["uuid"], "secondary"),
+ (saved_secondary_uuid, "secondary"),
+ (saved_untyped_uuid, "primary"),
]
+ def test_prefetched_links_resolve_without_queries(self):
+ saved_uuid = str(uuid.uuid4())
+ breakdowns = [{"property": "$browser", "type": "event"}]
+ self._attach_saved(
+ self._experiment(),
+ {"uuid": saved_uuid, "metric_type": "mean"},
+ {"breakdowns": breakdowns, "breakdown_limit": 3},
+ )
+ experiment = Experiment.objects.prefetch_related("experimenttosavedmetric_set__saved_metric").get(
+ team=self.team
+ )
+
+ with self.assertNumQueries(0):
+ definitions = scheduled_metric_definitions(experiment)
+
+ assert definitions[saved_uuid]["breakdownFilter"] == {"breakdowns": breakdowns, "breakdown_limit": 3}
+
def test_saved_metric_breakdowns_merged_from_link_metadata(self):
experiment = self._experiment()
saved_uuid = str(uuid.uuid4())
@@ -86,4 +114,88 @@ class TestMetricResolution(BaseTest):
)
self._attach_saved(experiment, {"metric_type": "funnel"})
self._attach_saved(experiment, {"uuid": str(uuid.uuid4())})
- assert iter_metric_dicts(experiment) == []
+ assert scheduled_metric_definitions(experiment) == {}
+
+
+_FUNNEL_WITH_SAVED_OVERRIDES: dict[str, Any] = {
+ "uuid": "saved-funnel",
+ "metric_type": "funnel",
+ "breakdownAttributionType": "step",
+ "breakdownAttributionValue": 2,
+ "breakdownFilter": {"breakdown_limit": 5, "breakdowns": [{"property": "$os", "type": "event"}]},
+}
+
+
+ [
+ (
+ "omitted_overrides_keep_saved_values_but_not_saved_breakdowns",
+ _FUNNEL_WITH_SAVED_OVERRIDES,
+ {"type": "primary"},
+ {"breakdownAttributionType": "step", "breakdownAttributionValue": 2},
+ {"breakdown_limit": 5, "breakdowns": []},
+ ),
+ (
+ "null_overrides_count_as_omitted",
+ _FUNNEL_WITH_SAVED_OVERRIDES,
+ {"breakdownAttributionType": None, "breakdownAttributionValue": None, "breakdown_limit": None},
+ {"breakdownAttributionType": "step", "breakdownAttributionValue": 2},
+ {"breakdown_limit": 5, "breakdowns": []},
+ ),
+ (
+ "link_values_replace_saved_values",
+ _FUNNEL_WITH_SAVED_OVERRIDES,
+ {
+ "breakdownAttributionType": "last_touch",
+ "breakdown_limit": 20,
+ "breakdowns": [{"property": "$browser", "type": "event"}],
+ },
+ {"breakdownAttributionType": "last_touch"},
+ {"breakdown_limit": 20, "breakdowns": [{"property": "$browser", "type": "event"}]},
+ ),
+ (
+ "attribution_step_zero_is_explicit",
+ _FUNNEL_WITH_SAVED_OVERRIDES,
+ {
+ "breakdownAttributionType": "step",
+ "breakdownAttributionValue": 0,
+ "breakdowns": [{"property": "$browser", "type": "event"}],
+ },
+ {"breakdownAttributionType": "step", "breakdownAttributionValue": 0},
+ {"breakdown_limit": 5, "breakdowns": [{"property": "$browser", "type": "event"}]},
+ ),
+ (
+ "attribution_on_a_mean_metric_is_ignored",
+ {"uuid": "saved-mean", "metric_type": "mean"},
+ {
+ "breakdownAttributionType": "last_touch",
+ "breakdownAttributionValue": 1,
+ "breakdowns": [{"property": "$browser", "type": "event"}],
+ },
+ {},
+ {"breakdowns": [{"property": "$browser", "type": "event"}]},
+ ),
+ (
+ "limit_and_attribution_without_link_breakdowns_are_ignored",
+ _FUNNEL_WITH_SAVED_OVERRIDES,
+ {"breakdownAttributionType": "last_touch", "breakdown_limit": 20, "breakdowns": []},
+ {"breakdownAttributionType": "step", "breakdownAttributionValue": 2},
+ {"breakdown_limit": 5, "breakdowns": []},
+ ),
+ ]
+)
+def test_saved_metric_override_precedence(
+ _name: str,
+ saved_query: dict[str, Any],
+ metadata: dict[str, Any],
+ expected_attribution: dict[str, Any],
+ expected_breakdown_filter: dict[str, Any],
+) -> None:
+ resolved = resolve_saved_metric_definition(saved_query, metadata)
+
+ attribution = {
+ key: resolved[key] for key in ("breakdownAttributionType", "breakdownAttributionValue") if key in resolved
+ }
+ assert attribution == expected_attribution
+ assert resolved["breakdownFilter"] == expected_breakdown_filter
+ assert resolved["uuid"] == saved_query["uuid"]
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 8bf4e56f6cd5..a9e934c148c2 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -48,7 +48,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
EXPERIMENT_EXPOSURE_EVENT_FLAG,
)
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
-from products.experiments.backend.metric_resolution import merge_saved_metric_breakdowns
+from products.experiments.backend.metric_resolution import find_metric_dict
from products.experiments.backend.models.experiment import (
EXPOSURE_FROZEN_GROUP_KEY,
EXPOSURE_FROZEN_GROUP_MARKER,
@@ -1242,22 +1242,31 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
{"id": holdout_2_id, "exclusion_percentage": 5},
)
- def test_saved_metric_fingerprint_is_stamped_from_the_merged_query(self):
+ @parameterized.expand([("event_source", False), ("action_source_renamed_after_the_save", True)])
+ def test_saved_metric_fingerprint_is_stamped_from_the_merged_query(self, _name: str, rename_action: bool):
"""The stamped fingerprint tells the frontend which timeseries rows to read. It must be computed on
- the saved query merged with the link-metadata breakdowns, the same dict the daily workflow files its
- rows under, or the chart reads an empty series for a breakdown-configured saved metric."""
+ the saved query with the link overrides applied, the same dict the daily workflow files its rows
+ under, or the chart reads an empty series for an override-configured saved metric."""
+ action = Action.objects.create(team=self.team, name="Stored name", steps_json=[{"event": "$pageview"}])
+ source = (
+ {"kind": "ActionsNode", "id": action.id, "name": action.name}
+ if rename_action
+ else {"kind": "EventsNode", "event": "$pageview"}
+ )
saved_metric_response = self.client.post(
f"/api/projects/{self.team.id}/experiment_saved_metrics/",
{
"name": "Breakdown saved metric",
- "query": {
- "kind": "ExperimentMetric",
- "metric_type": "mean",
- "source": {"kind": "EventsNode", "event": "$pageview"},
- },
+ "query": {"kind": "ExperimentMetric", "metric_type": "mean", "source": source},
},
)
- metadata = {"type": "primary", "breakdowns": [{"type": "event", "property": "$os_name"}]}
+ if rename_action:
+ Action.objects.filter(pk=action.pk).update(name="Current name")
+ metadata = {
+ "type": "primary",
+ "breakdowns": [{"type": "event", "property": "$os_name"}],
+ "breakdown_limit": 20,
+ }
experiment_response = self.client.post(
f"/api/projects/{self.team.id}/experiments/",
{
@@ -1273,6 +1282,8 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
detail = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_response.json()['id']}/")
stamped = detail.json()["saved_metrics"][0]["query"]["fingerprint"]
+ if rename_action:
+ self.assertEqual(detail.json()["saved_metrics"][0]["query"]["source"]["name"], "Current name")
experiment = Experiment.objects.get(pk=experiment_response.json()["id"])
saved_query = experiment.saved_metrics.first().query # type: ignore[union-attr]
@@ -1281,8 +1292,10 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
get_experiment_stats_method(experiment),
experiment.exposure_criteria,
)
+ effective_definition = find_metric_dict(experiment, saved_query["uuid"])
+ assert effective_definition is not None
expected = compute_metric_fingerprint(
- merge_saved_metric_breakdowns(saved_query, metadata),
+ effective_definition,
*fingerprint_args,
only_count_matured_users=experiment.only_count_matured_users,
excluded_variants=experiment.excluded_variants or [],
diff --git a/products/experiments/backend/timeseries_sync.py b/products/experiments/backend/timeseries_sync.py
index 53c52388001d..76c8ca80faad 100644
--- a/products/experiments/backend/timeseries_sync.py
+++ b/products/experiments/backend/timeseries_sync.py
@@ -23,7 +23,7 @@ from posthog.models.scoping import team_scope
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
-from products.experiments.backend.metric_resolution import find_metric_dict, is_daily_timeseries_metric
+from products.experiments.backend.metric_resolution import is_daily_timeseries_metric, resolve_scheduled_metrics
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentMetricResult,
@@ -31,7 +31,6 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.recalculation import get_active_recalculation
from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint
-from products.experiments.backend.temporal.recalculation_logic import discover_experiment_metrics
logger = structlog.get_logger(__name__)
@@ -70,13 +69,12 @@ def sync_timeseries_recalculation(
stats_method = get_experiment_stats_method(experiment)
metric_uuids: list[str] = []
points: dict[str, tuple[str, ExperimentMetricResult]] = {}
- for metric in discover_experiment_metrics(experiment):
- metric_dict = find_metric_dict(experiment, metric.metric_uuid)
- if metric_dict is None or not is_daily_timeseries_metric(metric_dict):
+ for metric in resolve_scheduled_metrics(experiment):
+ if not is_daily_timeseries_metric(metric.definition):
continue
- metric_uuids.append(metric.metric_uuid)
+ metric_uuids.append(metric.uuid)
config_fp = compute_metric_fingerprint(
- metric_dict,
+ metric.definition,
experiment.start_date,
stats_method,
experiment.exposure_criteria,
@@ -86,7 +84,7 @@ def sync_timeseries_recalculation(
row = (
ExperimentMetricResult.objects.filter(
experiment=experiment,
- metric_uuid=metric.metric_uuid,
+ metric_uuid=metric.uuid,
fingerprint=config_fp,
status=ExperimentMetricResult.Status.COMPLETED,
query_to__gte=run_started_at,
@@ -96,7 +94,7 @@ def sync_timeseries_recalculation(
.first()
)
if row is not None:
- points[metric.metric_uuid] = (compute_recalc_fingerprint(config_fp), row)
+ points[metric.uuid] = (compute_recalc_fingerprint(config_fp), row)
if not points:
return None
diff --git a/services/mcp/src/schema/experiments.ts b/services/mcp/src/schema/experiments.ts
index b103ebf53b58..1c4e28e36679 100644
--- a/services/mcp/src/schema/experiments.ts
+++ b/services/mcp/src/schema/experiments.ts
@@ -243,6 +243,44 @@ function toMetricSummary(
}
}
+/**
+ * The effective definition of a shared metric on one experiment: the saved query with the
+ * per-experiment overrides from the link metadata applied. The backend calculates stored results
+ * with `resolve_saved_metric_definition` in
+ * products/experiments/backend/metric_resolution.py, so the two must apply the same
+ * rules, or this tool reports a different metric than the experiment page shows.
+ */
+export function resolveSharedMetric({ query, metadata }: SavedMetricAttachment): unknown {
+ if (query === null || typeof query !== 'object' || Array.isArray(query)) {
+ return query
+ }
+ const saved = query as Record<string, unknown>
+ const overrides: Record<string, unknown> = metadata ?? {}
+ const breakdowns = Array.isArray(overrides.breakdowns) ? overrides.breakdowns : []
+ const hasBreakdowns = breakdowns.length > 0
+ const savedBreakdownFilter =
+ saved.breakdownFilter !== null && typeof saved.breakdownFilter === 'object' ? saved.breakdownFilter : {}
+
+ const resolved: Record<string, unknown> = {
+ ...saved,
+ breakdownFilter: {
+ ...savedBreakdownFilter,
+ breakdowns,
+ ...(hasBreakdowns && overrides.breakdown_limit != null
+ ? { breakdown_limit: overrides.breakdown_limit }
+ : {}),
+ },
+ }
+ if (hasBreakdowns && saved.metric_type === 'funnel' && overrides.breakdownAttributionType != null) {
+ resolved.breakdownAttributionType = overrides.breakdownAttributionType
+ delete resolved.breakdownAttributionValue
+ if (overrides.breakdownAttributionValue != null) {
+ resolved.breakdownAttributionValue = overrides.breakdownAttributionValue
+ }
+ }
+ return resolved
+}
+
/**
* Build the per-position metric entries for a primary/secondary slot, merging the
* inline metrics on the experiment with the shared metrics (saved_metrics), and
@@ -256,7 +294,7 @@ export function buildMetricEntries(experiment: Experiment, slot: 'primary' | 'se
const entries: ResolvedMetricEntry[] = [
...inline.map((metric) => ({ metric: metric as unknown, summary: toMetricSummary(metric, 'inline') })),
...shared.map((sm) => ({
- metric: sm.query,
+ metric: resolveSharedMetric(sm),
summary: toMetricSummary(sm.query, 'shared', {
id: typeof sm.saved_metric === 'number' ? sm.saved_metric : null,
name: typeof sm.name === 'string' ? sm.name : null,
diff --git a/services/mcp/tests/unit/experiments-results-transform.test.ts b/services/mcp/tests/unit/experiments-results-transform.test.ts
index edab03f7611a..eeb235ccfd0c 100644
--- a/services/mcp/tests/unit/experiments-results-transform.test.ts
+++ b/services/mcp/tests/unit/experiments-results-transform.test.ts
@@ -176,6 +176,52 @@ describe('transformExperimentResults', () => {
expect(entry?.summary.saved_metric_name).toBe('Activation funnel (revenue impact)')
})
+ it.each([
+ [
+ 'applies the link breakdowns, limit and attribution',
+ {
+ type: 'primary',
+ breakdowns: [{ property: '$browser', type: 'event' }],
+ breakdown_limit: 20,
+ breakdownAttributionType: 'last_touch',
+ },
+ { breakdownAttributionType: 'last_touch' },
+ { breakdown_limit: 20, breakdowns: [{ property: '$browser', type: 'event' }] },
+ ],
+ [
+ 'ignores the limit and attribution of a link without breakdowns',
+ { type: 'primary', breakdown_limit: 20, breakdownAttributionType: 'last_touch' },
+ { breakdownAttributionType: 'step', breakdownAttributionValue: 2 },
+ { breakdown_limit: 5, breakdowns: [] },
+ ],
+ ])('queries a shared metric as the experiment page does: %s', (_name, metadata, attribution, breakdownFilter) => {
+ const experiment = makeExperiment({
+ saved_metrics: [
+ {
+ saved_metric: 1,
+ name: 'Shared funnel',
+ metadata,
+ query: {
+ uuid: 'shared-funnel',
+ metric_type: 'funnel',
+ breakdownAttributionType: 'step',
+ breakdownAttributionValue: 2,
+ breakdownFilter: { breakdown_limit: 5, breakdowns: [{ property: '$os', type: 'event' }] },
+ },
+ },
+ ],
+ })
+
+ const [entry] = buildMetricEntries(experiment, 'primary')
+
+ expect(entry?.metric).toEqual({
+ uuid: 'shared-funnel',
+ metric_type: 'funnel',
+ ...attribution,
+ breakdownFilter,
+ })
+ })
+
it('orders result rows by *_metrics_ordered_uuids (the canonical UI ordering)', () => {
// Insertion order puts the inline metric first; ordered_uuids puts the shared one
// first. Without the sort step, an agent reading top-to-bottom would see a