Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(experiments): omit metric data from the list endpoint (#64571)

Anders9515c0ebd7cc
diff --git a/frontend/src/mocks/fixtures/api/experiments/_experiment_draft.json b/frontend/src/mocks/fixtures/api/experiments/_experiment_draft.json
index 7bcd0a7c319b..e3f3ca8d945e 100644
--- a/frontend/src/mocks/fixtures/api/experiments/_experiment_draft.json
+++ b/frontend/src/mocks/fixtures/api/experiments/_experiment_draft.json
@@ -1,5 +1,6 @@
{
"id": 20,
+ "is_legacy": false,
"name": "march-5-draft",
"description": null,
"start_date": null,
diff --git a/frontend/src/mocks/fixtures/api/experiments/experiment_with_funnels_query.json b/frontend/src/mocks/fixtures/api/experiments/experiment_with_funnels_query.json
index b5302f927e20..10958bfc1410 100644
--- a/frontend/src/mocks/fixtures/api/experiments/experiment_with_funnels_query.json
+++ b/frontend/src/mocks/fixtures/api/experiments/experiment_with_funnels_query.json
@@ -1,5 +1,6 @@
{
"id": 13,
+ "is_legacy": true,
"name": "experiment-funnels-query",
"description": null,
"start_date": "2025-05-20T14:16:00Z",
diff --git a/frontend/src/mocks/fixtures/api/experiments/experiment_with_multiple_metrics.json b/frontend/src/mocks/fixtures/api/experiments/experiment_with_multiple_metrics.json
index 2adb3375792d..f96ea7311509 100644
--- a/frontend/src/mocks/fixtures/api/experiments/experiment_with_multiple_metrics.json
+++ b/frontend/src/mocks/fixtures/api/experiments/experiment_with_multiple_metrics.json
@@ -1,5 +1,6 @@
{
"id": 17,
+ "is_legacy": false,
"name": "experiment-multiple-metrics",
"description": null,
"start_date": "2025-06-03T14:48:37.594000Z",
diff --git a/frontend/src/mocks/fixtures/api/experiments/experiment_with_trends_query.json b/frontend/src/mocks/fixtures/api/experiments/experiment_with_trends_query.json
index c81fe290815e..8fc7a587647b 100644
--- a/frontend/src/mocks/fixtures/api/experiments/experiment_with_trends_query.json
+++ b/frontend/src/mocks/fixtures/api/experiments/experiment_with_trends_query.json
@@ -1,5 +1,6 @@
{
"id": 12,
+ "is_legacy": true,
"name": "experiment-trends-query",
"description": null,
"start_date": "2025-05-20T14:01:00Z",
diff --git a/frontend/src/scenes/data-management/events/EventDefinitionExperiments.tsx b/frontend/src/scenes/data-management/events/EventDefinitionExperiments.tsx
index 8d3e9dc78225..3672dab648ba 100644
--- a/frontend/src/scenes/data-management/events/EventDefinitionExperiments.tsx
+++ b/frontend/src/scenes/data-management/events/EventDefinitionExperiments.tsx
@@ -7,7 +7,7 @@ import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { Link } from 'lib/lemon-ui/Link'
import {
EXPERIMENTS_PER_PAGE,
- type ExperimentApi,
+ type ExperimentBasicApi,
eventExperimentsLogic,
} from 'scenes/data-management/events/eventExperimentsLogic'
import { StatusTag } from 'scenes/experiments/ExperimentView/StatusTag'
@@ -21,7 +21,7 @@ export function EventDefinitionExperiments({ definition }: { definition: EventDe
const { page, experiments, experimentsLoading } = useValues(eventExperimentsLogic({ event }))
const { setPage } = useActions(eventExperimentsLogic({ event }))
- const columns: LemonTableColumns<ExperimentApi> = [
+ const columns: LemonTableColumns<ExperimentBasicApi> = [
{
title: 'Name',
key: 'name',
diff --git a/frontend/src/scenes/data-management/events/eventExperimentsLogic.ts b/frontend/src/scenes/data-management/events/eventExperimentsLogic.ts
index c6f21ae12e6f..db207f258a9b 100644
--- a/frontend/src/scenes/data-management/events/eventExperimentsLogic.ts
+++ b/frontend/src/scenes/data-management/events/eventExperimentsLogic.ts
@@ -4,7 +4,10 @@ import { loaders } from 'kea-loaders'
import { teamLogic } from 'scenes/teamLogic'
import { experimentsList } from 'products/experiments/frontend/generated/api'
-import type { ExperimentApi, PaginatedExperimentListApi } from 'products/experiments/frontend/generated/api.schemas'
+import type {
+ ExperimentBasicApi,
+ PaginatedExperimentBasicListApi,
+} from 'products/experiments/frontend/generated/api.schemas'
import type { eventExperimentsLogicType } from './eventExperimentsLogicType'
@@ -14,7 +17,7 @@ export interface EventExperimentsLogicProps {
export const EXPERIMENTS_PER_PAGE = 10
-const EMPTY_RESULT: PaginatedExperimentListApi = { count: 0, next: null, previous: null, results: [] }
+const EMPTY_RESULT: PaginatedExperimentBasicListApi = { count: 0, next: null, previous: null, results: [] }
export const eventExperimentsLogic = kea<eventExperimentsLogicType>([
path(['scenes', 'data-management', 'events', 'eventExperimentsLogic']),
@@ -33,7 +36,7 @@ export const eventExperimentsLogic = kea<eventExperimentsLogicType>([
experiments: [
EMPTY_RESULT,
{
- loadExperiments: async (): Promise<PaginatedExperimentListApi> => {
+ loadExperiments: async (): Promise<PaginatedExperimentBasicListApi> => {
return await experimentsList(String(values.currentProjectId), {
event: props.event,
limit: EXPERIMENTS_PER_PAGE,
@@ -53,4 +56,4 @@ export const eventExperimentsLogic = kea<eventExperimentsLogicType>([
}),
])
-export type { ExperimentApi }
+export type { ExperimentBasicApi }
diff --git a/frontend/src/scenes/experiments/Experiments.tsx b/frontend/src/scenes/experiments/Experiments.tsx
index b4a64003b6ed..8e66b4765164 100644
--- a/frontend/src/scenes/experiments/Experiments.tsx
+++ b/frontend/src/scenes/experiments/Experiments.tsx
@@ -62,7 +62,6 @@ import { ExperimentVelocityStats } from './ExperimentVelocityStats'
import { StatusTag } from './ExperimentView/StatusTag'
import { Holdouts } from './Holdouts'
import { SharedMetrics } from './SharedMetrics/SharedMetrics'
-import { isLegacyExperiment } from './utils'
export const scene: SceneExport = {
component: Experiments,
@@ -230,7 +229,7 @@ const ExperimentsTable = ({
No-code
</LemonTag>
)}
- {isLegacyExperiment(experiment) && (
+ {experiment.is_legacy && (
<Tooltip
title="This experiment uses the legacy engine, so some features and improvements may be missing."
docLink="https://posthog.com/docs/experiments/new-experimentation-engine"
@@ -387,7 +386,7 @@ const ExperimentsTable = ({
size="small"
fullWidth
disabledReason={
- isLegacyExperiment(experiment)
+ experiment.is_legacy
? 'Not supported for experiments using legacy metrics. Please recreate the experiment manually.'
: undefined
}
@@ -400,7 +399,7 @@ const ExperimentsTable = ({
size="small"
fullWidth
disabledReason={
- isLegacyExperiment(experiment)
+ experiment.is_legacy
? 'Copying is not supported for experiments using legacy metrics.'
: undefined
}
diff --git a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/ExperimentsNotebookTable.tsx b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/ExperimentsNotebookTable.tsx
index 39b5b6f04c1d..06e52bedf8ec 100644
--- a/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/ExperimentsNotebookTable.tsx
+++ b/frontend/src/scenes/notebooks/AddExperimentsToNotebookModal/ExperimentsNotebookTable.tsx
@@ -9,7 +9,6 @@ import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { getExperimentStatus } from '~/scenes/experiments/experimentsLogic'
import { StatusTag } from '~/scenes/experiments/ExperimentView/StatusTag'
-import { isLegacyExperiment } from '~/scenes/experiments/utils'
import { notebookLogic } from '~/scenes/notebooks/Notebook/notebookLogic'
import { NotebookNodeType } from '~/scenes/notebooks/types'
import { Experiment } from '~/types'
@@ -67,7 +66,7 @@ export function ExperimentsNotebookTable({ insertionPosition }: ExperimentsNoteb
<Tooltip title={experiment.name}>
<span className="block truncate max-w-full font-medium">{experiment.name}</span>
</Tooltip>
- {isLegacyExperiment(experiment) && (
+ {experiment.is_legacy && (
<LemonTag type="warning" size="small">
Legacy
</LemonTag>
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 064917815c10..2034717a2399 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4753,6 +4753,8 @@ export interface Experiment {
start_date?: string | null
end_date?: string | null
status?: ExperimentStatus | null
+ /** Server-computed: whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery). Present on every list and detail response; optional here because locally-constructed/new experiments don't set it (and are never legacy). */
+ is_legacy?: boolean
archived?: boolean
secondary_metrics: SecondaryExperimentMetric[]
created_at: string | null
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 4aac7687bd2d..63df1b3460f5 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -507,6 +507,11 @@ SPECTACULAR_SETTINGS = {
"HeatmapType": "products.web_analytics.backend.models.heatmap_saved.SavedHeatmap.Type",
# --- Inline value lists (type-hint enums, no x-spec-enum-id) ---
"PropertyGroupOperator": ["AND", "OR"],
+ # Experiment now has two serializers (full ExperimentSerializer + ExperimentBasicSerializer
+ # for the list endpoint) that both expose `type`/`status`. Pin both to their pre-existing
+ # generated names so the shared enums don't get component-prefixed auto-names on collision.
+ "ExperimentTypeEnum": ["web", "product", None],
+ "ExperimentStatusEnum": ["draft", "running", "paused", "stopped"],
# Two serializers now expose an `op` ChoiceField (metrics filters and email-template design
# patches). Pin both to stable names so neither gets a component-prefixed auto-name on collision.
# "OpEnum" keeps the metrics filter enum at its pre-existing generated name.
diff --git a/products/ai_observability/frontend/prompts/promptExperimentsLogic.ts b/products/ai_observability/frontend/prompts/promptExperimentsLogic.ts
index 336523f99c42..8fa28f848552 100644
--- a/products/ai_observability/frontend/prompts/promptExperimentsLogic.ts
+++ b/products/ai_observability/frontend/prompts/promptExperimentsLogic.ts
@@ -5,7 +5,7 @@ import posthog from 'posthog-js'
import { ApiConfig } from '~/lib/api'
import { experimentsList } from '../../../experiments/frontend/generated/api'
-import type { ExperimentApi } from '../../../experiments/frontend/generated/api.schemas'
+import type { ExperimentBasicApi } from '../../../experiments/frontend/generated/api.schemas'
import { createPromptExperimentModalLogic } from './createPromptExperimentModalLogic'
import type { promptExperimentsLogicType } from './promptExperimentsLogicType'
@@ -28,7 +28,7 @@ export const promptExperimentsLogic = kea<promptExperimentsLogicType>([
loaders(({ props }) => ({
experiments: [
- [] as ExperimentApi[],
+ [] as ExperimentBasicApi[],
{
loadExperiments: async () => {
const response = await experimentsList(String(ApiConfig.getCurrentTeamId()), {
diff --git a/products/ai_observability/frontend/prompts/promptSceneComponents.tsx b/products/ai_observability/frontend/prompts/promptSceneComponents.tsx
index e1e12860c29f..00ae029a6056 100644
--- a/products/ai_observability/frontend/prompts/promptSceneComponents.tsx
+++ b/products/ai_observability/frontend/prompts/promptSceneComponents.tsx
@@ -19,7 +19,7 @@ import { DataTable } from '~/queries/nodes/DataTable/DataTable'
import { Query } from '~/queries/Query/Query'
import { AccessControlLevel, AccessControlResourceType, LLMPrompt, LLMPromptVersionSummary } from '~/types'
-import type { ExperimentApi } from '../../../experiments/frontend/generated/api.schemas'
+import type { ExperimentBasicApi } from '../../../experiments/frontend/generated/api.schemas'
import { useTracesQueryContext } from '../AIObservabilityTracesScene'
import { MarkdownOutline } from '../components/MarkdownOutline'
import { CreatePromptExperimentModal } from './CreatePromptExperimentModal'
@@ -337,7 +337,7 @@ export function PromptUsage({ prompt }: { prompt: LLMPrompt }): JSX.Element {
)
}
-function experimentStatusTag(experiment: ExperimentApi): JSX.Element {
+function experimentStatusTag(experiment: ExperimentBasicApi): JSX.Element {
if (experiment.archived) {
return <LemonTag type="muted">Archived</LemonTag>
}
@@ -350,7 +350,7 @@ function experimentStatusTag(experiment: ExperimentApi): JSX.Element {
return <LemonTag type="default">Draft</LemonTag>
}
-function promptMetadata(experiment: ExperimentApi): { templates: string[]; versions: number[] } {
+function promptMetadata(experiment: ExperimentBasicApi): { templates: string[]; versions: number[] } {
const params = experiment.parameters as { prompt_metadata?: { templates?: string[]; versions?: number[] } } | null
const meta = params?.prompt_metadata
return {
@@ -364,7 +364,7 @@ export function PromptExperiments({ prompt }: { prompt: LLMPrompt }): JSX.Elemen
const { openModal } = useActions(createPromptExperimentModalLogic)
const { experiments, experimentsLoading } = useValues(promptExperimentsLogic({ promptName: prompt.name }))
- const columns: LemonTableColumns<ExperimentApi> = [
+ const columns: LemonTableColumns<ExperimentBasicApi> = [
{
title: 'Name',
dataIndex: 'name',
diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.tsx
index a90f8d7cfaca..c2e47ced865d 100644
--- a/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.tsx
+++ b/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.tsx
@@ -7,7 +7,7 @@ import { LemonInputSelect, type LemonInputSelectOption } from 'lib/lemon-ui/Lemo
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { fullName } from 'lib/utils/strings'
-import type { ExperimentApi } from 'products/experiments/frontend/generated/api.schemas'
+import type { ExperimentBasicApi } from 'products/experiments/frontend/generated/api.schemas'
import { experimentPickerLogic } from './experimentPickerLogic'
@@ -22,7 +22,7 @@ export type ExperimentPickerSelectProps = {
dataAttr?: string
}
-function ExperimentOptionLabel({ experiment }: { experiment: ExperimentApi }): JSX.Element {
+function ExperimentOptionLabel({ experiment }: { experiment: ExperimentBasicApi }): JSX.Element {
const creator = experiment.created_by
const creatorName = creator ? fullName(creator) || creator.email : null
return (
@@ -62,7 +62,7 @@ export function ExperimentPickerSelect({
}, [value, ensureSelectedLoaded])
const options = useMemo((): LemonInputSelectOption[] => {
- const byId = new Map<number, ExperimentApi>()
+ const byId = new Map<number, ExperimentBasicApi>()
if (selectedExperiment) {
byId.set(selectedExperiment.id, selectedExperiment)
}
diff --git a/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.ts b/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.ts
index b646e5d59b86..5c6fade8a78c 100644
--- a/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.ts
+++ b/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.ts
@@ -4,7 +4,7 @@ import { loaders } from 'kea-loaders'
import { teamLogic } from 'scenes/teamLogic'
import { experimentsList, experimentsRetrieve } from 'products/experiments/frontend/generated/api'
-import type { ExperimentApi } from 'products/experiments/frontend/generated/api.schemas'
+import type { ExperimentApi, ExperimentBasicApi } from 'products/experiments/frontend/generated/api.schemas'
import type { experimentPickerLogicType } from './experimentPickerLogicType'
@@ -36,12 +36,12 @@ export const experimentPickerLogic = kea<experimentPickerLogicType>([
loaders(({ values }) => ({
experimentOptions: [
- [] as ExperimentApi[],
+ [] as ExperimentBasicApi[],
{
loadOptions: async (
{ debounce }: { debounce: boolean } = { debounce: false },
breakpoint
- ): Promise<ExperimentApi[]> => {
+ ): Promise<ExperimentBasicApi[]> => {
// Debounce keystroke-driven searches; the initial focus load should open the dropdown immediately.
if (debounce) {
await breakpoint(SEARCH_DEBOUNCE_MS)
diff --git a/products/experiments/backend/metric_utils.py b/products/experiments/backend/metric_utils.py
index 1325446400ad..1b78579c944e 100644
--- a/products/experiments/backend/metric_utils.py
+++ b/products/experiments/backend/metric_utils.py
@@ -145,24 +145,6 @@ def _update_action_names(obj: Any, actions_by_id: dict[int, str]) -> None:
_update_action_names(item, actions_by_id)
-def resolve_action_names(metrics: list[dict[str, Any] | None], team: Team) -> dict[int, str]:
- """Resolve {action_id: name} for every ActionsNode across many metric queries in one query.
-
- Lets callers serializing a page of experiments batch action-name resolution instead of
- issuing a separate query per metric. Pass the result into ``refresh_action_names_in_metric``.
- Returns an empty map (no query) when no actions are referenced.
- """
- action_ids: set[int] = set()
- for metric in metrics:
- if metric:
- _collect_action_ids(metric, action_ids)
-
- if not action_ids:
- return {}
-
- return {action.id: action.name for action in Action.objects.filter(id__in=action_ids, team=team, deleted=False)}
-
-
def _collect_event_names_and_action_ids(obj: Any, event_names: set[str], action_ids: set[int]) -> None:
"""Recursively collect EventsNode event names and ActionsNode IDs from a metric query."""
if isinstance(obj, dict):
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 85d8831cb290..f8f39a6e3616 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -32,8 +32,13 @@ from products.experiments.backend.facade.contracts import CreateExperimentInput
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
from products.experiments.backend.llm_metric_templates import TEMPLATE_NAMES
-from products.experiments.backend.metric_utils import refresh_action_names_in_metric, resolve_action_names
-from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentMetricsRecalculation
+from products.experiments.backend.metric_utils import refresh_action_names_in_metric
+from products.experiments.backend.models.experiment import (
+ Experiment,
+ ExperimentHoldout,
+ ExperimentMetricsRecalculation,
+ experiment_has_legacy_metrics,
+)
from products.experiments.backend.running_time_calculator import METRIC_TYPE_CHOICES
from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -109,37 +114,17 @@ class ExperimentRunningTimeCalculationField(serializers.JSONField):
pass
-class ExperimentListSerializer(serializers.ListSerializer):
- """Batches action-name resolution across a whole page of experiments.
+class ExperimentBaseSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):
+ """Shared read-side fields for the full and list experiment serializers.
- ``ExperimentSerializer.to_representation`` refreshes stale cached action names on every
- metric, which would otherwise issue one ``Action`` query per metric per experiment. Here we
- resolve every referenced action in a single query and hand the map down via the shared
- serializer context, so a 100-experiment page does one action query instead of hundreds.
+ ``ExperimentSerializer`` (detail + write) and ``ExperimentBasicSerializer`` (list) both
+ declare the scalar, feature-flag, and method fields here, so they render identical types
+ for the fields they share. That keeps ``ExperimentApi`` a structural superset of
+ ``ExperimentBasicApi`` — which consumers rely on — by construction, not by hand-mirroring
+ field definitions across two classes. This base is abstract: subclasses supply their own
+ ``Meta`` (model + fields) and it is never instantiated on its own.
"""
- @tracer.start_as_current_span("ExperimentListSerializer.to_representation")
- def to_representation(self, data):
- instances = list(data)
- trace.get_current_span().set_attribute("experiment_count", len(instances))
-
- metric_queries: list[dict[str, Any] | None] = []
- team: Team | None = None
- for instance in instances:
- team = instance.team
- metric_queries.extend(instance.metrics or [])
- metric_queries.extend(instance.metrics_secondary or [])
- # Saved metrics are prefetched via experimenttosavedmetric_set
- for relation in instance.experimenttosavedmetric_set.all():
- metric_queries.append(relation.saved_metric.query)
-
- if team is not None:
- self.context["actions_by_id"] = resolve_action_names(metric_queries, team)
-
- return super().to_representation(instances)
-
-
-class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):
feature_flag_key = serializers.CharField(
source="get_feature_flag_key",
help_text=(
@@ -150,33 +135,6 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
created_by = UserBasicSerializer(read_only=True)
feature_flag = serializers.SerializerMethodField(read_only=True)
holdout = ExperimentHoldoutSerializer(read_only=True)
- holdout_id = TeamScopedPrimaryKeyRelatedField(
- queryset=ExperimentHoldout.objects.all(),
- source="holdout",
- required=False,
- 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_ids = serializers.ListField(
- child=serializers.JSONField(),
- required=False,
- allow_null=True,
- help_text="IDs of shared saved metrics to attach to this experiment. Each item has 'id' (saved metric ID) and 'metadata' with 'type' (primary or secondary).",
- )
- allow_unknown_events = serializers.BooleanField(
- required=False,
- default=False,
- write_only=True,
- help_text=(
- "Suppresses the validation that rejects metrics referencing events not yet "
- "ingested by this project. REQUIRES explicit user confirmation before being "
- "set to true — never flip this silently to retry a failed call. The default "
- "validation catches typo'd event names and missing instrumentation. Set this "
- "to true only when the user has confirmed the event is intentional (e.g. they "
- "are about to instrument it)."
- ),
- )
name = serializers.CharField(
max_length=400,
help_text="Name of the experiment.",
@@ -213,28 +171,6 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"during the deprecation window."
),
)
- metrics = ExperimentMetricsField(
- required=False,
- allow_null=True,
- help_text=(
- "Primary experiment metrics. Each metric must have kind='ExperimentMetric' and a metric_type: "
- "'mean' (set source to an EventsNode with an event name), "
- "'funnel' (set series to an array of EventsNode steps), "
- "'ratio' (set numerator and denominator EventsNode entries), or "
- "'retention' (set start_event and completion_event). "
- "Use the read-data-schema tool with query kind 'events' to find available events in the project."
- ),
- )
- metrics_secondary = ExperimentMetricsField(
- required=False,
- allow_null=True,
- help_text="Secondary metrics for additional measurements. Same format as primary metrics.",
- )
- exposure_criteria = ExperimentExposureCriteriaField(
- required=False,
- allow_null=True,
- help_text="Exposure configuration including filter test accounts and custom exposure events.",
- )
conclusion = serializers.ChoiceField(
choices=["won", "lost", "inconclusive", "stopped_early", "invalid"],
required=False,
@@ -258,6 +194,98 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
allow_null=True,
help_text="Experiment type: web for frontend UI changes, product for backend/API changes.",
)
+ status = serializers.SerializerMethodField(
+ help_text=(
+ "Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature "
+ "flag), 'paused' (running with feature flag deactivated — virtual state derived from "
+ "feature_flag.active, not stored), 'stopped' (ended)."
+ ),
+ )
+ is_legacy = serializers.SerializerMethodField(
+ help_text=(
+ "Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or "
+ "ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support "
+ "them, such as duplicate and copy-to-project."
+ ),
+ )
+
+ @extend_schema_field({"type": "string", "enum": ["draft", "running", "paused", "stopped"]})
+ def get_status(self, instance: Experiment) -> str:
+ return instance.status_label
+
+ @extend_schema_field(MinimalFeatureFlagSerializer)
+ def get_feature_flag(self, obj):
+ return MinimalFeatureFlagSerializer(obj.feature_flag).data if obj.feature_flag else None
+
+ @extend_schema_field(serializers.BooleanField())
+ def get_is_legacy(self, obj: Experiment) -> bool:
+ # The list queryset annotates is_legacy_annotation in SQL so the heavy metric columns stay
+ # deferred (see EnterpriseExperimentsViewSet.safely_get_queryset / list_is_legacy_annotation).
+ # On other paths (detail) the metrics are loaded, so fall back to computing it directly.
+ annotated = getattr(obj, "is_legacy_annotation", None)
+ if annotated is not None:
+ return annotated
+ return experiment_has_legacy_metrics(obj)
+
+
+class ExperimentSerializer(ExperimentBaseSerializer):
+ """Full experiment representation for the detail, create, and update endpoints.
+
+ Extends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric
+ definitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side
+ fields, and refreshes stale action names while serializing. The list endpoint uses the
+ leaner ``ExperimentBasicSerializer`` instead.
+ """
+
+ holdout_id = TeamScopedPrimaryKeyRelatedField(
+ queryset=ExperimentHoldout.objects.all(),
+ source="holdout",
+ required=False,
+ 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_ids = serializers.ListField(
+ child=serializers.JSONField(),
+ required=False,
+ allow_null=True,
+ help_text="IDs of shared saved metrics to attach to this experiment. Each item has 'id' (saved metric ID) and 'metadata' with 'type' (primary or secondary).",
+ )
+ allow_unknown_events = serializers.BooleanField(
+ required=False,
+ default=False,
+ write_only=True,
+ help_text=(
+ "Suppresses the validation that rejects metrics referencing events not yet "
+ "ingested by this project. REQUIRES explicit user confirmation before being "
+ "set to true — never flip this silently to retry a failed call. The default "
+ "validation catches typo'd event names and missing instrumentation. Set this "
+ "to true only when the user has confirmed the event is intentional (e.g. they "
+ "are about to instrument it)."
+ ),
+ )
+ metrics = ExperimentMetricsField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Primary experiment metrics. Each metric must have kind='ExperimentMetric' and a metric_type: "
+ "'mean' (set source to an EventsNode with an event name), "
+ "'funnel' (set series to an array of EventsNode steps), "
+ "'ratio' (set numerator and denominator EventsNode entries), or "
+ "'retention' (set start_event and completion_event). "
+ "Use the read-data-schema tool with query kind 'events' to find available events in the project."
+ ),
+ )
+ metrics_secondary = ExperimentMetricsField(
+ required=False,
+ allow_null=True,
+ help_text="Secondary metrics for additional measurements. Same format as primary metrics.",
+ )
+ exposure_criteria = ExperimentExposureCriteriaField(
+ required=False,
+ allow_null=True,
+ help_text="Exposure configuration including filter test accounts and custom exposure events.",
+ )
update_feature_flag_params = serializers.BooleanField(
required=False,
default=False,
@@ -269,19 +297,8 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"for non-drafts."
),
)
- status = serializers.SerializerMethodField(
- help_text=(
- "Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature "
- "flag), 'paused' (running with feature flag deactivated — virtual state derived from "
- "feature_flag.active, not stored), 'stopped' (ended)."
- ),
- )
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
- @extend_schema_field({"type": "string", "enum": ["draft", "running", "paused", "stopped"]})
- def get_status(self, instance: Experiment) -> str:
- return instance.status_label
-
class Meta:
model = Experiment
fields = [
@@ -321,6 +338,7 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"only_count_matured_users",
"update_feature_flag_params",
"status",
+ "is_legacy",
"user_access_level",
]
read_only_fields = [
@@ -335,7 +353,6 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"status",
"user_access_level",
]
- list_serializer_class = ExperimentListSerializer
def get_fields(self):
fields = super().get_fields()
@@ -346,10 +363,6 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
fields["holdout_id"].queryset = ExperimentHoldout.objects.none() # type: ignore[attr-defined]
return fields
- @extend_schema_field(MinimalFeatureFlagSerializer)
- def get_feature_flag(self, obj):
- return MinimalFeatureFlagSerializer(obj.feature_flag).data if obj.feature_flag else None
-
@tracer.start_as_current_span("ExperimentSerializer.to_representation")
def to_representation(self, instance):
data = super().to_representation(instance)
@@ -361,16 +374,14 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"explicitDate": True,
}
- # actions_by_id is preloaded once per page by ExperimentListSerializer to avoid an
- # Action query per metric; None on detail/launch/archive paths (falls back to a query).
- actions_by_id = self.context.get("actions_by_id")
-
- # Refresh action names in inline metrics (metrics and metrics_secondary)
- # The columns are nullable, so the keys can be present with a None value
+ # Refresh action names in inline metrics (metrics and metrics_secondary).
+ # The columns are nullable, so the keys can be present with a None value. Each call
+ # resolves the experiment's actions in a single query — fine here because this serializer
+ # only ever renders one experiment at a time (detail/launch/archive/…), never a list page.
for metrics_list in [data.get("metrics") or [], data.get("metrics_secondary") or []]:
for i, metric in enumerate(metrics_list):
# Refresh action names to show current names instead of stale cached values
- refreshed_metric = refresh_action_names_in_metric(metric, instance.team, actions_by_id)
+ refreshed_metric = refresh_action_names_in_metric(metric, instance.team)
if refreshed_metric:
metrics_list[i] = refreshed_metric
metric = refreshed_metric
@@ -539,6 +550,67 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
)
+class ExperimentBasicSerializer(ExperimentBaseSerializer):
+ """Lightweight, read-only serializer for the experiment list endpoint.
+
+ The list view (and the MCP list tool) render only the scalar and feature-flag fields
+ shared via ``ExperimentBaseSerializer`` — never the metric definitions. Omitting
+ ``metrics``/``metrics_secondary``/``saved_metrics`` lets the list query defer the large
+ JSON columns and skip the saved-metric prefetch plus per-row fingerprinting; that work
+ belongs to the detail response served by ``ExperimentSerializer``.
+
+ Because the metric fields, the write-side machinery, and the action-name-refreshing
+ ``to_representation`` all live on ``ExperimentSerializer`` rather than the shared base,
+ this serializer needs no overrides: it gets DRF's default ``get_fields`` (no write-only
+ ``holdout_id`` to configure), default ``to_representation`` (no metrics to normalize), and
+ a plain ``ListSerializer`` that never touches the deferred columns. See
+ ``EnterpriseExperimentsViewSet.safely_get_queryset``.
+ """
+
+ class Meta:
+ model = Experiment
+ fields = [
+ "id",
+ "name",
+ "description",
+ "start_date",
+ "end_date",
+ "feature_flag_key",
+ "feature_flag",
+ "holdout",
+ "exposure_cohort",
+ "parameters",
+ "running_time_calculation",
+ "archived",
+ "deleted",
+ "created_by",
+ "created_at",
+ "updated_at",
+ "type",
+ "conclusion",
+ "conclusion_comment",
+ "status",
+ "is_legacy",
+ "user_access_level",
+ ]
+ # Shared fields take their definitions from ExperimentBaseSerializer, so their types
+ # already match ExperimentSerializer. read_only_fields still has to mirror the full
+ # serializer for the model-derived fields (id/created_at/exposure_cohort/...) so each
+ # field's optionality matches and ExperimentApi stays a structural superset of
+ # ExperimentBasicApi, which consumers rely on.
+ read_only_fields = [
+ "id",
+ "created_by",
+ "created_at",
+ "updated_at",
+ "feature_flag",
+ "exposure_cohort",
+ "holdout",
+ "status",
+ "user_access_level",
+ ]
+
+
class EndExperimentSerializer(serializers.Serializer):
conclusion = serializers.ChoiceField(
choices=["won", "lost", "inconclusive", "stopped_early", "invalid"],
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 14398f233c73..342ad15590ec 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -13,7 +13,7 @@ import asyncio
from typing import Any, Literal, cast
from django.conf import settings
-from django.db.models import Prefetch, QuerySet
+from django.db.models import BooleanField, Case, Exists, OuterRef, Prefetch, Q, QuerySet, Value, When
from django.utils.text import slugify
import posthoganalytics
@@ -44,6 +44,7 @@ from products.experiments.backend.llm_metric_templates import build_template, li
# TODO: Route through facade instead of direct import
from products.experiments.backend.models.experiment import (
+ LEGACY_METRIC_KINDS,
Experiment,
ExperimentMetricsRecalculation,
ExperimentTimeseriesRecalculation,
@@ -54,6 +55,7 @@ from products.experiments.backend.presentation.serializers import (
CopyExperimentToProjectSerializer,
CreateFromPromptInputSerializer,
EndExperimentSerializer,
+ ExperimentBasicSerializer,
ExperimentMetricsRecalculationSerializer,
ExperimentSerializer,
RecalculateMetricsRequestSerializer,
@@ -89,6 +91,54 @@ from ee.clickhouse.queries.experiments.utils import requires_flag_warning
tracer = trace.get_tracer(__name__)
+# Heavy JSON columns the list view never renders. Deferred for the list action so large
+# pages don't pay to read/decode detail-only data; the full serializer still loads them
+# for retrieve/update. None of these are touched by the list filters or status derivation.
+LIST_DEFERRED_FIELDS = (
+ "metrics",
+ "metrics_secondary",
+ "secondary_metrics",
+ "exposure_criteria",
+ "stats_config",
+ "scheduling_config",
+ "filters",
+ "primary_metrics_ordered_uuids",
+ "secondary_metrics_ordered_uuids",
+)
+
+
+def flag_evaluation_contexts_prefetch() -> Prefetch:
+ return Prefetch(
+ "feature_flag__flag_evaluation_contexts",
+ queryset=FeatureFlagEvaluationContext.objects.select_related("evaluation_context"),
+ )
+
+
+def list_is_legacy_annotation() -> Case:
+ """DB-side `is_legacy` for the list endpoint, mirroring ``experiment_has_legacy_metrics`` in SQL.
+
+ The list serializer omits metrics, so it can't compute legacy-ness in Python without
+ re-reading the deferred JSON columns (one query per row). Instead we annotate the flag in the
+ single list query: a JSONB containment check on the inline metrics plus an ``EXISTS`` over the
+ saved metrics. The metric columns are referenced only in the predicate, so they stay out of the
+ SELECT output and the response — the deferral still holds.
+ """
+ inline_legacy = Q()
+ for kind in LEGACY_METRIC_KINDS:
+ inline_legacy |= Q(metrics__contains=[{"kind": kind}]) | Q(metrics_secondary__contains=[{"kind": kind}])
+ saved_legacy = Exists(
+ ExperimentToSavedMetric.objects.filter(
+ experiment=OuterRef("pk"),
+ saved_metric__query__kind__in=LEGACY_METRIC_KINDS,
+ )
+ )
+ return Case(
+ When(inline_legacy | saved_legacy, then=Value(True)),
+ default=Value(False),
+ output_field=BooleanField(),
+ )
+
+
PROMPT_EXPERIMENTS_FEATURE_FLAG = "experiments-llm-prompts"
@@ -262,10 +312,7 @@ class EnterpriseExperimentsViewSet(
"holdout__created_by",
)
.prefetch_related(
- Prefetch(
- "feature_flag__flag_evaluation_contexts",
- queryset=FeatureFlagEvaluationContext.objects.select_related("evaluation_context"),
- ),
+ flag_evaluation_contexts_prefetch(),
Prefetch(
# order_by("id") keeps saved metrics in insertion order — select_related below adds
# joins that would otherwise leave the row order unspecified.
@@ -279,6 +326,13 @@ class EnterpriseExperimentsViewSet(
)
ordering = "-created_at"
+ def get_serializer_class(self):
+ # The list view renders only scalar/flag fields; use the lightweight serializer so the
+ # heavy metric fields (and their prefetch/fingerprinting) are skipped — see safely_get_queryset.
+ if self.action == "list":
+ return ExperimentBasicSerializer
+ return ExperimentSerializer
+
@tracer.start_as_current_span("ExperimentViewSet.list")
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return super().list(request, *args, **kwargs)
@@ -286,6 +340,17 @@ class EnterpriseExperimentsViewSet(
@tracer.start_as_current_span("ExperimentViewSet.safely_get_queryset")
def safely_get_queryset(self, queryset) -> QuerySet:
request = getattr(self, "request", None)
+ if self.action == "list":
+ # ExperimentBasicSerializer omits metrics/saved_metrics, so drop the saved-metric
+ # prefetch and defer the heavy JSON columns. The ?event= filter reads metrics via its
+ # own values_list/queries, so it is unaffected by the defer. is_legacy is computed in
+ # SQL (see list_is_legacy_annotation) so the badge/guards survive without loading metrics.
+ queryset = (
+ queryset.prefetch_related(None)
+ .prefetch_related(flag_evaluation_contexts_prefetch())
+ .defer(*LIST_DEFERRED_FIELDS)
+ .annotate(is_legacy_annotation=list_is_legacy_annotation())
+ )
service = ExperimentService(team=self.team, user=getattr(request, "user", None))
return service.filter_experiments_queryset(
queryset,
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 7e5ae13c893f..806d547e4e12 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -1,6 +1,7 @@
from datetime import UTC, datetime, timedelta
from typing import Any, cast
+import unittest
from freezegun import freeze_time
from posthog.test.base import ClickhouseTestMixin, FuzzyInt, _create_event, _create_person, flush_persons_and_events
from unittest.mock import ANY, MagicMock, patch
@@ -30,6 +31,7 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.models.web_experiment import WebExperiment
+from products.experiments.backend.presentation.views import LIST_DEFERRED_FIELDS
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags_for_team_in_cache
@@ -396,8 +398,8 @@ class TestExperimentCRUD(APILicensedTest):
return experiment, action
def test_listing_experiments_with_action_metrics_is_not_nplus1(self) -> None:
- # Action names are refreshed per metric during serialization; without batching this is one
- # Action query per metric per experiment. Query count must stay flat as rows grow.
+ # The list serializer omits metrics, so no per-metric Action lookups happen during
+ # serialization. Query count must stay flat as rows grow.
self._create_experiment_with_action_metrics(0)
with CaptureQueriesContext(connection) as single_row:
@@ -415,19 +417,114 @@ class TestExperimentCRUD(APILicensedTest):
self.assertLessEqual(len(five_rows.captured_queries), len(single_row.captured_queries))
- def test_listing_experiments_refreshes_action_names(self) -> None:
+ def test_list_query_defers_heavy_metric_columns(self) -> None:
+ # Omitting the metric fields lets the list query defer the heavy JSON columns — they must not
+ # be SELECTed from posthog_experiment. metrics/metrics_secondary are the exception: the
+ # is_legacy annotation references them in its predicate (see list_is_legacy_annotation), so
+ # they appear in the WHERE/CASE but never in the SELECT output — the response still omits them
+ # (test_list_omits_heavy_metric_fields_kept_on_detail). The other deferred columns stay absent.
+ self._create_experiment_with_action_metrics(0)
+
+ with CaptureQueriesContext(connection) as ctx:
+ response = self.client.get(f"/api/projects/{self.team.id}/experiments")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ experiment_selects = [
+ query["sql"] for query in ctx.captured_queries if 'FROM "posthog_experiment"' in query["sql"]
+ ]
+ self.assertTrue(experiment_selects, "expected at least one SELECT against posthog_experiment")
+ # Inspected by the is_legacy predicate, so allowed in the SQL (but not in the SELECT output).
+ predicate_columns = {"metrics", "metrics_secondary"}
+ for sql in experiment_selects:
+ for column in LIST_DEFERRED_FIELDS:
+ if column in predicate_columns:
+ continue
+ # Table-qualified so a same-named column on a joined table (e.g. feature_flag.filters)
+ # doesn't trigger a false positive.
+ self.assertNotIn(f'"posthog_experiment"."{column}"', sql)
+
+ def test_list_reports_is_legacy(self) -> None:
+ # is_legacy must survive the metric omission — it's computed in SQL on the list path so the
+ # frontend badge/duplicate/copy guards keep working without loading the deferred metric JSON.
+ # Cover the inline-metric path and the saved-metric (EXISTS) path, plus a non-legacy control.
+ non_legacy, action = self._create_experiment_with_action_metrics(0)
+
+ legacy_inline = Experiment.objects.create(
+ team=self.team,
+ name="Legacy inline",
+ feature_flag=FeatureFlag.objects.create(team=self.team, key="legacy-inline", created_by=self.user),
+ created_by=self.user,
+ metrics=[{"kind": "ExperimentTrendsQuery"}],
+ )
+
+ legacy_via_saved = Experiment.objects.create(
+ team=self.team,
+ name="Legacy via saved metric",
+ feature_flag=FeatureFlag.objects.create(team=self.team, key="legacy-saved", created_by=self.user),
+ created_by=self.user,
+ metrics=[
+ {"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "ActionsNode", "id": action.id}}
+ ],
+ )
+ legacy_saved_metric = ExperimentSavedMetric.objects.create(
+ team=self.team,
+ name="Legacy saved metric",
+ created_by=self.user,
+ query={"kind": "ExperimentFunnelsQuery"},
+ )
+ ExperimentToSavedMetric.objects.create(experiment=legacy_via_saved, saved_metric=legacy_saved_metric)
+
+ results = self.client.get(f"/api/projects/{self.team.id}/experiments").json()["results"]
+ by_id = {r["id"]: r for r in results}
+
+ self.assertFalse(by_id[non_legacy.id]["is_legacy"])
+ self.assertTrue(by_id[legacy_inline.id]["is_legacy"])
+ self.assertTrue(by_id[legacy_via_saved.id]["is_legacy"])
+
+ def test_detail_reports_is_legacy(self) -> None:
+ experiment, _ = self._create_experiment_with_action_metrics(0)
+ Experiment.objects.filter(pk=experiment.pk).update(metrics=[{"kind": "ExperimentTrendsQuery"}])
+
+ response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment.id}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertTrue(response.json()["is_legacy"])
+
+ def test_retrieving_experiment_refreshes_action_names(self) -> None:
+ # Action-name refresh lives on the detail response — the list endpoint no longer
+ # returns metrics (see ExperimentBasicSerializer).
experiment, action = self._create_experiment_with_action_metrics(0)
action.name = "Renamed action"
action.save()
- response = self.client.get(f"/api/projects/{self.team.id}/experiments")
+ response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment.id}")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- result = next(r for r in response.json()["results"] if r["id"] == experiment.id)
+ result = response.json()
self.assertEqual(result["metrics"][0]["source"]["name"], "Renamed action")
self.assertEqual(result["metrics_secondary"][0]["source"]["name"], "Renamed action")
self.assertEqual(result["saved_metrics"][0]["query"]["source"]["name"], "Renamed action")
+ def test_list_omits_heavy_metric_fields_kept_on_detail(self) -> None:
+ # The list view never renders metric definitions, so they're excluded from the list
+ # response (letting the query defer the JSON columns and skip the saved-metric prefetch).
+ # The detail response still includes them.
+ experiment, _ = self._create_experiment_with_action_metrics(0)
+
+ list_result = next(
+ r
+ for r in self.client.get(f"/api/projects/{self.team.id}/experiments").json()["results"]
+ if r["id"] == experiment.id
+ )
+ for omitted in ["metrics", "metrics_secondary", "saved_metrics"]:
+ self.assertNotIn(omitted, list_result)
+ # Fields the list view does use are still present.
+ for kept in ["name", "status", "feature_flag", "parameters"]:
+ self.assertIn(kept, list_result)
+
+ detail_result = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment.id}").json()
+ for present in ["metrics", "metrics_secondary", "saved_metrics"]:
+ self.assertIn(present, detail_result)
+
def test_creating_updating_basic_experiment(self):
ff_key = "a-b-tests"
response = self.client.post(
@@ -7093,3 +7190,52 @@ class TestCalculateRunningTimeEndpoint(APILicensedTest):
def test_invalid_input_rejected(self, _name: str, payload: dict):
response = self._calculate(payload)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
+
+
+class TestExperimentSerializerSuperset(unittest.TestCase):
+ """Structural guard: ExperimentBasicSerializer must stay a subset of ExperimentSerializer.
+
+ ExperimentBasicApi is a structural subset of ExperimentApi in generated frontend types.
+ If a field is added to the detail serializer but forgotten in the basic one the superset
+ invariant holds — but the reverse (basic grows a field not in detail) would break it, and
+ a mismatched read_only/required on a shared field would produce divergent nullability.
+ """
+
+ def test_basic_fields_are_subset_of_full_fields(self) -> None:
+ from products.experiments.backend.presentation.serializers import (
+ ExperimentBasicSerializer,
+ ExperimentSerializer,
+ )
+
+ basic = ExperimentBasicSerializer()
+ full = ExperimentSerializer()
+ basic_field_names = set(basic.fields.keys())
+ full_field_names = set(full.fields.keys())
+ extra = basic_field_names - full_field_names
+ self.assertFalse(
+ extra,
+ f"ExperimentBasicSerializer has fields not present in ExperimentSerializer: {extra}. "
+ "ExperimentBasicApi must remain a structural subset of ExperimentApi.",
+ )
+
+ def test_shared_fields_have_matching_read_only_and_required(self) -> None:
+ from products.experiments.backend.presentation.serializers import (
+ ExperimentBasicSerializer,
+ ExperimentSerializer,
+ )
+
+ basic = ExperimentBasicSerializer()
+ full = ExperimentSerializer()
+ shared = set(basic.fields.keys()) & set(full.fields.keys())
+ mismatches: list[str] = []
+ for name in sorted(shared):
+ b_field = basic.fields[name]
+ f_field = full.fields[name]
+ if b_field.read_only != f_field.read_only:
+ mismatches.append(f"{name}: read_only basic={b_field.read_only} full={f_field.read_only}")
+ if b_field.required != f_field.required:
+ mismatches.append(f"{name}: required basic={b_field.required} full={f_field.required}")
+ self.assertFalse(
+ mismatches,
+ "Shared fields have mismatched read_only/required between serializers:\n" + "\n".join(mismatches),
+ )
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 628f2d251f1c..18958ed3681f 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -283,16 +283,6 @@ export interface ExperimentRunningTimeCalculationApi {
recommended_sample_size?: number | null
}
-export interface ExperimentToSavedMetricApi {
- readonly id: number
- experiment: number
- saved_metric: number
- metadata?: unknown
- readonly created_at: string
- readonly query: unknown
- readonly name: string
-}
-
/**
* * `web` - web
* * `product` - product
@@ -304,6 +294,130 @@ export const ExperimentTypeEnumApi = {
Product: 'product',
} as const
+/**
+ * * `won` - won
+ * * `lost` - lost
+ * * `inconclusive` - inconclusive
+ * * `stopped_early` - stopped_early
+ * * `invalid` - invalid
+ */
+export type ConclusionEnumApi = (typeof ConclusionEnumApi)[keyof typeof ConclusionEnumApi]
+
+export const ConclusionEnumApi = {
+ Won: 'won',
+ Lost: 'lost',
+ Inconclusive: 'inconclusive',
+ StoppedEarly: 'stopped_early',
+ Invalid: 'invalid',
+} as const
+
+export type ExperimentStatusEnumApi = (typeof ExperimentStatusEnumApi)[keyof typeof ExperimentStatusEnumApi]
+
+export const ExperimentStatusEnumApi = {
+ Draft: 'draft',
+ Running: 'running',
+ Paused: 'paused',
+ Stopped: 'stopped',
+} as const
+
+/**
+ * Lightweight, read-only serializer for the experiment list endpoint.
+ *
+ * The list view (and the MCP list tool) render only the scalar and feature-flag fields
+ * shared via ``ExperimentBaseSerializer`` — never the metric definitions. Omitting
+ * ``metrics``/``metrics_secondary``/``saved_metrics`` lets the list query defer the large
+ * JSON columns and skip the saved-metric prefetch plus per-row fingerprinting; that work
+ * belongs to the detail response served by ``ExperimentSerializer``.
+ *
+ * Because the metric fields, the write-side machinery, and the action-name-refreshing
+ * ``to_representation`` all live on ``ExperimentSerializer`` rather than the shared base,
+ * this serializer needs no overrides: it gets DRF's default ``get_fields`` (no write-only
+ * ``holdout_id`` to configure), default ``to_representation`` (no metrics to normalize), and
+ * a plain ``ListSerializer`` that never touches the deferred columns. See
+ * ``EnterpriseExperimentsViewSet.safely_get_queryset``.
+ */
+export interface ExperimentBasicApi {
+ readonly id: number
+ /**
+ * Name of the experiment.
+ * @maxLength 400
+ */
+ name: string
+ /**
+ * Description of the experiment hypothesis and expected outcomes.
+ * @maxLength 3000
+ * @nullable
+ */
+ description?: string | null
+ /** @nullable */
+ start_date?: string | null
+ /** @nullable */
+ end_date?: string | null
+ /** Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible. */
+ feature_flag_key: string
+ readonly feature_flag: MinimalFeatureFlagApi
+ readonly holdout: ExperimentHoldoutApi
+ /** @nullable */
+ readonly exposure_cohort: number | null
+ /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded). The running-time calculator keys (`minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `exposure_estimate_config`) are deprecated here — prefer `running_time_calculation`. */
+ parameters?: ExperimentParametersApi | null
+ /** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window. */
+ running_time_calculation?: ExperimentRunningTimeCalculationApi | null
+ /** Whether the experiment is archived. */
+ archived?: boolean
+ /** @nullable */
+ deleted?: boolean | null
+ readonly created_by: UserBasicApi
+ readonly created_at: string
+ readonly updated_at: string
+ /** Experiment type: web for frontend UI changes, product for backend/API changes.
+ *
+ * * `web` - web
+ * * `product` - product */
+ type?: ExperimentTypeEnumApi | null
+ /** Experiment conclusion: won, lost, inconclusive, stopped_early, or invalid.
+ *
+ * * `won` - won
+ * * `lost` - lost
+ * * `inconclusive` - inconclusive
+ * * `stopped_early` - stopped_early
+ * * `invalid` - invalid */
+ conclusion?: ConclusionEnumApi | null
+ /**
+ * Comment about the experiment conclusion.
+ * @nullable
+ */
+ conclusion_comment?: string | null
+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */
+ readonly status: ExperimentStatusEnumApi
+ /** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
+ readonly is_legacy: boolean
+ /**
+ * The effective access level the user has for this object
+ * @nullable
+ */
+ readonly user_access_level: string | null
+}
+
+export interface PaginatedExperimentBasicListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: ExperimentBasicApi[]
+}
+
+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 Kind1Api = (typeof Kind1Api)[keyof typeof Kind1Api]
export const Kind1Api = {
@@ -514,33 +628,12 @@ export interface ExperimentApiMetricApi {
export type _ExperimentApiMetricsListApi = ExperimentApiMetricApi[]
/**
- * * `won` - won
- * * `lost` - lost
- * * `inconclusive` - inconclusive
- * * `stopped_early` - stopped_early
- * * `invalid` - invalid
- */
-export type ConclusionEnumApi = (typeof ConclusionEnumApi)[keyof typeof ConclusionEnumApi]
-
-export const ConclusionEnumApi = {
- Won: 'won',
- Lost: 'lost',
- Inconclusive: 'inconclusive',
- StoppedEarly: 'stopped_early',
- Invalid: 'invalid',
-} as const
-
-export type ExperimentStatusEnumApi = (typeof ExperimentStatusEnumApi)[keyof typeof ExperimentStatusEnumApi]
-
-export const ExperimentStatusEnumApi = {
- Draft: 'draft',
- Running: 'running',
- Paused: 'paused',
- Stopped: 'stopped',
-} as const
-
-/**
- * Mixin for serializers to add user access control fields
+ * Full experiment representation for the detail, create, and update endpoints.
+ *
+ * Extends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric
+ * definitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side
+ * fields, and refreshes stale action names while serializing. The list endpoint uses the
+ * leaner ``ExperimentBasicSerializer`` instead.
*/
export interface ExperimentApi {
readonly id: number
@@ -625,6 +718,8 @@ export interface ExperimentApi {
update_feature_flag_params?: boolean
/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */
readonly status: ExperimentStatusEnumApi
+ /** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
+ readonly is_legacy: boolean
/**
* The effective access level the user has for this object
* @nullable
@@ -632,17 +727,13 @@ export interface ExperimentApi {
readonly user_access_level: string | null
}
-export interface PaginatedExperimentListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: ExperimentApi[]
-}
-
/**
- * Mixin for serializers to add user access control fields
+ * Full experiment representation for the detail, create, and update endpoints.
+ *
+ * Extends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric
+ * definitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side
+ * fields, and refreshes stale action names while serializing. The list endpoint uses the
+ * leaner ``ExperimentBasicSerializer`` instead.
*/
export interface PatchedExperimentApi {
readonly id?: number
@@ -727,6 +818,8 @@ export interface PatchedExperimentApi {
update_feature_flag_params?: boolean
/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */
readonly status?: ExperimentStatusEnumApi
+ /** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
+ readonly is_legacy?: boolean
/**
* The effective access level the user has for this object
* @nullable
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 1883fb6508d1..dcc6beb9e82b 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -21,8 +21,8 @@ import type {
ExperimentsListParams,
ExperimentsPromptTemplatesRetrieve200Item,
ExperimentsTimeseriesResultsRetrieveParams,
+ PaginatedExperimentBasicListApi,
PaginatedExperimentHoldoutListApi,
- PaginatedExperimentListApi,
PaginatedExperimentSavedMetricListApi,
PatchedExperimentApi,
PatchedExperimentHoldoutApi,
@@ -293,8 +293,8 @@ export const experimentsList = async (
projectId: string,
params?: ExperimentsListParams,
options?: RequestInit
-): Promise<PaginatedExperimentListApi> => {
- return apiMutator<PaginatedExperimentListApi>(getExperimentsListUrl(projectId, params), {
+): Promise<PaginatedExperimentBasicListApi> => {
+ return apiMutator<PaginatedExperimentBasicListApi>(getExperimentsListUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b7d67ba5c754..372b64c3aa2f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20414,7 +20414,12 @@ export namespace Schemas {
} as const;
/**
- * Mixin for serializers to add user access control fields
+ * Full experiment representation for the detail, create, and update endpoints.
+ *
+ * Extends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric
+ * definitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side
+ * fields, and refreshes stale action names while serializing. The list endpoint uses the
+ * leaner ``ExperimentBasicSerializer`` instead.
*/
export interface Experiment {
readonly id: number;
@@ -20499,6 +20504,87 @@ export namespace Schemas {
update_feature_flag_params?: boolean;
/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */
readonly status: ExperimentStatusEnum;
+ /** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
+ readonly is_legacy: boolean;
+ /**
+ * The effective access level the user has for this object
+ * @nullable
+ */
+ readonly user_access_level: string | null;
+ }
+
+ /**
+ * Lightweight, read-only serializer for the experiment list endpoint.
+ *
+ * The list view (and the MCP list tool) render only the scalar and feature-flag fields
+ * shared via ``ExperimentBaseSerializer`` — never the metric definitions. Omitting
+ * ``metrics``/``metrics_secondary``/``saved_metrics`` lets the list query defer the large
+ * JSON columns and skip the saved-metric prefetch plus per-row fingerprinting; that work
+ * belongs to the detail response served by ``ExperimentSerializer``.
+ *
+ * Because the metric fields, the write-side machinery, and the action-name-refreshing
+ * ``to_representation`` all live on ``ExperimentSerializer`` rather than the shared base,
+ * this serializer needs no overrides: it gets DRF's default ``get_fields`` (no write-only
+ * ``holdout_id`` to configure), default ``to_representation`` (no metrics to normalize), and
+ * a plain ``ListSerializer`` that never touches the deferred columns. See
+ * ``EnterpriseExperimentsViewSet.safely_get_queryset``.
+ */
+ export interface ExperimentBasic {
+ readonly id: number;
+ /**
+ * Name of the experiment.
+ * @maxLength 400
+ */
+ name: string;
+ /**
+ * Description of the experiment hypothesis and expected outcomes.
+ * @maxLength 3000
+ * @nullable
+ */
+ description?: string | null;
+ /** @nullable */
+ start_date?: string | null;
+ /** @nullable */
+ end_date?: string | null;
+ /** Unique key for the experiment's feature flag. Letters, numbers, hyphens, and underscores only. Search existing flags with the feature-flag-get-all tool first — reuse an existing flag when possible. */
+ feature_flag_key: string;
+ readonly feature_flag: MinimalFeatureFlag;
+ readonly holdout: ExperimentHoldout;
+ /** @nullable */
+ readonly exposure_cohort: number | null;
+ /** Experiment parameters JSON. Supported keys include `feature_flag_variants`, `rollout_percentage`, `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `custom_exposure_filter`, and `excluded_variants` (list of variant keys to drop from statistical analysis; the baseline variant and holdout pseudo-variants cannot be excluded). The running-time calculator keys (`minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, `exposure_estimate_config`) are deprecated here — prefer `running_time_calculation`. */
+ parameters?: ExperimentParameters | null;
+ /** Running-time calculator state: `minimum_detectable_effect`, `recommended_running_time`, `recommended_sample_size`, and `exposure_estimate_config`. Canonical home for these keys, which historically lived in `parameters`; values are kept in sync with `parameters` during the deprecation window. */
+ running_time_calculation?: ExperimentRunningTimeCalculation | null;
+ /** Whether the experiment is archived. */
+ archived?: boolean;
+ /** @nullable */
+ deleted?: boolean | null;
+ readonly created_by: UserBasic;
+ readonly created_at: string;
+ readonly updated_at: string;
+ /** Experiment type: web for frontend UI changes, product for backend/API changes.
+ *
+ * * `web` - web
+ * * `product` - product */
+ type?: ExperimentTypeEnum | null;
+ /** Experiment conclusion: won, lost, inconclusive, stopped_early, or invalid.
+ *
+ * * `won` - won
+ * * `lost` - lost
+ * * `inconclusive` - inconclusive
+ * * `stopped_early` - stopped_early
+ * * `invalid` - invalid */
+ conclusion?: ConclusionEnum | null;
+ /**
+ * Comment about the experiment conclusion.
+ * @nullable
+ */
+ conclusion_comment?: string | null;
+ /** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */
+ readonly status: ExperimentStatusEnum;
+ /** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
+ readonly is_legacy: boolean;
/**
* The effective access level the user has for this object
* @nullable
@@ -29494,22 +29580,22 @@ export namespace Schemas {
results: EventSchema[];
}
- export interface PaginatedExperimentHoldoutList {
+ export interface PaginatedExperimentBasicList {
count: number;
/** @nullable */
next?: string | null;
/** @nullable */
previous?: string | null;
- results: ExperimentHoldout[];
+ results: ExperimentBasic[];
}
- export interface PaginatedExperimentList {
+ export interface PaginatedExperimentHoldoutList {
count: number;
/** @nullable */
next?: string | null;
/** @nullable */
previous?: string | null;
- results: Experiment[];
+ results: ExperimentHoldout[];
}
export interface PaginatedExperimentSavedMetricList {
@@ -35119,7 +35205,12 @@ export namespace Schemas {
}
/**
- * Mixin for serializers to add user access control fields
+ * Full experiment representation for the detail, create, and update endpoints.
+ *
+ * Extends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric
+ * definitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side
+ * fields, and refreshes stale action names while serializing. The list endpoint uses the
+ * leaner ``ExperimentBasicSerializer`` instead.
*/
export interface PatchedExperiment {
readonly id?: number;
@@ -35204,6 +35295,8 @@ export namespace Schemas {
update_feature_flag_params?: boolean;
/** Experiment lifecycle state: 'draft' (not yet launched), 'running' (launched with active feature flag), 'paused' (running with feature flag deactivated — virtual state derived from feature_flag.active, not stored), 'stopped' (ended). */
readonly status?: ExperimentStatusEnum;
+ /** Whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery or ExperimentFunnelsQuery). Used to flag legacy experiments and gate actions that don't support them, such as duplicate and copy-to-project. */
+ readonly is_legacy?: boolean;
/**
* The effective access level the user has for this object
* @nullable
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 16699868440d..cb1dfb145cc2 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -2512,7 +2512,9 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod
'When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts.'
),
})
- .describe('Mixin for serializers to add user access control fields')
+ .describe(
+ 'Full experiment representation for the detail, create, and update endpoints.\n\nExtends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric\ndefinitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side\nfields, and refreshes stale action names while serializing. The list endpoint uses the\nleaner ``ExperimentBasicSerializer`` instead.'
+ )
/**
* Retrieve a single experiment by ID, including its current status, metrics, feature flag, and results metadata.
@@ -4885,7 +4887,9 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod
'When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts.'
),
})
- .describe('Mixin for serializers to add user access control fields')
+ .describe(
+ 'Full experiment representation for the detail, create, and update endpoints.\n\nExtends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric\ndefinitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side\nfields, and refreshes stale action names while serializing. The list endpoint uses the\nleaner ``ExperimentBasicSerializer`` instead.'
+ )
/**
* Hard delete of this model is not allowed. Use a patch API call to set "deleted" to true
@@ -7302,7 +7306,9 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod
'When true, sync feature flag configuration from parameters to the linked feature flag. Draft experiments always sync regardless of update_feature_flag_params, so only required for non-drafts.'
),
})
- .describe('Mixin for serializers to add user access control fields')
+ .describe(
+ 'Full experiment representation for the detail, create, and update endpoints.\n\nExtends the shared read-side fields in ``ExperimentBaseSerializer`` with the metric\ndefinitions (``metrics``/``metrics_secondary``/``saved_metrics``) and the write-side\nfields, and refreshes stale action names while serializing. The list endpoint uses the\nleaner ``ExperimentBasicSerializer`` instead.'
+ )
/**
* End a running experiment without shipping a variant.
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 1eae6325fc57..0331fd7ec7b3 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -432,13 +432,16 @@ const ExperimentListSchema = ExperimentsListQueryParams.extend({
feature_flag_id: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['feature_flag_id']).optional(),
})
-const experimentList = (): ToolBase<typeof ExperimentListSchema, WithPostHogUrl<Schemas.PaginatedExperimentList>> =>
+const experimentList = (): ToolBase<
+ typeof ExperimentListSchema,
+ WithPostHogUrl<Schemas.PaginatedExperimentBasicList>
+> =>
withUiApp('experiment-list', {
name: 'experiment-list',
schema: ExperimentListSchema,
handler: async (context: Context, params: z.infer<typeof ExperimentListSchema>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedExperimentList>({
+ const result = await context.api.request<Schemas.PaginatedExperimentBasicList>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/`,
query: {