: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
fix(experiments/mcp): Improve experiment-results-get mcp to be self-describing (#59351)
Marcel Poelker7b8bb74d465f
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex dbf835c1cd70..93d4988a6842 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1901,10 +1901,10 @@}},"experiment-results-get": {- "description": "Get comprehensive experiment results including all metrics data (primary and secondary) and exposure data. This tool fetches the experiment details and executes the necessary queries to get complete experiment results. Only works with new experiments (not legacy experiments).",+ "description": "Get experiment metric results and exposure data in one call. Each row in `metrics.primary.results` and `metrics.secondary.results` carries a self-describing `metric` summary: `uuid`, `name` (the label users see in the experiment UI), `metric_type`, `goal`, and `source` — `inline` for metrics defined on the experiment, `shared` for metrics attached via a saved metric. For `shared` rows, `saved_metric_id` and `saved_metric_name` identify the underlying saved metric; both are `null` for `inline` rows. Rows are ordered to match the experiment UI (`primary_metrics_ordered_uuids` / `secondary_metrics_ordered_uuids`). A row whose underlying metric query failed is kept with `data: null` so positions stay aligned with the ordered UUIDs — check `data === null` to detect failures. The raw source surfaces (`experiment.metrics`, `experiment.metrics_secondary`, `experiment.saved_metrics`) are preserved on the response for callers who want to audit them, but you do not need to reconcile them yourself — the result rows already merge inline and shared. Only works with new experiments (not legacy `ExperimentTrendsQuery` / `ExperimentFunnelsQuery`).","category": "Experiments","feature": "experiments",- "summary": "Get comprehensive experiment results including metrics and exposure data.",+ "summary": "Get experiment metric and exposure results with self-describing per-metric metadata.","title": "Get experiment results","required_scopes": ["experiment:read"],"new_mcp": true,diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex cdd914271536..28a9ea71e8a1 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -17,10 +17,10 @@}},"experiment-results-get": {- "description": "Get comprehensive experiment results including all metrics data (primary and secondary) and exposure data. This tool fetches the experiment details and executes the necessary queries to get complete experiment results. Only works with new experiments (not legacy experiments).",+ "description": "Get experiment metric results and exposure data in one call. Each row in `metrics.primary.results` and `metrics.secondary.results` carries a self-describing `metric` summary: `uuid`, `name` (the label users see in the experiment UI), `metric_type`, `goal`, and `source` — `inline` for metrics defined on the experiment, `shared` for metrics attached via a saved metric. For `shared` rows, `saved_metric_id` and `saved_metric_name` identify the underlying saved metric; both are `null` for `inline` rows. Rows are ordered to match the experiment UI (`primary_metrics_ordered_uuids` / `secondary_metrics_ordered_uuids`). A row whose underlying metric query failed is kept with `data: null` so positions stay aligned with the ordered UUIDs — check `data === null` to detect failures. The raw source surfaces (`experiment.metrics`, `experiment.metrics_secondary`, `experiment.saved_metrics`) are preserved on the response for callers who want to audit them, but you do not need to reconcile them yourself — the result rows already merge inline and shared. Only works with new experiments (not legacy `ExperimentTrendsQuery` / `ExperimentFunnelsQuery`).","category": "Experiments","feature": "experiments",- "summary": "Get comprehensive experiment results including metrics and exposure data.",+ "summary": "Get experiment metric and exposure results with self-describing per-metric metadata.","title": "Get experiment results","required_scopes": ["experiment:read"],"new_mcp": true,diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.tsindex 70df594b5151..a098de32af6e 100644--- a/services/mcp/src/api/client.ts+++ b/services/mcp/src/api/client.ts@@ -11,8 +11,13 @@ import type {ApiRedactedPersonalApiKey,ApiUser,} from '@/schema/api'-import type { Experiment, ExperimentExposureQuery, ExperimentExposureQueryResponse } from '@/schema/experiments'-import { ExperimentExposureQuerySchema } from '@/schema/experiments'+import type {+ Experiment,+ ExperimentExposureQuery,+ ExperimentExposureQueryResponse,+ ResolvedMetricEntry,+} from '@/schema/experiments'+import { buildMetricEntries, ExperimentExposureQuerySchema } from '@/schema/experiments'import { isShortId } from '@/tools/insights/utils'import type { Schemas } from './generated.js'@@ -721,6 +726,8 @@ export class ApiClient {}): Promise<Result<{experiment: Experiment+ primaryMetricEntries: ResolvedMetricEntry[]+ secondaryMetricEntries: ResolvedMetricEntry[]primaryMetricsResults: any[]secondaryMetricsResults: any[]exposures: ExperimentExposureQueryResponse@@ -766,20 +773,15 @@ export class ApiClient {const { exposures } = experimentExposure.data- // Prepare metrics queries- const sharedPrimaryMetrics = (experiment.saved_metrics || [])- .filter(({ metadata }: any) => metadata.type === 'primary')- .map(({ query }: any) => query)- const allPrimaryMetrics = [...(experiment.metrics || []), ...sharedPrimaryMetrics]-- const sharedSecondaryMetrics = (experiment.saved_metrics || [])- .filter(({ metadata }: any) => metadata.type === 'secondary')- .map(({ query }: any) => query)- const allSecondaryMetrics = [...(experiment.metrics_secondary || []), ...sharedSecondaryMetrics]+ // Build the per-position metric entries. Each entry knows whether the metric+ // was defined inline on the experiment or attached via a shared saved metric, so+ // the result row can be self-describing to MCP callers.+ const primaryMetricEntries = buildMetricEntries(experiment, 'primary')+ const secondaryMetricEntries = buildMetricEntries(experiment, 'secondary')// Execute queries for primary metricsconst primaryResults = await Promise.all(- allPrimaryMetrics.map(async (metric) => {+ primaryMetricEntries.map(async ({ metric }) => {try {const queryBody = {kind: 'ExperimentQuery',@@ -809,7 +811,7 @@ export class ApiClient {// Execute queries for secondary metricsconst secondaryResults = await Promise.all(- allSecondaryMetrics.map(async (metric) => {+ secondaryMetricEntries.map(async ({ metric }) => {try {const queryBody = {kind: 'ExperimentQuery',@@ -841,6 +843,8 @@ export class ApiClient {success: true,data: {experiment,+ primaryMetricEntries,+ secondaryMetricEntries,primaryMetricsResults: primaryResults,secondaryMetricsResults: secondaryResults,exposures,diff --git a/services/mcp/src/schema/experiments.ts b/services/mcp/src/schema/experiments.tsindex 342e29a0d02e..feeec95bfd79 100644--- a/services/mcp/src/schema/experiments.ts+++ b/services/mcp/src/schema/experiments.ts@@ -27,6 +27,28 @@ const ExperimentExposureCriteriaSchema = z.object({multiple_variant_handling: z.enum(['exclude', 'first_seen']).optional(),})+/**+ * One entry of `experiment.saved_metrics` — a junction row attaching a shared+ * saved metric to an experiment. Mirrors `ExperimentToSavedMetricSerializer` on+ * the backend. Kept loose (looseObject so extra fields survive, nullish on+ * every field) so a malformed row doesn't fail parsing of the whole experiment;+ * `buildMetricEntries` does the strict filtering. Tightening this catches+ * backend field renames at the type boundary instead of silently nulling out+ * shared-row fields.+ */+export const SavedMetricAttachmentSchema = z.looseObject({+ saved_metric: z.number().nullish(),+ name: z.string().nullish(),+ metadata: z+ .looseObject({+ type: z.string().nullish(),+ })+ .nullish(),+ query: z.unknown(),+})++export type SavedMetricAttachment = z.infer<typeof SavedMetricAttachmentSchema>+/*** Hand-written Experiment schema used by the results tool's API client methods.* The codegen tools use Schemas.Experiment from the generated OpenAPI types instead.@@ -42,7 +64,7 @@ export const ExperimentSchema = z.object({exposure_criteria: ExperimentExposureCriteriaSchema.nullish(),metrics: z.array(z.any()).nullish(),metrics_secondary: z.array(z.any()).nullish(),- saved_metrics: z.array(z.any()).nullish(),+ saved_metrics: z.array(SavedMetricAttachmentSchema).nullish(),saved_metrics_ids: z.array(z.any()).nullable(),parameters: z.object({@@ -110,6 +132,28 @@ export const ExperimentExposureQueryResponseSchema = z.object({export type ExperimentExposureQueryResponse = z.infer<typeof ExperimentExposureQueryResponseSchema>+export type MetricSummary = {+ uuid: string | null+ name: string | null+ metric_type: string | null+ goal: string | null+ source: 'inline' | 'shared'+ saved_metric_id: number | null+ saved_metric_name: string | null+}++export type ResolvedMetricEntry = {+ /** metric is forwarded to the ExperimentQuery body but not read by MCP. */+ metric: unknown+ summary: MetricSummary+}++export type ExperimentMetricResultRow = {+ index: number+ metric: MetricSummary+ data: unknown+}+export interface ExperimentResultsSummary {experiment: {id: number@@ -118,6 +162,7 @@ export interface ExperimentResultsSummary {feature_flag_key: stringmetrics?: unknown[] | null | undefinedmetrics_secondary?: unknown[] | null | undefined+ saved_metrics?: unknown[] | null | undefinedstart_date?: string | null | undefinedend_date?: string | null | undefinedstatus: 'draft' | 'running' | 'completed'@@ -132,22 +177,90 @@ export interface ExperimentResultsSummary {metrics: {primary: {count: number- results: Array<{ index: number; data: unknown }>+ results: ExperimentMetricResultRow[]}secondary: {count: number- results: Array<{ index: number; data: unknown }>+ results: ExperimentMetricResultRow[]}}}+function toMetricSummary(+ metric: unknown,+ source: 'inline' | 'shared',+ saved: { id: number | null; name: string | null } = { id: null, name: null }+): MetricSummary {+ const m = (metric ?? {}) as Record<string, unknown>+ const queryName = typeof m.name === 'string' ? m.name : null+ // For shared rows, the saved metric's label is what users see in the UI, the+ // inner query.name is internal and often unset or drifted+ const name = source === 'shared' ? (saved.name ?? queryName) : queryName+ return {+ uuid: typeof m.uuid === 'string' ? m.uuid : null,+ name,+ metric_type: typeof m.metric_type === 'string' ? m.metric_type : null,+ goal: typeof m.goal === 'string' ? m.goal : null,+ source,+ saved_metric_id: saved.id,+ saved_metric_name: saved.name,+ }+}++/**+ * 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+ * ordering them by `*_metrics_ordered_uuids` so the result rows match what users+ * see in the UI. Each entry tracks its source so each result row can be+ * self-describing.+ */+export function buildMetricEntries(experiment: Experiment, slot: 'primary' | 'secondary'): ResolvedMetricEntry[] {+ const inline = (slot === 'primary' ? experiment.metrics : experiment.metrics_secondary) ?? []+ const shared = (experiment.saved_metrics ?? []).filter((sm) => sm.metadata?.type === slot)+ const entries: ResolvedMetricEntry[] = [+ ...inline.map((metric) => ({ metric: metric as unknown, summary: toMetricSummary(metric, 'inline') })),+ ...shared.map((sm) => ({+ metric: sm.query,+ summary: toMetricSummary(sm.query, 'shared', {+ id: typeof sm.saved_metric === 'number' ? sm.saved_metric : null,+ name: typeof sm.name === 'string' ? sm.name : null,+ }),+ })),+ ]++ // Sort by position in *_metrics_ordered_uuids so result rows match the UI.+ // Entries whose uuid isn't listed (legacy or stale ordering) keep their+ // insertion order at the end thanks to stable Array.prototype.sort.+ const orderedUuids =+ (slot === 'primary' ? experiment.primary_metrics_ordered_uuids : experiment.secondary_metrics_ordered_uuids) ??+ []+ if (orderedUuids.length === 0) {+ return entries+ }+ const positionByUuid = new Map<string, number>()+ orderedUuids.forEach((uuid, i) => positionByUuid.set(uuid, i))+ const fallbackPosition = orderedUuids.length+ const position = (entry: ResolvedMetricEntry): number =>+ entry.summary.uuid ? (positionByUuid.get(entry.summary.uuid) ?? fallbackPosition) : fallbackPosition+ return [...entries].sort((a, b) => position(a) - position(b))+}+export function transformExperimentResults(input: {experiment: Experimentexposures: ExperimentExposureQueryResponse+ primaryMetricEntries: ResolvedMetricEntry[]+ secondaryMetricEntries: ResolvedMetricEntry[]primaryMetricsResults: unknown[]secondaryMetricsResults: unknown[]}): ExperimentResultsSummary {- const { experiment, exposures, primaryMetricsResults, secondaryMetricsResults } = input+ const {+ experiment,+ exposures,+ primaryMetricEntries,+ secondaryMetricEntries,+ primaryMetricsResults,+ secondaryMetricsResults,+ } = inputconst transformedExperiment = {id: experiment.id,@@ -156,6 +269,7 @@ export function transformExperimentResults(input: {feature_flag_key: experiment.feature_flag_key,metrics: experiment.metrics,metrics_secondary: experiment.metrics_secondary,+ saved_metrics: experiment.saved_metrics,start_date: experiment.start_date,end_date: experiment.end_date,status: (experiment.start_date ? (experiment.end_date ? 'completed' : 'running') : 'draft') as@@ -165,28 +279,35 @@ export function transformExperimentResults(input: {variants: experiment.parameters?.feature_flag_variants || [],}+ const buildRows = (+ results: unknown[],+ entries: ResolvedMetricEntry[]+ ): { count: number; results: ExperimentMetricResultRow[] } => {+ if (results.length !== entries.length) {+ // Defensive throwing since the two arrays are paired by index, one result per entry+ throw new Error(+ `experiment-results-get (experiment ${experiment.id}): result/entry length mismatch (${results.length} results, ${entries.length} entries) — this should not happen, please report.`+ )+ }+ // Failed metric queries surface as `data: null` so callers can see "metric N+ // exists and failed" instead of having the row erased and subsequent metric+ // positions shift relative to *_metrics_ordered_uuids.+ return {+ count: results.length,+ results: results.map((result, index) => ({+ index,+ metric: entries[index]!.summary,+ data: result,+ })),+ }+ }+return {experiment: transformedExperiment,exposures,metrics: {- primary: {- count: primaryMetricsResults.length,- results: primaryMetricsResults- .map((result, index) => ({- index,- data: result,- }))- .filter((item) => item.data !== null),- },- secondary: {- count: secondaryMetricsResults.length,- results: secondaryMetricsResults- .map((result, index) => ({- index,- data: result,- }))- .filter((item) => item.data !== null),- },+ primary: buildRows(primaryMetricsResults, primaryMetricEntries),+ secondary: buildRows(secondaryMetricsResults, secondaryMetricEntries),},}}diff --git a/services/mcp/src/tools/experiments/getResults.ts b/services/mcp/src/tools/experiments/getResults.tsindex d63f4d1ecf3d..4139cf7f4db7 100644--- a/services/mcp/src/tools/experiments/getResults.ts+++ b/services/mcp/src/tools/experiments/getResults.ts@@ -32,12 +32,21 @@ export const getResultsHandler: ToolBase<typeof schema, Result>['handler'] = asythrow new Error(`Failed to get experiment results: ${result.error.message}`)}- const { experiment, primaryMetricsResults, secondaryMetricsResults, exposures } = result.data+ const {+ experiment,+ primaryMetricEntries,+ secondaryMetricEntries,+ primaryMetricsResults,+ secondaryMetricsResults,+ exposures,+ } = result.datareturn withPostHogUrl(context,transformExperimentResults({experiment,+ primaryMetricEntries,+ secondaryMetricEntries,primaryMetricsResults,secondaryMetricsResults,exposures,diff --git a/services/mcp/tests/unit/experiments-results-transform.test.ts b/services/mcp/tests/unit/experiments-results-transform.test.tsnew file mode 100644index 000000000000..70e5fbfa9ea5--- /dev/null+++ b/services/mcp/tests/unit/experiments-results-transform.test.ts@@ -0,0 +1,252 @@+/**+ * Regression tests for the experiment-results-get response transformation.+ *+ * Production trace: an agent calling `experiment-results-get` couldn't tell+ * which secondary-metric row belonged to which metric (`data.metric` was null)+ * and concluded `metrics_secondary: []` meant no secondaries, when in fact every+ * secondary was attached as a shared metric.+ *+ * These tests pin the contract:+ * - each result row carries a self-describing `metric` summary+ * - inline and shared metrics are merged into one ordered result stream,+ * with `source` tagged so callers can tell them apart+ * - row order follows `*_metrics_ordered_uuids` (the canonical UI ordering)+ */+import { describe, expect, it } from 'vitest'++import type { Experiment } from '@/schema/experiments'+import { buildMetricEntries, ExperimentSchema, transformExperimentResults } from '@/schema/experiments'++const baseExposures = {+ kind: 'ExperimentExposureQuery' as const,+ timeseries: [],+ total_exposures: {},+ date_range: { date_from: '2026-01-01T00:00:00Z', date_to: null as string | null },+}++// Parse rather than cast so the factory stays honest if ExperimentSchema gains+// required fields — a missing field fails the test instead of silently typing.+const makeExperiment = (overrides: Partial<Experiment>): Experiment =>+ ExperimentSchema.parse({+ id: 1,+ name: 'Test',+ feature_flag_key: 'k',+ archived: false,+ deleted: false,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ saved_metrics_ids: null,+ ...overrides,+ })++describe('transformExperimentResults', () => {+ it('attaches metric metadata to each result row so callers do not need a second experiment-get', () => {+ const experiment = makeExperiment({+ metrics: [{ uuid: 'p-1', name: 'Primary', metric_type: 'mean', goal: 'increase' }],+ metrics_secondary: [{ uuid: 's-1', name: 'Secondary', metric_type: 'funnel', goal: 'decrease' }],+ primary_metrics_ordered_uuids: ['p-1'],+ secondary_metrics_ordered_uuids: ['s-1'],+ })+ const primaryEntries = buildMetricEntries(experiment, 'primary')+ const secondaryEntries = buildMetricEntries(experiment, 'secondary')++ const result = transformExperimentResults({+ experiment,+ exposures: baseExposures,+ primaryMetricEntries: primaryEntries,+ secondaryMetricEntries: secondaryEntries,+ primaryMetricsResults: [{ baseline: { key: 'control' } }],+ secondaryMetricsResults: [{ baseline: { key: 'control' } }],+ })++ expect(result.metrics.primary.results[0]?.metric).toEqual({+ uuid: 'p-1',+ name: 'Primary',+ metric_type: 'mean',+ goal: 'increase',+ source: 'inline',+ saved_metric_id: null,+ saved_metric_name: null,+ })+ expect(result.metrics.secondary.results[0]?.metric).toEqual({+ uuid: 's-1',+ name: 'Secondary',+ metric_type: 'funnel',+ goal: 'decrease',+ source: 'inline',+ saved_metric_id: null,+ saved_metric_name: null,+ })+ })++ it('treats inline and shared metrics as one ordered surface and tags the source on each', () => {+ const experiment = makeExperiment({+ metrics: [],+ metrics_secondary: [{ uuid: 'inline-1', name: 'Inline secondary', metric_type: 'mean' }],+ saved_metrics: [+ {+ saved_metric: 42,+ name: 'Shared secondary',+ metadata: { type: 'secondary' },+ query: { uuid: 'shared-1', name: 'Shared query', metric_type: 'funnel', goal: 'increase' },+ },+ ],+ secondary_metrics_ordered_uuids: ['inline-1', 'shared-1'],+ })+ const entries = buildMetricEntries(experiment, 'secondary')++ const result = transformExperimentResults({+ experiment,+ exposures: baseExposures,+ primaryMetricEntries: [],+ secondaryMetricEntries: entries,+ primaryMetricsResults: [],+ secondaryMetricsResults: [{ baseline: { key: 'control' } }, { baseline: { key: 'control' } }],+ })++ expect(result.metrics.secondary.results).toHaveLength(2)+ expect(result.metrics.secondary.results[0]?.metric).toEqual(+ expect.objectContaining({+ uuid: 'inline-1',+ name: 'Inline secondary',+ source: 'inline',+ saved_metric_id: null,+ saved_metric_name: null,+ })+ )+ expect(result.metrics.secondary.results[1]?.metric).toEqual(+ expect.objectContaining({+ uuid: 'shared-1',+ source: 'shared',+ saved_metric_id: 42,+ saved_metric_name: 'Shared secondary',+ })+ )+ })++ it("uses the saved metric's UI label as `name` on shared rows (not the inner query.name)", () => {+ // The saved metric's `name` is what users see in the experiment UI; the inner+ // `query.name` is internal and may be unset or drifted. An agent asked "which+ // metric is this?" should reach for `summary.name` and get the UI label.+ const experiment = makeExperiment({+ saved_metrics: [+ {+ saved_metric: 1,+ name: 'Activation funnel (revenue impact)',+ metadata: { type: 'primary' },+ query: { uuid: 'shared-x', name: 'inner_funnel_v2', metric_type: 'funnel' },+ },+ ],+ primary_metrics_ordered_uuids: ['shared-x'],+ })+ const [entry] = buildMetricEntries(experiment, 'primary')+ expect(entry?.summary.name).toBe('Activation funnel (revenue impact)')+ expect(entry?.summary.saved_metric_name).toBe('Activation funnel (revenue impact)')+ })++ 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+ // different order than what users see in the experiment UI.+ const experiment = makeExperiment({+ metrics_secondary: [{ uuid: 'inline-a', name: 'Inline A', metric_type: 'mean' }],+ saved_metrics: [+ {+ saved_metric: 7,+ name: 'Shared B',+ metadata: { type: 'secondary' },+ query: { uuid: 'shared-b', name: 'Shared B', metric_type: 'mean' },+ },+ ],+ secondary_metrics_ordered_uuids: ['shared-b', 'inline-a'],+ })+ const entries = buildMetricEntries(experiment, 'secondary')++ expect(entries.map((e) => e.summary.uuid)).toEqual(['shared-b', 'inline-a'])+ })++ it('skips saved metrics with a missing or unexpected metadata.type instead of defaulting them', () => {+ // A defensive guard: a malformed secondary metric must not silently surface in+ // the primary slot. Better to drop than to misclassify.+ const experiment = makeExperiment({+ saved_metrics: [+ { saved_metric: 1, name: 'No type', metadata: {}, query: { uuid: 'no-type', metric_type: 'mean' } },+ {+ saved_metric: 2,+ name: 'Bogus type',+ metadata: { type: 'tertiary' },+ query: { uuid: 'bogus', metric_type: 'mean' },+ },+ {+ saved_metric: 3,+ name: 'Good primary',+ metadata: { type: 'primary' },+ query: { uuid: 'good-primary', metric_type: 'mean' },+ },+ ],+ })+ expect(buildMetricEntries(experiment, 'primary').map((e) => e.summary.uuid)).toEqual(['good-primary'])+ expect(buildMetricEntries(experiment, 'secondary')).toEqual([])+ })++ it('preserves experiment.metrics, metrics_secondary, and saved_metrics on the response so callers can audit the source surfaces', () => {+ const inlineMetric = { uuid: 'p-1', name: 'Primary', metric_type: 'mean' }+ const inlineSecondary = { uuid: 's-1', name: 'Secondary', metric_type: 'mean' }+ const savedMetric = {+ saved_metric: 9,+ name: 'Shared',+ metadata: { type: 'primary' as const },+ query: { uuid: 'shared-9', metric_type: 'mean' },+ }+ const experiment = makeExperiment({+ metrics: [inlineMetric],+ metrics_secondary: [inlineSecondary],+ saved_metrics: [savedMetric],+ primary_metrics_ordered_uuids: ['p-1', 'shared-9'],+ secondary_metrics_ordered_uuids: ['s-1'],+ })++ const result = transformExperimentResults({+ experiment,+ exposures: baseExposures,+ primaryMetricEntries: buildMetricEntries(experiment, 'primary'),+ secondaryMetricEntries: buildMetricEntries(experiment, 'secondary'),+ primaryMetricsResults: [{ baseline: { key: 'control' } }, { baseline: { key: 'control' } }],+ secondaryMetricsResults: [{ baseline: { key: 'control' } }],+ })++ expect(result.experiment.metrics).toEqual([inlineMetric])+ expect(result.experiment.metrics_secondary).toEqual([inlineSecondary])+ expect(result.experiment.saved_metrics).toEqual([savedMetric])+ })++ it('keeps a row with `data: null` when the underlying metric query fails, so positions stay aligned', () => {+ // The API client returns `null` for that row when the per-metric query errors.+ // Erasing the row would shift subsequent positions away from+ // primary_metrics_ordered_uuids, making "the third metric" ambiguous to callers.+ const experiment = makeExperiment({+ metrics: [+ { uuid: 'p-1', name: 'Worked', metric_type: 'mean' },+ { uuid: 'p-2', name: 'Failed', metric_type: 'mean' },+ { uuid: 'p-3', name: 'Worked too', metric_type: 'mean' },+ ],+ primary_metrics_ordered_uuids: ['p-1', 'p-2', 'p-3'],+ })++ const result = transformExperimentResults({+ experiment,+ exposures: baseExposures,+ primaryMetricEntries: buildMetricEntries(experiment, 'primary'),+ secondaryMetricEntries: [],+ primaryMetricsResults: [{ baseline: { key: 'control' } }, null, { baseline: { key: 'control' } }],+ secondaryMetricsResults: [],+ })++ expect(result.metrics.primary.count).toBe(3)+ expect(result.metrics.primary.results).toHaveLength(3)+ expect(result.metrics.primary.results[1]?.data).toBeNull()+ expect(result.metrics.primary.results[1]?.metric.uuid).toBe('p-2')+ expect(result.metrics.primary.results[1]?.metric.name).toBe('Failed')+ expect(result.metrics.primary.results.map((r) => r.metric.uuid)).toEqual(['p-1', 'p-2', 'p-3'])+ })+})