:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): serve effective metric definitions from the API (#109357)
Anders0472e8f553f7
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex 80391246731c..ae7d7de1c446 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -673,6 +673,13 @@ describe('experimentLogic', () => {source: { kind: NodeKind.EventsNode, event: '$pageview' },},metadata: { type: 'primary', breakdowns: [breakdown], breakdown_limit: 20 },+ effective_query: {+ uuid: 'shared-metric-uuid',+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: '$pageview' },+ breakdownFilter: { breakdowns: [breakdown], breakdown_limit: 20 },+ },created_at: '2024-01-01T00:00:00Z',} as unknown as ExperimentSavedMetric@@ -1388,7 +1395,15 @@ describe('experimentLogic', () => {expect(updatedMetric.breakdownFilter?.breakdowns).toEqual([{ property: '$os', type: 'event' }])})- it('should remove breakdown from shared metric metadata', () => {+ const browserBreakdown: Breakdown = { property: '$browser', type: 'event' }+ const osBreakdown: Breakdown = { property: '$os', type: 'event' }++ it.each([+ ['the shown breakdown', [browserBreakdown, osBreakdown], 0, browserBreakdown, [osBreakdown]],+ // The scene shows the last saved effective_query, so before the first removal saves, $os is still+ // shown at index 1 while the link metadata already holds it at index 0.+ ['the shown breakdown while an earlier removal is unsaved', [osBreakdown], 1, osBreakdown, []],+ ])('should remove %s from shared metric metadata', (_name, linkBreakdowns, shownIndex, shown, expected) => {const testExperiment: Experiment = {...experiment,saved_metrics: [@@ -1403,12 +1418,13 @@ describe('experimentLogic', () => {metric_type: ExperimentMetricType.MEAN,source: { kind: NodeKind.EventsNode, event: '$pageview' },},- metadata: {- type: 'primary',- breakdowns: [- { property: '$browser', type: 'event' } satisfies Breakdown,- { property: '$os', type: 'event' } satisfies Breakdown,- ],+ metadata: { type: 'primary', breakdowns: linkBreakdowns },+ effective_query: {+ uuid: 'shared-metric-uuid',+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: '$pageview' },+ breakdownFilter: { breakdowns: [browserBreakdown, osBreakdown] },},created_at: '2024-01-01T00:00:00Z',} satisfies ExperimentSavedMetric,@@ -1417,12 +1433,9 @@ describe('experimentLogic', () => {}logic.actions.setExperiment(testExperiment)- const breakdownToRemove: Breakdown = { property: '$browser', type: 'event' }- logic.actions.removeMetricBreakdown('shared-metric-uuid', 0, breakdownToRemove)+ logic.actions.removeMetricBreakdown('shared-metric-uuid', shownIndex, shown)- expect(logic.values.experiment.saved_metrics[0].metadata.breakdowns).toEqual([- { property: '$os', type: 'event' },- ])+ expect(logic.values.experiment.saved_metrics[0].metadata.breakdowns).toEqual(expected)})it('should include breakdowns when preparing shared metrics for loading', () => {@@ -1447,6 +1460,13 @@ describe('experimentLogic', () => {{ property: '$os', type: 'event' } satisfies Breakdown,],},+ effective_query: {+ uuid: 'shared-metric-uuid',+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: '$pageview' },+ breakdownFilter: { breakdowns: [browserBreakdown, osBreakdown] },+ },created_at: '2024-01-01T00:00:00Z',} satisfies ExperimentSavedMetric,],@@ -1557,6 +1577,13 @@ describe('experimentLogic', () => {{ property: '$os', type: 'event' } satisfies Breakdown,],},+ effective_query: {+ uuid: 'secondary-metric-uuid',+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: '$pageview' },+ breakdownFilter: { breakdowns: [browserBreakdown, osBreakdown] },+ },created_at: '2024-01-01T00:00:00Z',} satisfies ExperimentSavedMetric,],@@ -1625,6 +1652,57 @@ describe('experimentLogic', () => {expect(logic.values.experiment.saved_metrics[0].metadata.breakdown_limit).toEqual(10)})++ it.each([+ ['reloads the section of a shared primary metric', true, ['loadPrimaryMetricsResults']],+ ['skips the reload when the save fails', false, []],+ ])('adding a breakdown %s', async (_name, saveSucceeds, reloaded) => {+ useMocks({+ post: {+ '/api/environments/:team/query': () => [+ 200,+ { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },+ ],+ },+ get: {+ '/api/environments/:team/query/:id': () => [200, experimentMetricResultsSuccessJson],+ },+ })+ const testExperiment: Experiment = {+ ...experiment,+ saved_metrics: [+ {+ id: 1,+ experiment: experiment.id as number,+ saved_metric: 123,+ name: 'Shared Metric',+ query: {+ uuid: 'shared-metric-uuid',+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: '$pageview' },+ },+ metadata: { type: 'primary' },+ created_at: '2024-01-01T00:00:00Z',+ } satisfies ExperimentSavedMetric,+ ],+ metrics: [],+ }+ logic.actions.setExperiment(testExperiment)+ if (saveSucceeds) {+ jest.spyOn(api, 'update').mockResolvedValue(testExperiment)+ } else {+ jest.spyOn(api, 'update').mockRejectedValue(new Error('network down'))+ }+ const reloads = ['loadPrimaryMetricsResults', 'loadSecondaryMetricsResults', 'refreshExperimentResults']++ await expectLogic(logic, () => {+ logic.actions.updateMetricBreakdown('shared-metric-uuid', browserBreakdown)+ })+ .toDispatchActions(reloaded)+ .toFinishAllListeners()+ .toNotHaveDispatchedActions(reloads.filter((action) => !reloaded.includes(action)))+ })})describe('launchExperiment', () => {diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex a3d84a8e892b..e83edfae47ed 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -25,6 +25,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { eventUsageLogic, getEventPropertiesForExperiment } from 'lib/utils/eventUsageLogic'import { addProjectIdIfMissing } from 'lib/utils/kea-router'+import { objectsEqual } from 'lib/utils/objects'import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'import { billingLogic } from 'scenes/billing/billingLogic'@@ -143,7 +144,7 @@ import {conflictPreservedFields,isExperimentConflictError,isLegacyExperiment,- resolveSharedMetric,+ sharedMetricEffectiveQuery,sharedMetricsToExperimentMetrics,toConcurrencyPayload,toFlagVariantsInput,@@ -291,6 +292,31 @@ export function getSectionMetricUuids(experiment: Experiment, isSecondary: boolereturn [...inlineMetrics.map((metric) => metric.uuid), ...sharedMetrics.map(({ query }) => query?.uuid)]}+function isPrimaryMetric(experiment: Experiment, uuid: string): boolean {+ const sharedMetric = ((experiment.saved_metrics || []) as ExperimentSavedMetric[]).find(+ ({ query }) => query?.uuid === uuid+ )+ return sharedMetric ? sharedMetric.metadata.type === 'primary' : experiment.metrics.some((m) => m.uuid === uuid)+}++/**+ * kea-loaders turns a rejected loader into a failure action, so awaiting `asyncActions.updateExperiment()` does+ * not throw. Call this right after dispatching `updateExperiment`: it awaits the queued request of that dispatch+ * and returns whether the save succeeded. The loader still owns error reporting and conflict recovery.+ */+async function inflightUpdateSaved(cache: Record<string, any>): Promise<boolean> {+ const updatePromise: Promise<Experiment> | undefined = cache.inflightUpdate?.promise+ if (!updatePromise) {+ return false+ }+ try {+ await updatePromise+ return true+ } catch {+ return false+ }+}+// Max concurrent metric queries to avoid overwhelming the celery queue's// per-team concurrency limit (10). Using runWithLimit instead of Promise.all// prevents mass rejections and retry churn when experiments have many metrics.@@ -1817,7 +1843,7 @@ export const experimentLogic = kea<experimentLogicType>([const name = `${savedMetric.name || getDefaultMetricTitle(query)} (copy)`const newMetric = {- ...resolveSharedMetric(savedMetric),+ ...sharedMetricEffectiveQuery(savedMetric),uuid: newUuid,name,}@@ -1884,7 +1910,7 @@ export const experimentLogic = kea<experimentLogicType>([[metricsKey]: metrics,}},- removeMetricBreakdown: (state, { uuid, index }) => {+ removeMetricBreakdown: (state, { uuid, index, breakdown }) => {/*** Check if the UUID belongs to a shared metric* Shared Metric types are confusing. The query property@@ -1896,13 +1922,18 @@ export const experimentLogic = kea<experimentLogicType>([)if (savedMetricIndex !== -1) {- // Handle shared metric - update saved_metrics metadata+ // Handle shared metric - update saved_metrics metadata. The scene shows the breakdowns+ // of the link's effective_query, which only the API resolves, so that list can differ+ // from metadata.breakdowns until the save returns. Remove the breakdown by value, so+ // that an index into the shown list never removes a different breakdown.const savedMetric = savedMetrics[savedMetricIndex]+ const breakdowns = savedMetric.metadata?.breakdowns || []+ const position = breakdowns.findIndex((candidate) => objectsEqual(candidate, breakdown))savedMetrics[savedMetricIndex] = {...savedMetric,metadata: {...savedMetric.metadata,- breakdowns: (savedMetric.metadata?.breakdowns || []).filter((_, i) => i !== index),+ breakdowns: breakdowns.filter((_, i) => i !== position),},}@@ -3412,7 +3443,7 @@ export const experimentLogic = kea<experimentLogicType>([}},updateMetricBreakdown: async ({ uuid, breakdown }) => {- const isPrimary = values.experiment.metrics.some((m) => m.uuid === uuid)+ const isPrimary = isPrimaryMetric(values.experiment, uuid)actions.reportExperimentMetricBreakdownAdded(values.experiment, uuid, breakdown, isPrimary)@@ -3435,6 +3466,10 @@ export const experimentLogic = kea<experimentLogicType>([}actions.updateExperiment(updatePayload)+ // The reload reads a shared metric's effective_query, which only the save response carries.+ if (!(await inflightUpdateSaved(cache))) {+ return+ }// Adding a breakdown changes how the metric is computed, so re-run results. The recalculation// flow reuses the current window (metric_config_change), so this breakdown recomputes on its@@ -3448,7 +3483,7 @@ export const experimentLogic = kea<experimentLogicType>([}},removeMetricBreakdown: async ({ uuid, index, breakdown }) => {- const isPrimary = values.experiment.metrics.some((m) => m.uuid === uuid)+ const isPrimary = isPrimaryMetric(values.experiment, uuid)actions.reportExperimentMetricBreakdownRemoved(values.experiment, uuid, breakdown, index, isPrimary)@@ -3471,6 +3506,10 @@ export const experimentLogic = kea<experimentLogicType>([}actions.updateExperiment(updatePayload)+ // The reload reads a shared metric's effective_query, which only the save response carries.+ if (!(await inflightUpdateSaved(cache))) {+ return+ }// Removing a breakdown changes how the metric is computed, so re-run results. On the// recalculation flow this reuses the current window (metric_config_change), so this metric@@ -3508,14 +3547,15 @@ export const experimentLogic = kea<experimentLogicType>([/*** guard against failed persist calling recalculations by awaiting the experiment save*/- await asyncActions.updateExperiment(updatePayload)+ actions.updateExperiment(updatePayload)+ if (!(await inflightUpdateSaved(cache))) {+ return+ }/*** figure out if it's a primary metric*/- const isPrimary = sharedMetric- ? sharedMetric.metadata.type === 'primary'- : values.experiment.metrics.some((m) => m.uuid === uuid)+ const isPrimary = isPrimaryMetric(values.experiment, uuid)/*** updating a breakdown limit triggers a recalculation.@@ -3553,14 +3593,15 @@ export const experimentLogic = kea<experimentLogicType>([/*** guard against failed persist calling recalculations by awaiting the experiment save*/- await asyncActions.updateExperiment(updatePayload)+ actions.updateExperiment(updatePayload)+ if (!(await inflightUpdateSaved(cache))) {+ return+ }/*** find if the updated metris is primary*/- const isPrimary = sharedMetric- ? sharedMetric.metadata.type === 'primary'- : values.experiment.metrics.some((m) => m.uuid === uuid)+ const isPrimary = isPrimaryMetric(values.experiment, uuid)/*** updating a breakdown limit triggers a recalculation.*/diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.tsindex 2ea8ae108fc9..8d2dce920a8e 100644--- a/frontend/src/scenes/experiments/utils.test.ts+++ b/frontend/src/scenes/experiments/utils.test.ts@@ -1,6 +1,5 @@import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'import {- Breakdown,CachedNewExperimentQueryResponse,ExperimentEventExposureConfig,ExperimentMetric,@@ -10,7 +9,6 @@ import {} from '~/queries/schema/schema-general'import {AccessControlLevel,- BreakdownAttributionType,Experiment,ExperimentMetricMathType,FeatureFlagBucketingIdentifier,@@ -42,7 +40,7 @@ import {isLegacyExperimentQuery,metricResults,percentageDistribution,- resolveSharedMetric,+ sharedMetricsToExperimentMetrics,toConcurrencyPayload,toExperimentWritePayload,withoutProjectedFlagConfig,@@ -842,79 +840,6 @@ describe('getOrderedMetricsWithResults', () => {expect(ordered[0].metric.isSharedMetric).toBe(true)})- it('merges breakdowns from metadata into shared metrics', () => {- const breakdowns: Breakdown[] = [- { property: '$browser', type: 'event' },- { property: '$os', type: 'event' },- ]-- const experiment = {- ...baseExperiment,- saved_metrics: [- {- saved_metric: 123,- name: 'Shared Metric',- query: {- uuid: 'shared-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'test' },- },- metadata: {- type: 'primary',- breakdowns,- },- },- ],- primary_metrics_ordered_uuids: ['shared-uuid'],- }-- const results = [mockResult({ result: 'shared-data' })]- const errors = [null]-- const ordered = getOrderedMetricsWithResults(experiment, results, errors, [], [], false)-- expect(ordered).toHaveLength(1)- expect(ordered[0].metric.breakdownFilter?.breakdowns).toEqual(breakdowns)- })-- it('merges existing breakdownFilter properties with metadata breakdowns', () => {- const metadataBreakdowns: Breakdown[] = [{ property: '$browser', type: 'event' }]-- const experiment = {- ...baseExperiment,- saved_metrics: [- {- saved_metric: 123,- name: 'Shared Metric',- query: {- uuid: 'shared-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'test' },- breakdownFilter: { some_other_prop: 'value' },- },- metadata: {- type: 'primary',- breakdowns: metadataBreakdowns,- },- },- ],- primary_metrics_ordered_uuids: ['shared-uuid'],- }-- const results = [mockResult({ result: 'shared-data' })]- const errors = [null]-- const ordered = getOrderedMetricsWithResults(experiment, results, errors, [], [], false)-- expect(ordered).toHaveLength(1)- expect(ordered[0].metric.breakdownFilter).toEqual({- some_other_prop: 'value',- breakdowns: metadataBreakdowns,- })- })-it('filters shared metrics by type (primary vs secondary)', () => {const experiment = {...baseExperiment,@@ -972,103 +897,6 @@ 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', () => {@@ -1124,59 +952,6 @@ describe('getOrderedMetricsWithResults', () => {expect(ordered).toEqual([])})- it('handles empty breakdowns array in metadata', () => {- const experiment = {- ...baseExperiment,- saved_metrics: [- {- saved_metric: 123,- name: 'Shared',- query: {- uuid: 'shared-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'test' },- },- metadata: {- type: 'primary',- breakdowns: [],- },- },- ],- primary_metrics_ordered_uuids: ['shared-uuid'],- }-- const ordered = getOrderedMetricsWithResults(experiment, [mockResult({})], [null], [], [], false)-- expect(ordered).toHaveLength(1)- expect(ordered[0].metric.breakdownFilter?.breakdowns).toEqual([])- })-- it('handles missing breakdowns in metadata', () => {- const experiment = {- ...baseExperiment,- saved_metrics: [- {- saved_metric: 123,- name: 'Shared',- query: {- uuid: 'shared-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'test' },- },- metadata: { type: 'primary' },- },- ],- primary_metrics_ordered_uuids: ['shared-uuid'],- }-- const ordered = getOrderedMetricsWithResults(experiment, [mockResult({})], [null], [], [], false)-- expect(ordered).toHaveLength(1)- expect(ordered[0].metric.breakdownFilter?.breakdowns).toEqual([])- })-it('tracks metricIndex for retry functionality', () => {const experiment = {...baseExperiment,@@ -1318,34 +1093,49 @@ describe('metricResults', () => {expect(ordered.map((o) => o.result)).toEqual([{ result: 'data2' }, { result: 'data1' }])})- it('enriches shared metrics and merges metadata breakdowns', () => {- const breakdowns: Breakdown[] = [{ property: '$browser', type: 'event' }]+ const savedQuery = {+ uuid: 'shared-uuid',+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: 'test' },+ }+ const effectiveQuery = {+ ...savedQuery,+ breakdownFilter: { breakdown_limit: 20, breakdowns: [{ property: '$browser', type: 'event' }] },+ fingerprint: 'effective-fingerprint',+ }++ it.each([+ ['the effective query the API resolved', { effective_query: effectiveQuery }, effectiveQuery],+ ['the saved query of a legacy shared metric', { effective_query: null }, savedQuery],+ ['the saved query when the API predates effective_query', {}, savedQuery],+ ['an empty metric when the link carries no query', { query: undefined }, {}],+ ])('shows and queries a shared metric with %s', (_name, effectiveQueryField, expectedQuery) => {const experiment = {...baseExperiment,saved_metrics: [{saved_metric: 123,name: 'Shared Metric',- query: {- uuid: 'shared-uuid',- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'test' },- },- metadata: { type: 'primary', breakdowns },+ query: savedQuery,+ metadata: { type: 'primary', breakdowns: [{ property: '$browser', type: 'event' }] },+ ...effectiveQueryField,},],primary_metrics_ordered_uuids: ['shared-uuid'],}- const ordered = metricResults(experiment)([mockResult({ result: 'shared' })], [null], 'primary')+ const ordered = metricResults(experiment)([mockResult({})], [null], 'primary')- expect(ordered).toHaveLength(1)- expect(ordered[0].metric.uuid).toBe('shared-uuid')- expect(ordered[0].metric.name).toBe('Shared Metric')- expect(ordered[0].metric.sharedMetricId).toBe(123)- expect(ordered[0].metric.isSharedMetric).toBe(true)- expect(ordered[0].metric.breakdownFilter?.breakdowns).toEqual(breakdowns)+ expect(ordered[0].metric).toEqual({+ ...expectedQuery,+ name: 'Shared Metric',+ sharedMetricId: 123,+ isSharedMetric: true,+ })+ expect(+ sharedMetricsToExperimentMetrics(experiment.saved_metrics as unknown as ExperimentSavedMetric[], 'primary')+ ).toEqual([expectedQuery])})it('only includes shared metrics whose metadata type matches', () => {diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex 6798a1fbf630..36b2723c9ec0 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -53,6 +53,7 @@ import { EXPERIMENT_VARIANT_MULTIPLE } from 'products/experiments/frontend/constimport type {ExperimentFeatureFlagFiltersApi,ExperimentFeatureFlagInputApi,+ ExperimentToSavedMetricApi,} from 'products/experiments/frontend/generated/api.schemas'import {@@ -1017,10 +1018,11 @@ export function getDisplayOrderedIndices(return ordered}-export type ExperimentSavedMetric = {- id: number- experiment: number- saved_metric: number+/**+ * A shared metric's link to an experiment, as the experiment API returns it. The generated type leaves+ * `query` and `metadata` untyped, so this narrows them to the shapes the experiment scene reads and edits.+ */+export type ExperimentSavedMetric = Omit<ExperimentToSavedMetricApi, 'metadata' | 'query' | 'effective_query'> & {metadata: {type: 'primary' | 'secondary'breakdowns?: Breakdown[]@@ -1028,47 +1030,32 @@ export type ExperimentSavedMetric = {breakdownAttributionValue?: numberbreakdown_limit?: number}- created_at: stringquery: ExperimentMetric- name: string+ // Optional because a new frontend can briefly receive a response from an API server that predates the field.+ effective_query?: ExperimentMetric | null}/**- * 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.+ * The backend applies the link overrides to the saved query and serves the result as `effective_query`.+ * A legacy shared metric takes no overrides and has no effective query, so its saved query applies as is.+ * A link that carries no query gets an empty metric. Results map to metrics by position, and the callers+ * read fields of every metric, so the link must keep its position.*/-export function resolveSharedMetric({+export const sharedMetricEffectiveQuery = ({query,- metadata,-}: Pick<ExperimentSavedMetric, 'query' | 'metadata'>): ExperimentMetric {- const breakdowns = metadata?.breakdowns || []- const hasBreakdowns = breakdowns.length > 0- return {- ...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-}+ effective_query,+}: Pick<ExperimentSavedMetric, 'query' | 'effective_query'>): ExperimentMetric =>+ effective_query ?? query ?? ({} as ExperimentMetric)export const sharedMetricsToExperimentMetrics = (sharedMetrics: ExperimentSavedMetric[] | undefined,type: 'primary' | 'secondary'-): ExperimentMetric[] => (sharedMetrics || []).filter(({ metadata }) => metadata.type === type).map(resolveSharedMetric)+): ExperimentMetric[] =>+ (sharedMetrics || []).filter(({ metadata }) => metadata.type === type).map(sharedMetricEffectiveQuery)function enrichSharedMetric(sharedMetric: ExperimentSavedMetric): ExperimentMetric {return {- ...resolveSharedMetric(sharedMetric),+ ...sharedMetricEffectiveQuery(sharedMetric),name: sharedMetric.name,sharedMetricId: sharedMetric.saved_metric,isSharedMetric: true,diff --git a/products/experiments/backend/facade/timeseries.py b/products/experiments/backend/facade/timeseries.pyindex 0f97f566d4f0..1fcd2118f142 100644--- a/products/experiments/backend/facade/timeseries.py+++ b/products/experiments/backend/facade/timeseries.py@@ -1,6 +1,7 @@"""Timeseries capabilities, re-exported for callers outside the experiments product."""from products.experiments.backend.metric_resolution import (+ METRIC_BUILDERS,build_metric,is_daily_timeseries_metric,is_scheduled_metric,@@ -10,6 +11,7 @@ from products.experiments.backend.timeseries_backfill import backfill_experimentfrom products.experiments.backend.timeseries_sync import sync_timeseries_recalculation__all__ = [+ "METRIC_BUILDERS","backfill_experiment_timeseries","build_metric","is_daily_timeseries_metric",diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 660e0bdf8234..bf8ad5e03f19 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -11,7 +11,7 @@ from typing import Annotated, Any, TypeGuardfrom django.utils import timezone-from drf_spectacular.utils import extend_schema_field+from drf_spectacular.utils import extend_schema_field, extend_schema_serializerfrom opentelemetry import tracefrom pydantic import (Field as PydanticField,@@ -26,6 +26,7 @@ from posthog.schema import (EventPropertyFilter,ExperimentApiExposureCriteria,ExperimentApiMetric,+ ExperimentMetric,ExperimentParameters,ExperimentRunningTimeCalculation,MultipleVariantHandling,@@ -43,7 +44,7 @@ from products.access_control.backend.presentation.access_control import UserAccefrom products.ai_observability.backend.models.llm_prompt import LLMPromptfrom products.experiments.backend.experiment_service import ExperimentServicefrom products.experiments.backend.facade.contracts import CreateExperimentInput-from products.experiments.backend.facade.timeseries import resolve_saved_metric_definition+from products.experiments.backend.facade.timeseries import METRIC_BUILDERS, resolve_saved_metric_definitionfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.exposure_query_logic import resolve_default_exposure_eventfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_method@@ -173,6 +174,11 @@ class ExperimentRunningTimeCalculationField(serializers.JSONField):pass+@extend_schema_field(ExperimentMetric) # type: ignore[arg-type]+class ExperimentMetricDefinitionField(serializers.JSONField):+ pass++class ExperimentBaseSerializer(TaggedItemSerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer):@@ -366,6 +372,28 @@ def _dedupe_metric_ordering(value: list[str] | None) -> list[str] | None:return list(dict.fromkeys(value))+@extend_schema_serializer(component_name="ExperimentToSavedMetric")+class ExperimentSavedMetricLinkSerializer(ExperimentToSavedMetricSerializer):+ """A shared metric's link to one experiment, as the experiment API returns it."""++ # The link model has no such attribute, so this serializer renders it as null.+ # ExperimentSerializer.to_representation sets the value from the served query.+ effective_query = ExperimentMetricDefinitionField(+ read_only=True,+ allow_null=True,+ help_text=(+ "The metric this experiment calculates for this shared metric: `query` with the per-experiment "+ "overrides from `metadata` applied (breakdowns, breakdown_limit, and funnel breakdown attribution). "+ "Results, fingerprints and queries for this metric use this definition, not `query`. "+ "Null when `query` is not an ExperimentMetric, such as a legacy shared metric "+ "(kind ExperimentTrendsQuery or ExperimentFunnelsQuery), which takes no overrides."+ ),+ )++ class Meta(ExperimentToSavedMetricSerializer.Meta):+ fields = [*ExperimentToSavedMetricSerializer.Meta.fields, "effective_query"]++class ExperimentSerializer(ExperimentBaseSerializer):"""Full experiment representation for the detail, create, and update endpoints.@@ -382,7 +410,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):allow_null=True,help_text="ID of a holdout group to exclude from the experiment.",)- saved_metrics = ExperimentToSavedMetricSerializer(many=True, source="experimenttosavedmetric_set", read_only=True)+ saved_metrics = ExperimentSavedMetricLinkSerializer(many=True, source="experimenttosavedmetric_set", read_only=True)saved_metrics_ids = serializers.ListField(child=serializers.JSONField(),required=False,@@ -664,6 +692,19 @@ class ExperimentSerializer(ExperimentBaseSerializer):excluded_variants=instance.excluded_variants or [],)+ # Derived from the served query after the fingerprint is stamped, so that the effective+ # definition carries the same fingerprint and refreshed action names. Clients send it to+ # /query as is. The schema types it as the ExperimentMetric union, so a query outside the+ # union (a legacy kind, or a row without a known metric_type) keeps the null default.+ served_query = saved_metric["query"]+ if (+ served_query.get("kind") == "ExperimentMetric"+ and served_query.get("metric_type") in METRIC_BUILDERS+ ):+ saved_metric["effective_query"] = resolve_saved_metric_definition(+ served_query, saved_metric.get("metadata")+ )+return datadef validate_saved_metrics_ids(self, value):diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex a9e934c148c2..5023a611d55a 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -625,6 +625,23 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertTrue(response.json()["is_legacy"])+ @parameterized.expand(+ [+ ("legacy_kind", {"kind": "ExperimentFunnelsQuery"}),+ ("no_kind", {"metric_type": "mean", "source": {"kind": "EventsNode", "event": "$pageview"}}),+ ("no_metric_type", {"kind": "ExperimentMetric", "source": {"kind": "EventsNode", "event": "$pageview"}}),+ ]+ )+ def test_detail_serves_no_effective_query_for_a_query_outside_the_metric_union(+ self, _name: str, saved_query: dict[str, Any]+ ) -> None:+ experiment, _ = self._create_experiment_with_action_metrics(0)+ ExperimentSavedMetric.objects.filter(experimenttosavedmetric__experiment=experiment).update(query=saved_query)++ response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment.id}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIsNone(response.json()["saved_metrics"][0]["effective_query"])+@parameterized.expand([# (name, flag enabled for team, start_date offset from cutoff in days, expected event)@@ -1242,11 +1259,20 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):{"id": holdout_2_id, "exclusion_percentage": 5},)- @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):+ @parameterized.expand(+ [+ ("event_source", False, True),+ ("action_source_renamed_after_the_save", True, True),+ ("limit_without_link_breakdowns", False, False),+ ]+ )+ def test_saved_metric_fingerprint_is_stamped_from_the_merged_query(+ self, _name: str, rename_action: bool, link_has_breakdowns: bool+ ):"""The stamped fingerprint tells the frontend which timeseries rows to read. It must be computed onthe saved query with the link overrides applied, the same dict the daily workflow files its rowsunder, or the chart reads an empty series for an override-configured saved metric."""+ breakdowns = [{"type": "event", "property": "$os_name"}] if link_has_breakdowns else []action = Action.objects.create(team=self.team, name="Stored name", steps_json=[{"event": "$pageview"}])source = ({"kind": "ActionsNode", "id": action.id, "name": action.name}@@ -1262,11 +1288,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):)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,- }+ metadata = {"type": "primary", "breakdowns": breakdowns, "breakdown_limit": 20}experiment_response = self.client.post(f"/api/projects/{self.team.id}/experiments/",{@@ -1281,9 +1303,20 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):self.assertEqual(experiment_response.status_code, status.HTTP_201_CREATED)detail = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_response.json()['id']}/")- stamped = detail.json()["saved_metrics"][0]["query"]["fingerprint"]+ served = detail.json()["saved_metrics"][0]+ stamped = served["query"]["fingerprint"]if rename_action:- self.assertEqual(detail.json()["saved_metrics"][0]["query"]["source"]["name"], "Current name")+ self.assertEqual(served["query"]["source"]["name"], "Current name")+ # The link limit applies only together with link breakdowns.+ self.assertEqual(+ served["effective_query"],+ {+ **served["query"],+ "breakdownFilter": (+ {"breakdowns": breakdowns, "breakdown_limit": 20} if link_has_breakdowns else {"breakdowns": []}+ ),+ },+ )experiment = Experiment.objects.get(pk=experiment_response.json()["id"])saved_query = experiment.saved_metrics.first().query # type: ignore[union-attr]@@ -1301,17 +1334,18 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):excluded_variants=experiment.excluded_variants or [],)self.assertEqual(stamped, expected)- # The raw query hashes differently when real breakdowns exist, so a stamp computed on it would- # point the chart at rows that do not exist.- self.assertNotEqual(- stamped,- compute_metric_fingerprint(- saved_query,- *fingerprint_args,- only_count_matured_users=experiment.only_count_matured_users,- excluded_variants=experiment.excluded_variants or [],- ),- )+ if link_has_breakdowns:+ # The raw query hashes differently when real breakdowns exist, so a stamp computed on it would+ # point the chart at rows that do not exist.+ self.assertNotEqual(+ stamped,+ compute_metric_fingerprint(+ saved_query,+ *fingerprint_args,+ only_count_matured_users=experiment.only_count_matured_users,+ excluded_variants=experiment.excluded_variants or [],+ ),+ )def test_saved_metrics(self):response = self.client.post(diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 5e1de05b847d..a92e51201298 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -933,21 +933,82 @@ export interface ExperimentFeatureFlagInputApi {ensure_experience_continuity?: boolean | null}-export interface ExperimentToSavedMetricApi {- readonly id: number- experiment: number- saved_metric: number- metadata?: unknown- readonly created_at: string- readonly query: unknown- readonly name: string+export type BreakdownTypeApi = (typeof BreakdownTypeApi)[keyof typeof BreakdownTypeApi]++export const BreakdownTypeApi = {+ Cohort: 'cohort',+ Person: 'person',+ Event: 'event',+ EventMetadata: 'event_metadata',+ Element: 'element',+ Group: 'group',+ Session: 'session',+ Hogql: 'hogql',+ DataWarehouse: 'data_warehouse',+ DataWarehousePersonProperty: 'data_warehouse_person_property',+ RevenueAnalytics: 'revenue_analytics',+} as const++export type MultipleBreakdownTypeApi = (typeof MultipleBreakdownTypeApi)[keyof typeof MultipleBreakdownTypeApi]++export const MultipleBreakdownTypeApi = {+ Person: 'person',+ Event: 'event',+ EventMetadata: 'event_metadata',+ Element: 'element',+ Group: 'group',+ Session: 'session',+ Hogql: 'hogql',+ Cohort: 'cohort',+ RevenueAnalytics: 'revenue_analytics',+ DataWarehouse: 'data_warehouse',+ DataWarehousePersonProperty: 'data_warehouse_person_property',+} as const++export interface BreakdownApi {+ group_type_index?: number | null+ histogram_bin_count?: number | null+ normalize_url?: boolean | null+ property: string | number+ type?: MultipleBreakdownTypeApi | null}-export type Kind2Api = (typeof Kind2Api)[keyof typeof Kind2Api]+export interface BreakdownFilterApi {+ breakdown?: string | (string | number)[] | number | null+ breakdown_group_type_index?: number | null+ breakdown_hide_other_aggregation?: boolean | null+ breakdown_histogram_bin_count?: number | null+ breakdown_limit?: number | null+ breakdown_normalize_url?: boolean | null+ breakdown_path_cleaning?: boolean | null+ breakdown_type?: BreakdownTypeApi | null+ breakdowns?: BreakdownApi[] | null+}-export const Kind2Api = {- ExperimentEventExposureConfig: 'ExperimentEventExposureConfig',- ActionsNode: 'ActionsNode',+export type FunnelConversionWindowTimeUnitApi =+ (typeof FunnelConversionWindowTimeUnitApi)[keyof typeof FunnelConversionWindowTimeUnitApi]++export const FunnelConversionWindowTimeUnitApi = {+ Second: 'second',+ Minute: 'minute',+ Hour: 'hour',+ Day: 'day',+ Week: 'week',+ Month: 'month',+} as const++export type ExperimentMetricGoalApi = (typeof ExperimentMetricGoalApi)[keyof typeof ExperimentMetricGoalApi]++export const ExperimentMetricGoalApi = {+ Increase: 'increase',+ Decrease: 'decrease',+} as const++export type ExperimentMeanMetricApiMetricType =+ (typeof ExperimentMeanMetricApiMetricType)[keyof typeof ExperimentMeanMetricApiMetricType]++export const ExperimentMeanMetricApiMetricType = {+ Mean: 'mean',} as constexport type PropertyOperatorApi = (typeof PropertyOperatorApi)[keyof typeof PropertyOperatorApi]@@ -1275,6 +1336,712 @@ export interface BehavioralPropertyFilterApi {value: InlineBehavioralTypeApi}+export type BaseMathTypeApi = (typeof BaseMathTypeApi)[keyof typeof BaseMathTypeApi]++export const BaseMathTypeApi = {+ Total: 'total',+ Dau: 'dau',+ WeeklyActive: 'weekly_active',+ MonthlyActive: 'monthly_active',+ UniqueSession: 'unique_session',+ FirstTimeForUser: 'first_time_for_user',+ FirstMatchingEventForUser: 'first_matching_event_for_user',+} as const++export type FunnelMathTypeApi = (typeof FunnelMathTypeApi)[keyof typeof FunnelMathTypeApi]++export const FunnelMathTypeApi = {+ Total: 'total',+ FirstTimeForUser: 'first_time_for_user',+ FirstTimeForUserWithFilters: 'first_time_for_user_with_filters',+} as const++export type PropertyMathTypeApi = (typeof PropertyMathTypeApi)[keyof typeof PropertyMathTypeApi]++export const PropertyMathTypeApi = {+ Avg: 'avg',+ Sum: 'sum',+ Min: 'min',+ Max: 'max',+ Median: 'median',+ P75: 'p75',+ P90: 'p90',+ P95: 'p95',+ P99: 'p99',+} as const++export type CountPerActorMathTypeApi = (typeof CountPerActorMathTypeApi)[keyof typeof CountPerActorMathTypeApi]++export const CountPerActorMathTypeApi = {+ AvgCountPerActor: 'avg_count_per_actor',+ MinCountPerActor: 'min_count_per_actor',+ MaxCountPerActor: 'max_count_per_actor',+ MedianCountPerActor: 'median_count_per_actor',+ P75CountPerActor: 'p75_count_per_actor',+ P90CountPerActor: 'p90_count_per_actor',+ P95CountPerActor: 'p95_count_per_actor',+ P99CountPerActor: 'p99_count_per_actor',+} as const++export type GroupMathTypeApi = (typeof GroupMathTypeApi)[keyof typeof GroupMathTypeApi]++export const GroupMathTypeApi = {+ UniqueGroup: 'unique_group',+ FirstTimeForGroup: 'first_time_for_group',+ FirstMatchingEventForGroup: 'first_matching_event_for_group',+} as const++export type ExperimentMetricMathTypeApi = (typeof ExperimentMetricMathTypeApi)[keyof typeof ExperimentMetricMathTypeApi]++export const ExperimentMetricMathTypeApi = {+ Total: 'total',+ Sum: 'sum',+ UniqueSession: 'unique_session',+ Min: 'min',+ Max: 'max',+ Avg: 'avg',+ Dau: 'dau',+ UniqueGroup: 'unique_group',+ Hogql: 'hogql',+} as const++export type CalendarHeatmapMathTypeApi = (typeof CalendarHeatmapMathTypeApi)[keyof typeof CalendarHeatmapMathTypeApi]++export const CalendarHeatmapMathTypeApi = {+ Total: 'total',+ Dau: 'dau',+} as const++export type MathGroupTypeIndexApi = (typeof MathGroupTypeIndexApi)[keyof typeof MathGroupTypeIndexApi]++export const MathGroupTypeIndexApi = {+ Number0: 0,+ Number1: 1,+ Number2: 2,+ Number3: 3,+ Number4: 4,+} as const++export type CurrencyCodeApi = (typeof CurrencyCodeApi)[keyof typeof CurrencyCodeApi]++export const CurrencyCodeApi = {+ Aed: 'AED',+ Afn: 'AFN',+ All: 'ALL',+ Amd: 'AMD',+ Ang: 'ANG',+ Aoa: 'AOA',+ Ars: 'ARS',+ Aud: 'AUD',+ Awg: 'AWG',+ Azn: 'AZN',+ Bam: 'BAM',+ Bbd: 'BBD',+ Bdt: 'BDT',+ Bgn: 'BGN',+ Bhd: 'BHD',+ Bif: 'BIF',+ Bmd: 'BMD',+ Bnd: 'BND',+ Bob: 'BOB',+ Brl: 'BRL',+ Bsd: 'BSD',+ Btc: 'BTC',+ Btn: 'BTN',+ Bwp: 'BWP',+ Byn: 'BYN',+ Bzd: 'BZD',+ Cad: 'CAD',+ Cdf: 'CDF',+ Chf: 'CHF',+ Clp: 'CLP',+ Cny: 'CNY',+ Cop: 'COP',+ Crc: 'CRC',+ Cve: 'CVE',+ Czk: 'CZK',+ Djf: 'DJF',+ Dkk: 'DKK',+ Dop: 'DOP',+ Dzd: 'DZD',+ Egp: 'EGP',+ Ern: 'ERN',+ Etb: 'ETB',+ Eur: 'EUR',+ Fjd: 'FJD',+ Gbp: 'GBP',+ Gel: 'GEL',+ Ghs: 'GHS',+ Gip: 'GIP',+ Gmd: 'GMD',+ Gnf: 'GNF',+ Gtq: 'GTQ',+ Gyd: 'GYD',+ Hkd: 'HKD',+ Hnl: 'HNL',+ Hrk: 'HRK',+ Htg: 'HTG',+ Huf: 'HUF',+ Idr: 'IDR',+ Ils: 'ILS',+ Inr: 'INR',+ Iqd: 'IQD',+ Irr: 'IRR',+ Isk: 'ISK',+ Jmd: 'JMD',+ Jod: 'JOD',+ Jpy: 'JPY',+ Kes: 'KES',+ Kgs: 'KGS',+ Khr: 'KHR',+ Kmf: 'KMF',+ Krw: 'KRW',+ Kwd: 'KWD',+ Kyd: 'KYD',+ Kzt: 'KZT',+ Lak: 'LAK',+ Lbp: 'LBP',+ Lkr: 'LKR',+ Lrd: 'LRD',+ Ltl: 'LTL',+ Lvl: 'LVL',+ Lsl: 'LSL',+ Lyd: 'LYD',+ Mad: 'MAD',+ Mdl: 'MDL',+ Mga: 'MGA',+ Mkd: 'MKD',+ Mmk: 'MMK',+ Mnt: 'MNT',+ Mop: 'MOP',+ Mru: 'MRU',+ Mtl: 'MTL',+ Mur: 'MUR',+ Mvr: 'MVR',+ Mwk: 'MWK',+ Mxn: 'MXN',+ Myr: 'MYR',+ Mzn: 'MZN',+ Nad: 'NAD',+ Ngn: 'NGN',+ Nio: 'NIO',+ Nok: 'NOK',+ Npr: 'NPR',+ Nzd: 'NZD',+ Omr: 'OMR',+ Pab: 'PAB',+ Pen: 'PEN',+ Pgk: 'PGK',+ Php: 'PHP',+ Pkr: 'PKR',+ Pln: 'PLN',+ Pyg: 'PYG',+ Qar: 'QAR',+ Ron: 'RON',+ Rsd: 'RSD',+ Rub: 'RUB',+ Rwf: 'RWF',+ Sar: 'SAR',+ Sbd: 'SBD',+ Scr: 'SCR',+ Sdg: 'SDG',+ Sek: 'SEK',+ Sgd: 'SGD',+ Srd: 'SRD',+ Ssp: 'SSP',+ Stn: 'STN',+ Syp: 'SYP',+ Szl: 'SZL',+ Thb: 'THB',+ Tjs: 'TJS',+ Tmt: 'TMT',+ Tnd: 'TND',+ Top: 'TOP',+ Try: 'TRY',+ Ttd: 'TTD',+ Twd: 'TWD',+ Tzs: 'TZS',+ Uah: 'UAH',+ Ugx: 'UGX',+ Usd: 'USD',+ Uyu: 'UYU',+ Uzs: 'UZS',+ Ves: 'VES',+ Vnd: 'VND',+ Vuv: 'VUV',+ Wst: 'WST',+ Xaf: 'XAF',+ Xcd: 'XCD',+ Xof: 'XOF',+ Xpf: 'XPF',+ Yer: 'YER',+ Zar: 'ZAR',+ Zmw: 'ZMW',+} as const++export interface RevenueCurrencyPropertyConfigApi {+ property?: string | null+ static?: CurrencyCodeApi | null+}++export type EventsNodeApiResponse = { [key: string]: unknown } | null++export interface EventsNodeApi {+ custom_name?: string | null+ /** The event or `null` for all events. */+ event?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ kind?: 'EventsNode'+ limit?: number | null+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Columns to order by */+ orderBy?: string[] | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: EventsNodeApiResponse+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type ActionsNodeApiResponse = { [key: string]: unknown } | null++export interface ActionsNodeApi {+ custom_name?: string | null+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ id: number+ kind?: 'ActionsNode'+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: ActionsNodeApiResponse+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type ExperimentDataWarehouseNodeApiResponse = { [key: string]: unknown } | null++export interface ExperimentDataWarehouseNodeApi {+ custom_name?: string | null+ data_warehouse_join_key: string+ events_join_key: string+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */+ fixedProperties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ kind?: 'ExperimentDataWarehouseNode'+ math?:+ | BaseMathTypeApi+ | FunnelMathTypeApi+ | PropertyMathTypeApi+ | CountPerActorMathTypeApi+ | GroupMathTypeApi+ | ExperimentMetricMathTypeApi+ | CalendarHeatmapMathTypeApi+ | 'hogql'+ | null+ math_group_type_index?: MathGroupTypeIndexApi | null+ math_hogql?: string | null+ math_multiplier?: number | null+ math_property?: string | null+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null+ math_property_type?: string | null+ name?: string | null+ optionalInFunnel?: boolean | null+ /** Properties configurable in the interface */+ properties?:+ | (+ | EventPropertyFilterApi+ | PersonPropertyFilterApi+ | PersonMetadataPropertyFilterApi+ | ElementPropertyFilterApi+ | EventMetadataPropertyFilterApi+ | SessionPropertyFilterApi+ | CohortPropertyFilterApi+ | RecordingPropertyFilterApi+ | LogEntryPropertyFilterApi+ | GroupPropertyFilterApi+ | FeaturePropertyFilterApi+ | FlagPropertyFilterApi+ | HogQLPropertyFilterApi+ | EmptyPropertyFilterApi+ | DataWarehousePropertyFilterApi+ | DataWarehousePersonPropertyFilterApi+ | ErrorTrackingIssueFilterApi+ | LogPropertyFilterApi+ | MetricPropertyFilterApi+ | SpanPropertyFilterApi+ | RevenueAnalyticsPropertyFilterApi+ | AccountCustomPropertyFilterApi+ | WorkflowVariablePropertyFilterApi+ | BehavioralPropertyFilterApi+ )[]+ | null+ response?: ExperimentDataWarehouseNodeApiResponse+ table_name: string+ timestamp_field: string+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type ExperimentMeanMetricApiResponse = { [key: string]: unknown } | null++export interface ExperimentMeanMetricApi {+ breakdownFilter?: BreakdownFilterApi | null+ conversion_window?: number | null+ conversion_window_unit?: FunnelConversionWindowTimeUnitApi | null+ fingerprint?: string | null+ goal?: ExperimentMetricGoalApi | null+ ignore_zeros?: boolean | null+ isSharedMetric?: boolean | null+ kind?: 'ExperimentMetric'+ /** Winsorization lower percentile bound, as a fraction in [0, 1] (e.g. 0.01 for the 1st percentile). */+ lower_bound_percentile?: number | null+ metric_type: ExperimentMeanMetricApiMetricType+ name?: string | null+ response?: ExperimentMeanMetricApiResponse+ sharedMetricId?: number | null+ source: EventsNodeApi | ActionsNodeApi | ExperimentDataWarehouseNodeApi+ /** When set, reports the percentage of users whose per-user summed/counted value reaches or exceeds this threshold. Only meaningful for sum/count math types. */+ threshold?: number | null+ /** Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). */+ upper_bound_percentile?: number | null+ uuid?: string | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type BreakdownAttributionTypeApi = (typeof BreakdownAttributionTypeApi)[keyof typeof BreakdownAttributionTypeApi]++export const BreakdownAttributionTypeApi = {+ FirstTouch: 'first_touch',+ LastTouch: 'last_touch',+ AllEvents: 'all_events',+ Step: 'step',+} as const++export type StepOrderValueApi = (typeof StepOrderValueApi)[keyof typeof StepOrderValueApi]++export const StepOrderValueApi = {+ Strict: 'strict',+ Unordered: 'unordered',+ Ordered: 'ordered',+} as const++export type ExperimentFunnelMetricApiMetricType =+ (typeof ExperimentFunnelMetricApiMetricType)[keyof typeof ExperimentFunnelMetricApiMetricType]++export const ExperimentFunnelMetricApiMetricType = {+ Funnel: 'funnel',+} as const++export type ExperimentFunnelMetricApiResponse = { [key: string]: unknown } | null++export interface ExperimentFunnelMetricApi {+ /** How to attribute the breakdown value across funnel steps. */+ breakdownAttributionType?: BreakdownAttributionTypeApi | null+ /** When breakdownAttributionType is `step`, the 0-indexed step to attribute from. */+ breakdownAttributionValue?: number | null+ breakdownFilter?: BreakdownFilterApi | null+ conversion_window?: number | null+ conversion_window_unit?: FunnelConversionWindowTimeUnitApi | null+ fingerprint?: string | null+ funnel_order_type?: StepOrderValueApi | null+ goal?: ExperimentMetricGoalApi | null+ isSharedMetric?: boolean | null+ kind?: 'ExperimentMetric'+ metric_type: ExperimentFunnelMetricApiMetricType+ name?: string | null+ response?: ExperimentFunnelMetricApiResponse+ series: (EventsNodeApi | ActionsNodeApi | ExperimentDataWarehouseNodeApi)[]+ sharedMetricId?: number | null+ uuid?: string | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export interface ExperimentMetricOutlierHandlingApi {+ ignore_zeros?: boolean | null+ /** Winsorization lower percentile bound, as a fraction in [0, 1] (e.g. 0.01 for the 1st percentile). */+ lower_bound_percentile?: number | null+ /** Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). */+ upper_bound_percentile?: number | null+}++export type ExperimentRatioMetricApiMetricType =+ (typeof ExperimentRatioMetricApiMetricType)[keyof typeof ExperimentRatioMetricApiMetricType]++export const ExperimentRatioMetricApiMetricType = {+ Ratio: 'ratio',+} as const++export type ExperimentRatioMetricApiResponse = { [key: string]: unknown } | null++export interface ExperimentRatioMetricApi {+ breakdownFilter?: BreakdownFilterApi | null+ conversion_window?: number | null+ conversion_window_unit?: FunnelConversionWindowTimeUnitApi | null+ denominator: EventsNodeApi | ActionsNodeApi | ExperimentDataWarehouseNodeApi+ denominator_outlier_handling?: ExperimentMetricOutlierHandlingApi | null+ fingerprint?: string | null+ goal?: ExperimentMetricGoalApi | null+ isSharedMetric?: boolean | null+ kind?: 'ExperimentMetric'+ metric_type: ExperimentRatioMetricApiMetricType+ name?: string | null+ numerator: EventsNodeApi | ActionsNodeApi | ExperimentDataWarehouseNodeApi+ numerator_outlier_handling?: ExperimentMetricOutlierHandlingApi | null+ response?: ExperimentRatioMetricApiResponse+ sharedMetricId?: number | null+ uuid?: string | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type ExperimentRetentionMetricApiMetricType =+ (typeof ExperimentRetentionMetricApiMetricType)[keyof typeof ExperimentRetentionMetricApiMetricType]++export const ExperimentRetentionMetricApiMetricType = {+ Retention: 'retention',+} as const++export type ExperimentExposureNodeApiResponse = { [key: string]: unknown } | null++export interface ExperimentExposureNodeApi {+ kind?: 'ExperimentExposureNode'+ response?: ExperimentExposureNodeApiResponse+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type StartHandlingApi = (typeof StartHandlingApi)[keyof typeof StartHandlingApi]++export const StartHandlingApi = {+ FirstSeen: 'first_seen',+ LastSeen: 'last_seen',+} as const++export type ExperimentRetentionMetricApiResponse = { [key: string]: unknown } | null++export interface ExperimentRetentionMetricApi {+ breakdownFilter?: BreakdownFilterApi | null+ completion_event: EventsNodeApi | ActionsNodeApi | ExperimentDataWarehouseNodeApi+ conversion_window?: number | null+ conversion_window_unit?: FunnelConversionWindowTimeUnitApi | null+ fingerprint?: string | null+ goal?: ExperimentMetricGoalApi | null+ isSharedMetric?: boolean | null+ kind?: 'ExperimentMetric'+ metric_type: ExperimentRetentionMetricApiMetricType+ name?: string | null+ response?: ExperimentRetentionMetricApiResponse+ retention_window_end: number+ retention_window_start: number+ retention_window_unit: FunnelConversionWindowTimeUnitApi+ sharedMetricId?: number | null+ start_event: EventsNodeApi | ActionsNodeApi | ExperimentDataWarehouseNodeApi | ExperimentExposureNodeApi+ start_handling: StartHandlingApi+ uuid?: string | null+ /** version of the node, used for schema migrations */+ version?: number | null+}++export type ExperimentMetricApi =+ | ExperimentMeanMetricApi+ | ExperimentFunnelMetricApi+ | ExperimentRatioMetricApi+ | ExperimentRetentionMetricApi++/**+ * A shared metric's link to one experiment, as the experiment API returns it.+ */+export interface ExperimentToSavedMetricApi {+ readonly id: number+ experiment: number+ saved_metric: number+ metadata?: unknown+ readonly created_at: string+ readonly query: unknown+ readonly name: string+ /** The metric this experiment calculates for this shared metric: `query` with the per-experiment overrides from `metadata` applied (breakdowns, breakdown_limit, and funnel breakdown attribution). Results, fingerprints and queries for this metric use this definition, not `query`. Null when `query` is not an ExperimentMetric, such as a legacy shared metric (kind ExperimentTrendsQuery or ExperimentFunnelsQuery), which takes no overrides. */+ readonly effective_query: ExperimentMetricApi | null+}++export type Kind2Api = (typeof Kind2Api)[keyof typeof Kind2Api]++export const Kind2Api = {+ ExperimentEventExposureConfig: 'ExperimentEventExposureConfig',+ ActionsNode: 'ActionsNode',+} as const+export interface ExperimentApiExposureConfigApi {/** Custom exposure event name. Required when kind is 'ExperimentEventExposureConfig'. */event?: string | null@@ -1334,30 +2101,6 @@ export const Kind1Api = {ActionsNode: 'ActionsNode',} as const-export type ExperimentMetricMathTypeApi = (typeof ExperimentMetricMathTypeApi)[keyof typeof ExperimentMetricMathTypeApi]--export const ExperimentMetricMathTypeApi = {- Total: 'total',- Sum: 'sum',- UniqueSession: 'unique_session',- Min: 'min',- Max: 'max',- Avg: 'avg',- Dau: 'dau',- UniqueGroup: 'unique_group',- Hogql: 'hogql',-} as const--export type MathGroupTypeIndexApi = (typeof MathGroupTypeIndexApi)[keyof typeof MathGroupTypeIndexApi]--export const MathGroupTypeIndexApi = {- Number0: 0,- Number1: 1,- Number2: 2,- Number3: 3,- Number4: 4,-} as const-export interface ExperimentApiEventSourceApi {/** Event name, e.g. '$pageview'. Required for EventsNode. */event?: string | null@@ -1376,41 +2119,6 @@ export interface ExperimentApiEventSourceApi {properties?: EventPropertyFilterApi[] | null}-export type FunnelConversionWindowTimeUnitApi =- (typeof FunnelConversionWindowTimeUnitApi)[keyof typeof FunnelConversionWindowTimeUnitApi]--export const FunnelConversionWindowTimeUnitApi = {- Second: 'second',- Minute: 'minute',- Hour: 'hour',- Day: 'day',- Week: 'week',- Month: 'month',-} as const--export interface ExperimentMetricOutlierHandlingApi {- ignore_zeros?: boolean | null- /** Winsorization lower percentile bound, as a fraction in [0, 1] (e.g. 0.01 for the 1st percentile). */- lower_bound_percentile?: number | null- /** Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). */- upper_bound_percentile?: number | null-}--export type StepOrderValueApi = (typeof StepOrderValueApi)[keyof typeof StepOrderValueApi]--export const StepOrderValueApi = {- Strict: 'strict',- Unordered: 'unordered',- Ordered: 'ordered',-} as const--export type ExperimentMetricGoalApi = (typeof ExperimentMetricGoalApi)[keyof typeof ExperimentMetricGoalApi]--export const ExperimentMetricGoalApi = {- Increase: 'increase',- Decrease: 'decrease',-} as const-export type ExperimentMetricTypeApi = (typeof ExperimentMetricTypeApi)[keyof typeof ExperimentMetricTypeApi]export const ExperimentMetricTypeApi = {@@ -1447,13 +2155,6 @@ export interface ExperimentApiRetentionStartApi {properties?: EventPropertyFilterApi[] | null}-export type StartHandlingApi = (typeof StartHandlingApi)[keyof typeof StartHandlingApi]--export const StartHandlingApi = {- FirstSeen: 'first_seen',- LastSeen: 'last_seen',-} as const-export interface ExperimentApiMetricApi {/** For retention metrics: completion event. */completion_event?: ExperimentApiEventSourceApi | nulldiff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 43a017d00878..f8959d5a0abd 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -550,6 +550,9 @@ tools:- experimentId- experiment_idui_app: experiment+ response:+ exclude:+ - saved_metrics.*.effective_queryexperiment-holdouts-create:operation: experiment_holdouts_createenabled: true@@ -1556,7 +1559,13 @@ tools:- excluded_variants- metrics- metrics_secondary- - saved_metrics+ - saved_metrics.*.id+ - saved_metrics.*.experiment+ - saved_metrics.*.saved_metric+ - saved_metrics.*.metadata+ - saved_metrics.*.created_at+ - saved_metrics.*.query+ - saved_metrics.*.name- conclusion- conclusion_comment- tagsdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2b9051fd41fd..98a4eb34c900 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -6807,6 +6807,13 @@ export namespace Schemas {Decrease: 'decrease',} as const;+ export type ExperimentMeanMetricMetricType = typeof ExperimentMeanMetricMetricType[keyof typeof ExperimentMeanMetricMetricType];+++ export const ExperimentMeanMetricMetricType = {+ Mean: 'mean',+ } as const;+export type ExperimentDataWarehouseNodeResponse = { [key: string]: unknown } | null;export interface ExperimentDataWarehouseNode {@@ -6847,7 +6854,7 @@ export namespace Schemas {kind?: 'ExperimentMetric';/** Winsorization lower percentile bound, as a fraction in [0, 1] (e.g. 0.01 for the 1st percentile). */lower_bound_percentile?: number | null;- metric_type?: 'mean';+ metric_type: ExperimentMeanMetricMetricType;name?: string | null;response?: ExperimentMeanMetricResponse;sharedMetricId?: number | null;@@ -6861,6 +6868,13 @@ export namespace Schemas {version?: number | null;}+ export type ExperimentFunnelMetricMetricType = typeof ExperimentFunnelMetricMetricType[keyof typeof ExperimentFunnelMetricMetricType];+++ export const ExperimentFunnelMetricMetricType = {+ Funnel: 'funnel',+ } as const;+export type ExperimentFunnelMetricResponse = { [key: string]: unknown } | null;export interface ExperimentFunnelMetric {@@ -6876,7 +6890,7 @@ export namespace Schemas {goal?: ExperimentMetricGoal | null;isSharedMetric?: boolean | null;kind?: 'ExperimentMetric';- metric_type?: 'funnel';+ metric_type: ExperimentFunnelMetricMetricType;name?: string | null;response?: ExperimentFunnelMetricResponse;series: (EventsNode | ActionsNode | ExperimentDataWarehouseNode)[];@@ -6894,6 +6908,13 @@ export namespace Schemas {upper_bound_percentile?: number | null;}+ export type ExperimentRatioMetricMetricType = typeof ExperimentRatioMetricMetricType[keyof typeof ExperimentRatioMetricMetricType];+++ export const ExperimentRatioMetricMetricType = {+ Ratio: 'ratio',+ } as const;+export type ExperimentRatioMetricResponse = { [key: string]: unknown } | null;export interface ExperimentRatioMetric {@@ -6906,7 +6927,7 @@ export namespace Schemas {goal?: ExperimentMetricGoal | null;isSharedMetric?: boolean | null;kind?: 'ExperimentMetric';- metric_type?: 'ratio';+ metric_type: ExperimentRatioMetricMetricType;name?: string | null;numerator: EventsNode | ActionsNode | ExperimentDataWarehouseNode;numerator_outlier_handling?: ExperimentMetricOutlierHandling | null;@@ -6917,6 +6938,13 @@ export namespace Schemas {version?: number | null;}+ export type ExperimentRetentionMetricMetricType = typeof ExperimentRetentionMetricMetricType[keyof typeof ExperimentRetentionMetricMetricType];+++ export const ExperimentRetentionMetricMetricType = {+ Retention: 'retention',+ } as const;+export type ExperimentExposureNodeResponse = { [key: string]: unknown } | null;export interface ExperimentExposureNode {@@ -6945,7 +6973,7 @@ export namespace Schemas {goal?: ExperimentMetricGoal | null;isSharedMetric?: boolean | null;kind?: 'ExperimentMetric';- metric_type?: 'retention';+ metric_type: ExperimentRetentionMetricMetricType;name?: string | null;response?: ExperimentRetentionMetricResponse;retention_window_end: number;@@ -42799,6 +42827,11 @@ export namespace Schemas {recommended_sample_size?: number | null;}+ export type ExperimentMetric = ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric;++ /**+ * A shared metric's link to one experiment, as the experiment API returns it.+ */export interface ExperimentToSavedMetric {readonly id: number;experiment: number;@@ -42807,6 +42840,8 @@ export namespace Schemas {readonly created_at: string;readonly query: unknown;readonly name: string;+ /** The metric this experiment calculates for this shared metric: `query` with the per-experiment overrides from `metadata` applied (breakdowns, breakdown_limit, and funnel breakdown attribution). Results, fingerprints and queries for this metric use this definition, not `query`. Null when `query` is not an ExperimentMetric, such as a legacy shared metric (kind ExperimentTrendsQuery or ExperimentFunnelsQuery), which takes no overrides. */+ readonly effective_query: ExperimentMetric | null;}/**diff --git a/services/mcp/src/schema/experiments.ts b/services/mcp/src/schema/experiments.tsindex 1c4e28e36679..0da3704422ef 100644--- a/services/mcp/src/schema/experiments.ts+++ b/services/mcp/src/schema/experiments.ts@@ -92,6 +92,7 @@ export const SavedMetricAttachmentSchema = z.looseObject({}).nullish(),query: z.unknown(),+ effective_query: z.unknown().optional(),})export type SavedMetricAttachment = z.infer<typeof SavedMetricAttachmentSchema>@@ -244,13 +245,21 @@ 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.+ * The effective definition of a shared metric on one experiment, so that the tool queries the metric+ * the experiment page shows. The API applies the per-experiment overrides from the link metadata to+ * the saved query and serves the result as `effective_query`. The field is null for a legacy shared+ * metric, which takes no overrides.+ *+ * A PostHog server that predates the field, such as an older self-hosted instance, omits it. For that+ * server this function applies the overrides itself. It copies the rules of+ * `resolve_saved_metric_definition` in products/experiments/backend/metric_resolution.py as those+ * servers run them. A server that serves `effective_query` never reaches that code, so a later change+ * to the backend rules does not need a change here.*/-export function resolveSharedMetric({ query, metadata }: SavedMetricAttachment): unknown {+function sharedMetricDefinition({ query, metadata, effective_query }: SavedMetricAttachment): unknown {+ if (effective_query !== undefined) {+ return effective_query ?? query+ }if (query === null || typeof query !== 'object' || Array.isArray(query)) {return query}@@ -294,7 +303,7 @@ export function buildMetricEntries(experiment: Experiment, slot: 'primary' | 'seconst entries: ResolvedMetricEntry[] = [...inline.map((metric) => ({ metric: metric as unknown, summary: toMetricSummary(metric, 'inline') })),...shared.map((sm) => ({- metric: resolveSharedMetric(sm),+ metric: sharedMetricDefinition(sm),summary: toMetricSummary(sm.query, 'shared', {id: typeof sm.saved_metric === 'number' ? sm.saved_metric : null,name: typeof sm.name === 'string' ? sm.name : null,@@ -413,7 +422,10 @@ export function transformExperimentResults(input: {feature_flag_key: experiment.feature_flag_key,metrics: experiment.metrics,metrics_secondary: experiment.metrics_secondary,- saved_metrics: experiment.saved_metrics,+ // `effective_query` repeats `query` with the `metadata` overrides applied, so it only spends context.+ saved_metrics:+ experiment.saved_metrics &&+ experiment.saved_metrics.map(({ effective_query: _effective, ...link }) => link),start_date: experiment.start_date,end_date: experiment.end_date,status: (experiment.start_date ? (experiment.end_date ? 'completed' : 'running') : 'draft') asdiff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex 7111b6398fec..a410acd65414 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -551,7 +551,8 @@ const experimentGet = (): ToolBase<ReturnType<typeof ExperimentGetSchema>, WithPmethod: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/`,})- return await withPostHogUrl(context, result, `/experiments/${result.id}`)+ const filtered = omitResponseFields(result, ['saved_metrics.*.effective_query']) as typeof result+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)},})@@ -1541,7 +1542,13 @@ const experimentUpdate = (): ToolBase<ReturnType<typeof ExperimentUpdateSchema>,'excluded_variants','metrics','metrics_secondary',- 'saved_metrics',+ 'saved_metrics.*.id',+ 'saved_metrics.*.experiment',+ 'saved_metrics.*.saved_metric',+ 'saved_metrics.*.metadata',+ 'saved_metrics.*.created_at',+ 'saved_metrics.*.query',+ 'saved_metrics.*.name','conclusion','conclusion_comment','tags',diff --git a/services/mcp/tests/unit/experiments-results-transform.test.ts b/services/mcp/tests/unit/experiments-results-transform.test.tsindex eeb235ccfd0c..a95fc24a033d 100644--- a/services/mcp/tests/unit/experiments-results-transform.test.ts+++ b/services/mcp/tests/unit/experiments-results-transform.test.ts@@ -112,6 +112,7 @@ describe('transformExperimentResults', () => {})it('treats inline and shared metrics as one ordered surface and tags the source on each', () => {+ const sharedQuery = { uuid: 'shared-1', name: 'Shared query', metric_type: 'funnel', goal: 'increase' }const experiment = makeExperiment({metrics: [],metrics_secondary: [{ uuid: 'inline-1', name: 'Inline secondary', metric_type: 'mean' }],@@ -120,7 +121,8 @@ describe('transformExperimentResults', () => {saved_metric: 42,name: 'Shared secondary',metadata: { type: 'secondary' },- query: { uuid: 'shared-1', name: 'Shared query', metric_type: 'funnel', goal: 'increase' },+ query: sharedQuery,+ effective_query: sharedQuery,},],secondary_metrics_ordered_uuids: ['inline-1', 'shared-1'],@@ -154,6 +156,10 @@ describe('transformExperimentResults', () => {saved_metric_name: 'Shared secondary',}))+ // The link keeps its query and metadata, without the effective_query that repeats them.+ expect(result.experiment.saved_metrics).toEqual([+ { saved_metric: 42, name: 'Shared secondary', metadata: { type: 'secondary' }, query: sharedQuery },+ ])})it("uses the saved metric's UI label as `name` on shared rows (not the inner query.name)", () => {@@ -176,50 +182,55 @@ describe('transformExperimentResults', () => {expect(entry?.summary.saved_metric_name).toBe('Activation funnel (revenue impact)')})+ const savedFunnel = {+ uuid: 'shared-funnel',+ metric_type: 'funnel',+ breakdownAttributionType: 'step',+ breakdownAttributionValue: 2,+ breakdownFilter: { breakdown_limit: 5, breakdowns: [{ property: '$os', type: 'event' }] },+ }+ const linkWithBreakdowns = {+ type: 'primary',+ breakdowns: [{ property: '$browser', type: 'event' }],+ breakdown_limit: 20,+ breakdownAttributionType: 'last_touch',+ }+ const effectiveFunnel = {+ uuid: 'shared-funnel',+ metric_type: 'funnel',+ breakdownAttributionType: 'last_touch',+ breakdownFilter: { breakdown_limit: 20, breakdowns: [{ property: '$browser', type: 'event' }] },+ }+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' }] },+ 'the effective query the API resolved',+ { metadata: linkWithBreakdowns, effective_query: { ...effectiveFunnel, fingerprint: 'served' } },+ { ...effectiveFunnel, fingerprint: 'served' },+ ],+ [+ 'the saved query of a legacy shared metric',+ { metadata: linkWithBreakdowns, effective_query: null },+ savedFunnel,+ ],+ [+ 'the link breakdowns, limit and attribution when the API predates effective_query',+ { metadata: linkWithBreakdowns },+ effectiveFunnel,],[- '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: [] },+ 'no link limit or attribution without link breakdowns when the API predates effective_query',+ { metadata: { type: 'primary', breakdown_limit: 20, breakdownAttributionType: 'last_touch' } },+ { ...savedFunnel, breakdownFilter: { breakdown_limit: 5, breakdowns: [] } },],- ])('queries a shared metric as the experiment page does: %s', (_name, metadata, attribution, breakdownFilter) => {+ ])('queries a shared metric with %s', (_name, link, expectedMetric) => {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' }] },- },- },- ],+ saved_metrics: [{ saved_metric: 1, name: 'Shared funnel', query: savedFunnel, ...link }],})const [entry] = buildMetricEntries(experiment, 'primary')- expect(entry?.metric).toEqual({- uuid: 'shared-funnel',- metric_type: 'funnel',- ...attribution,- breakdownFilter,- })+ expect(entry?.metric).toEqual(expectedMetric)})it('orders result rows by *_metrics_ordered_uuids (the canonical UI ordering)', () => {