Skip to content

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

fix(experiments/mcp): Fix pydantic pointing agents to the wrong class for metric types (#58385)

Marcel Poelker125fcdae2676
diff --git a/frontend/bin/build-validators.mjs b/frontend/bin/build-validators.mjs
index 458b5a42da95..d89e9e23d069 100644
--- a/frontend/bin/build-validators.mjs
+++ b/frontend/bin/build-validators.mjs
@@ -13,6 +13,11 @@ const schema = JSON.parse(fs.readFileSync(inputPath, 'utf-8'))
const ajv = new Ajv({
allowUnionTypes: true,
code: { source: true, esm: true },
+ // `discriminator` is an OpenAPI keyword used by ts-json-schema-generator (and consumed
+ // by datamodel-codegen to emit Pydantic `Field(discriminator=...)`). It carries routing
+ // information for union types, not validation rules — declare it as a no-op so ajv's
+ // strict mode doesn't reject schemas that use it.
+ keywords: [{ keyword: 'discriminator' }],
})
// Add the main schema
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index f9720c3f9477..a046d2a1ae9b 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -17559,20 +17559,7 @@
"type": "object"
},
"ExperimentMetric": {
- "anyOf": [
- {
- "$ref": "#/definitions/ExperimentMeanMetric"
- },
- {
- "$ref": "#/definitions/ExperimentFunnelMetric"
- },
- {
- "$ref": "#/definitions/ExperimentRatioMetric"
- },
- {
- "$ref": "#/definitions/ExperimentRetentionMetric"
- }
- ]
+ "$ref": "#/definitions/ExperimentMetricUnion"
},
"ExperimentMetricBaseProperties": {
"additionalProperties": false,
@@ -17742,6 +17729,27 @@
}
]
},
+ "ExperimentMetricUnion": {
+ "discriminator": {
+ "propertyName": "metric_type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/definitions/ExperimentMeanMetric"
+ },
+ {
+ "$ref": "#/definitions/ExperimentFunnelMetric"
+ },
+ {
+ "$ref": "#/definitions/ExperimentRatioMetric"
+ },
+ {
+ "$ref": "#/definitions/ExperimentRetentionMetric"
+ }
+ ],
+ "required": ["metric_type"],
+ "type": "object"
+ },
"ExperimentParameters": {
"additionalProperties": false,
"properties": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index d642ba63c01d..5741f0fcd00b 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3615,12 +3615,21 @@ export type ExperimentMetricTypeProps =
| ExperimentRatioMetricTypeProps
| ExperimentRetentionMetricTypeProps
-export type ExperimentMetric =
+// Named separately from `ExperimentMetric` so the JSDoc `@discriminator` tag below
+// can attach without colliding with the `NodeKind.ExperimentMetric` enum value
+// (which trips ts-json-schema-generator's deduplication). The alias is the public
+// type — callers continue to use `ExperimentMetric`.
+/**
+ * @discriminator metric_type
+ */
+export type ExperimentMetricUnion =
| ExperimentMeanMetric
| ExperimentFunnelMetric
| ExperimentRatioMetric
| ExperimentRetentionMetric
+export type ExperimentMetric = ExperimentMetricUnion
+
export interface ExperimentQuery extends DataNode<ExperimentQueryResponse> {
kind: NodeKind.ExperimentQuery
metric: ExperimentMetric
diff --git a/frontend/src/queries/validators.js b/frontend/src/queries/validators.js
index 6ed375078957..5525579b92c2 100644
--- a/frontend/src/queries/validators.js
+++ b/frontend/src/queries/validators.js
@@ -5881,12 +5881,15 @@ function validate77(data, { instancePath = '', parentData, parentDataProperty, r
}
export const ExperimentMetric = validate78
const schema62 = {
- anyOf: [
+ discriminator: { propertyName: 'metric_type' },
+ oneOf: [
{ $ref: '#/definitions/ExperimentMeanMetric' },
{ $ref: '#/definitions/ExperimentFunnelMetric' },
{ $ref: '#/definitions/ExperimentRatioMetric' },
{ $ref: '#/definitions/ExperimentRetentionMetric' },
],
+ required: ['metric_type'],
+ type: 'object',
}
const schema63 = {
additionalProperties: false,
@@ -11899,49 +11902,71 @@ function validate120(data, { instancePath = '', parentData, parentDataProperty,
function validate78(data, { instancePath = '', parentData, parentDataProperty, rootData = data } = {}) {
let vErrors = null
let errors = 0
- const _errs0 = errors
- let valid0 = false
const _errs1 = errors
+ let valid0 = false
+ let passing0 = null
+ const _errs2 = errors
if (!validate79(data, { instancePath, parentData, parentDataProperty, rootData })) {
vErrors = vErrors === null ? validate79.errors : vErrors.concat(validate79.errors)
errors = vErrors.length
}
- var _valid0 = _errs1 === errors
- valid0 = valid0 || _valid0
- if (!valid0) {
- const _errs2 = errors
- if (!validate107(data, { instancePath, parentData, parentDataProperty, rootData })) {
- vErrors = vErrors === null ? validate107.errors : vErrors.concat(validate107.errors)
+ var _valid0 = _errs2 === errors
+ if (_valid0) {
+ valid0 = true
+ passing0 = 0
+ }
+ const _errs3 = errors
+ if (!validate107(data, { instancePath, parentData, parentDataProperty, rootData })) {
+ vErrors = vErrors === null ? validate107.errors : vErrors.concat(validate107.errors)
+ errors = vErrors.length
+ }
+ var _valid0 = _errs3 === errors
+ if (_valid0 && valid0) {
+ valid0 = false
+ passing0 = [passing0, 1]
+ } else {
+ if (_valid0) {
+ valid0 = true
+ passing0 = 1
+ }
+ const _errs4 = errors
+ if (!validate115(data, { instancePath, parentData, parentDataProperty, rootData })) {
+ vErrors = vErrors === null ? validate115.errors : vErrors.concat(validate115.errors)
errors = vErrors.length
}
- var _valid0 = _errs2 === errors
- valid0 = valid0 || _valid0
- if (!valid0) {
- const _errs3 = errors
- if (!validate115(data, { instancePath, parentData, parentDataProperty, rootData })) {
- vErrors = vErrors === null ? validate115.errors : vErrors.concat(validate115.errors)
+ var _valid0 = _errs4 === errors
+ if (_valid0 && valid0) {
+ valid0 = false
+ passing0 = [passing0, 2]
+ } else {
+ if (_valid0) {
+ valid0 = true
+ passing0 = 2
+ }
+ const _errs5 = errors
+ if (!validate120(data, { instancePath, parentData, parentDataProperty, rootData })) {
+ vErrors = vErrors === null ? validate120.errors : vErrors.concat(validate120.errors)
errors = vErrors.length
}
- var _valid0 = _errs3 === errors
- valid0 = valid0 || _valid0
- if (!valid0) {
- const _errs4 = errors
- if (!validate120(data, { instancePath, parentData, parentDataProperty, rootData })) {
- vErrors = vErrors === null ? validate120.errors : vErrors.concat(validate120.errors)
- errors = vErrors.length
+ var _valid0 = _errs5 === errors
+ if (_valid0 && valid0) {
+ valid0 = false
+ passing0 = [passing0, 3]
+ } else {
+ if (_valid0) {
+ valid0 = true
+ passing0 = 3
}
- var _valid0 = _errs4 === errors
- valid0 = valid0 || _valid0
}
}
}
if (!valid0) {
const err0 = {
instancePath,
- schemaPath: '#/anyOf',
- keyword: 'anyOf',
- params: {},
- message: 'must match a schema in anyOf',
+ schemaPath: '#/oneOf',
+ keyword: 'oneOf',
+ params: { passingSchemas: passing0 },
+ message: 'must match exactly one schema in oneOf',
}
if (vErrors === null) {
vErrors = [err0]
@@ -11952,15 +11977,43 @@ function validate78(data, { instancePath = '', parentData, parentDataProperty, r
validate78.errors = vErrors
return false
} else {
- errors = _errs0
+ errors = _errs1
if (vErrors !== null) {
- if (_errs0) {
- vErrors.length = _errs0
+ if (_errs1) {
+ vErrors.length = _errs1
} else {
vErrors = null
}
}
}
+ if (errors === 0) {
+ if (data && typeof data == 'object' && !Array.isArray(data)) {
+ let missing0
+ if (data.metric_type === undefined && (missing0 = 'metric_type')) {
+ validate78.errors = [
+ {
+ instancePath,
+ schemaPath: '#/required',
+ keyword: 'required',
+ params: { missingProperty: missing0 },
+ message: "must have required property '" + missing0 + "'",
+ },
+ ]
+ return false
+ }
+ } else {
+ validate78.errors = [
+ {
+ instancePath,
+ schemaPath: '#/type',
+ keyword: 'type',
+ params: { type: 'object' },
+ message: 'must be object',
+ },
+ ]
+ return false
+ }
+ }
validate78.errors = vErrors
return errors === 0
}
diff --git a/posthog/schema.py b/posthog/schema.py
index 31ea77df530d..f00ac7b066f8 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -20794,12 +20794,6 @@ class ExperimentMeanMetricTypeProps(BaseModel):
upper_bound_percentile: float | None = None
-class ExperimentMetric(
- RootModel[ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric]
-):
- root: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
-
-
class ExperimentMetricTypeProps(
RootModel[
ExperimentMeanMetricTypeProps
@@ -20816,38 +20810,6 @@ class ExperimentMetricTypeProps(
)
-class ExperimentQueryResponse(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- baseline: ExperimentStatsBaseValidated | None = None
- breakdown_results: list[ExperimentBreakdownResult] | None = Field(
- default=None,
- description=(
- "Results grouped by breakdown value. When present, baseline and variant_results contain aggregated data."
- ),
- )
- clickhouse_sql: str | None = None
- credible_intervals: dict[str, list[float]] | None = None
- hogql: str | None = None
- insight: list[dict[str, Any]] | None = None
- is_precomputed: bool | None = Field(
- default=None,
- description="Whether exposures were served from the precomputation system",
- )
- kind: Literal["ExperimentQuery"] = "ExperimentQuery"
- metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric | None = (
- None
- )
- p_value: float | None = None
- probability: dict[str, float] | None = None
- significance_code: ExperimentSignificanceCode | None = None
- significant: bool | None = None
- stats_version: int | None = None
- variant_results: list[ExperimentVariantResultFrequentist] | list[ExperimentVariantResultBayesian] | None = None
- variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats] | None = None
-
-
class GroupNode(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -21206,22 +21168,6 @@ class InsightsQueryBaseTrendsQueryResponse(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class LegacyExperimentQueryResponse(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- credible_intervals: dict[str, list[float]]
- insight: list[dict[str, Any]]
- kind: Literal["ExperimentQuery"] = "ExperimentQuery"
- metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
- p_value: float
- probability: dict[str, float]
- significance_code: ExperimentSignificanceCode
- significant: bool
- stats_version: int | None = None
- variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats]
-
-
class LifecycleQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -21353,38 +21299,6 @@ class LogsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class QueryResponseAlternative20(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- baseline: ExperimentStatsBaseValidated | None = None
- breakdown_results: list[ExperimentBreakdownResult] | None = Field(
- default=None,
- description=(
- "Results grouped by breakdown value. When present, baseline and variant_results contain aggregated data."
- ),
- )
- clickhouse_sql: str | None = None
- credible_intervals: dict[str, list[float]] | None = None
- hogql: str | None = None
- insight: list[dict[str, Any]] | None = None
- is_precomputed: bool | None = Field(
- default=None,
- description="Whether exposures were served from the precomputation system",
- )
- kind: Literal["ExperimentQuery"] = "ExperimentQuery"
- metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric | None = (
- None
- )
- p_value: float | None = None
- probability: dict[str, float] | None = None
- significance_code: ExperimentSignificanceCode | None = None
- significant: bool | None = None
- stats_version: int | None = None
- variant_results: list[ExperimentVariantResultFrequentist] | list[ExperimentVariantResultBayesian] | None = None
- variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats] | None = None
-
-
class SessionsQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -21578,76 +21492,6 @@ class TrendsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class NamedArgs1(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
-
-
-class IsExperimentFunnelMetric(BaseModel):
- namedArgs: NamedArgs1 | None = None
-
-
-class IsExperimentMeanMetric(BaseModel):
- namedArgs: NamedArgs1 | None = None
-
-
-class IsExperimentRatioMetric(BaseModel):
- namedArgs: NamedArgs1 | None = None
-
-
-class IsExperimentRetentionMetric(BaseModel):
- namedArgs: NamedArgs1 | None = None
-
-
-class CachedExperimentQueryResponse(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- baseline: ExperimentStatsBaseValidated | None = None
- breakdown_results: list[ExperimentBreakdownResult] | None = Field(
- default=None,
- description=(
- "Results grouped by breakdown value. When present, baseline and variant_results contain aggregated data."
- ),
- )
- cache_key: str
- cache_target_age: AwareDatetime | None = None
- calculation_trigger: str | None = Field(
- default=None,
- description=("What triggered the calculation of the query, leave empty if user/immediate"),
- )
- clickhouse_sql: str | None = None
- credible_intervals: dict[str, list[float]] | None = None
- hogql: str | None = None
- insight: list[dict[str, Any]] | None = None
- is_cached: bool
- is_precomputed: bool | None = Field(
- default=None,
- description="Whether exposures were served from the precomputation system",
- )
- kind: Literal["ExperimentQuery"] = "ExperimentQuery"
- last_refresh: AwareDatetime
- metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric | None = (
- None
- )
- next_allowed_client_refresh: AwareDatetime
- p_value: float | None = None
- probability: dict[str, float] | None = None
- query_metadata: dict[str, Any] | None = None
- query_status: QueryStatus | None = Field(
- default=None,
- description=("Query status indicates whether next to the provided data, a query is still running."),
- )
- significance_code: ExperimentSignificanceCode | None = None
- significant: bool | None = None
- stats_version: int | None = None
- timezone: str
- variant_results: list[ExperimentVariantResultFrequentist] | list[ExperimentVariantResultBayesian] | None = None
- variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats] | None = None
-
-
class CachedExperimentTrendsQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -21680,37 +21524,6 @@ class CachedExperimentTrendsQueryResponse(BaseModel):
variants: list[ExperimentVariantTrendsBaseStats]
-class CachedLegacyExperimentQueryResponse(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- cache_key: str
- cache_target_age: AwareDatetime | None = None
- calculation_trigger: str | None = Field(
- default=None,
- description=("What triggered the calculation of the query, leave empty if user/immediate"),
- )
- credible_intervals: dict[str, list[float]]
- insight: list[dict[str, Any]]
- is_cached: bool
- kind: Literal["ExperimentQuery"] = "ExperimentQuery"
- last_refresh: AwareDatetime
- metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
- next_allowed_client_refresh: AwareDatetime
- p_value: float
- probability: dict[str, float]
- query_metadata: dict[str, Any] | None = None
- query_status: QueryStatus | None = Field(
- default=None,
- description=("Query status indicates whether next to the provided data, a query is still running."),
- )
- significance_code: ExperimentSignificanceCode
- significant: bool
- stats_version: int | None = None
- timezone: str
- variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats]
-
-
class Response24(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -21763,35 +21576,44 @@ class EndpointRequest(BaseModel):
)
-class ExperimentMetricTimeseries(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
+class ExperimentMetric(
+ RootModel[ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric]
+):
+ root: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric = Field(
+ ..., discriminator="metric_type"
)
- computed_at: str | None = None
- created_at: str
- errors: dict[str, str] | None = None
- experiment_id: float
- metric_uuid: str
- recalculation_created_at: str | None = None
- recalculation_status: str | None = None
- status: Status
- timeseries: dict[str, ExperimentQueryResponse] | None = None
- updated_at: str
-class ExperimentQuery(BaseModel):
+class ExperimentQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
- experiment_id: int | None = None
+ baseline: ExperimentStatsBaseValidated | None = None
+ breakdown_results: list[ExperimentBreakdownResult] | None = Field(
+ default=None,
+ description=(
+ "Results grouped by breakdown value. When present, baseline and variant_results contain aggregated data."
+ ),
+ )
+ clickhouse_sql: str | None = None
+ credible_intervals: dict[str, list[float]] | None = None
+ hogql: str | None = None
+ insight: list[dict[str, Any]] | None = None
+ is_precomputed: bool | None = Field(
+ default=None,
+ description="Whether exposures were served from the precomputation system",
+ )
kind: Literal["ExperimentQuery"] = "ExperimentQuery"
- metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
- name: str | None = None
- precomputation_mode: PrecomputationMode | None = None
- response: ExperimentQueryResponse | None = None
- tags: QueryLogTags | None = None
- version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+ metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric | None = (
+ Field(default=None, discriminator="metric_type")
+ )
+ p_value: float | None = None
+ probability: dict[str, float] | None = None
+ significance_code: ExperimentSignificanceCode | None = None
+ significant: bool | None = None
+ stats_version: int | None = None
+ variant_results: list[ExperimentVariantResultFrequentist] | list[ExperimentVariantResultBayesian] | None = None
+ variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats] | None = None
class ExperimentTrendsQueryResponse(BaseModel):
@@ -21865,6 +21687,24 @@ class FunnelsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class LegacyExperimentQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ credible_intervals: dict[str, list[float]]
+ insight: list[dict[str, Any]]
+ kind: Literal["ExperimentQuery"] = "ExperimentQuery"
+ metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric = Field(
+ ..., discriminator="metric_type"
+ )
+ p_value: float
+ probability: dict[str, float]
+ significance_code: ExperimentSignificanceCode
+ significant: bool
+ stats_version: int | None = None
+ variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats]
+
+
class QueryResponseAlternative18(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -21898,6 +21738,38 @@ class QueryResponseAlternative19(BaseModel):
variants: list[ExperimentVariantTrendsBaseStats]
+class QueryResponseAlternative20(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ baseline: ExperimentStatsBaseValidated | None = None
+ breakdown_results: list[ExperimentBreakdownResult] | None = Field(
+ default=None,
+ description=(
+ "Results grouped by breakdown value. When present, baseline and variant_results contain aggregated data."
+ ),
+ )
+ clickhouse_sql: str | None = None
+ credible_intervals: dict[str, list[float]] | None = None
+ hogql: str | None = None
+ insight: list[dict[str, Any]] | None = None
+ is_precomputed: bool | None = Field(
+ default=None,
+ description="Whether exposures were served from the precomputation system",
+ )
+ kind: Literal["ExperimentQuery"] = "ExperimentQuery"
+ metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric | None = (
+ Field(default=None, discriminator="metric_type")
+ )
+ p_value: float | None = None
+ probability: dict[str, float] | None = None
+ significance_code: ExperimentSignificanceCode | None = None
+ significant: bool | None = None
+ stats_version: int | None = None
+ variant_results: list[ExperimentVariantResultFrequentist] | list[ExperimentVariantResultBayesian] | None = None
+ variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats] | None = None
+
+
class QueryResponseAlternative62(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -22160,6 +22032,31 @@ class VisualizationBlock(BaseModel):
type: Literal["visualization"] = "visualization"
+class NamedArgs1(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric = Field(
+ ..., discriminator="metric_type"
+ )
+
+
+class IsExperimentFunnelMetric(BaseModel):
+ namedArgs: NamedArgs1 | None = None
+
+
+class IsExperimentMeanMetric(BaseModel):
+ namedArgs: NamedArgs1 | None = None
+
+
+class IsExperimentRatioMetric(BaseModel):
+ namedArgs: NamedArgs1 | None = None
+
+
+class IsExperimentRetentionMetric(BaseModel):
+ namedArgs: NamedArgs1 | None = None
+
+
class CachedExperimentFunnelsQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -22191,6 +22088,86 @@ class CachedExperimentFunnelsQueryResponse(BaseModel):
variants: list[ExperimentVariantFunnelsBaseStats]
+class CachedExperimentQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ baseline: ExperimentStatsBaseValidated | None = None
+ breakdown_results: list[ExperimentBreakdownResult] | None = Field(
+ default=None,
+ description=(
+ "Results grouped by breakdown value. When present, baseline and variant_results contain aggregated data."
+ ),
+ )
+ cache_key: str
+ cache_target_age: AwareDatetime | None = None
+ calculation_trigger: str | None = Field(
+ default=None,
+ description=("What triggered the calculation of the query, leave empty if user/immediate"),
+ )
+ clickhouse_sql: str | None = None
+ credible_intervals: dict[str, list[float]] | None = None
+ hogql: str | None = None
+ insight: list[dict[str, Any]] | None = None
+ is_cached: bool
+ is_precomputed: bool | None = Field(
+ default=None,
+ description="Whether exposures were served from the precomputation system",
+ )
+ kind: Literal["ExperimentQuery"] = "ExperimentQuery"
+ last_refresh: AwareDatetime
+ metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric | None = (
+ Field(default=None, discriminator="metric_type")
+ )
+ next_allowed_client_refresh: AwareDatetime
+ p_value: float | None = None
+ probability: dict[str, float] | None = None
+ query_metadata: dict[str, Any] | None = None
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ significance_code: ExperimentSignificanceCode | None = None
+ significant: bool | None = None
+ stats_version: int | None = None
+ timezone: str
+ variant_results: list[ExperimentVariantResultFrequentist] | list[ExperimentVariantResultBayesian] | None = None
+ variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats] | None = None
+
+
+class CachedLegacyExperimentQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ cache_key: str
+ cache_target_age: AwareDatetime | None = None
+ calculation_trigger: str | None = Field(
+ default=None,
+ description=("What triggered the calculation of the query, leave empty if user/immediate"),
+ )
+ credible_intervals: dict[str, list[float]]
+ insight: list[dict[str, Any]]
+ is_cached: bool
+ kind: Literal["ExperimentQuery"] = "ExperimentQuery"
+ last_refresh: AwareDatetime
+ metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric = Field(
+ ..., discriminator="metric_type"
+ )
+ next_allowed_client_refresh: AwareDatetime
+ p_value: float
+ probability: dict[str, float]
+ query_metadata: dict[str, Any] | None = None
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ significance_code: ExperimentSignificanceCode
+ significant: bool
+ stats_version: int | None = None
+ timezone: str
+ variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats]
+
+
class Response23(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -22225,44 +22202,6 @@ class DatabaseSchemaQueryResponse(BaseModel):
]
-class ExperimentActorsQuery(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- exposureConfig: ExperimentEventExposureConfig | ActionsNode | None = Field(
- default=None,
- description=(
- "Exposure configuration for filtering events. Defines when users were first exposed to the experiment."
- ),
- )
- featureFlagKey: str | None = Field(default=None, description="Feature flag key for breakdown filtering.")
- funnelStep: int | None = Field(
- default=None,
- description=(
- "Index of the step for which we want to get actors for, per experiment"
- " variant. Positive for converted persons, negative for dropped off"
- " persons."
- ),
- )
- funnelStepBreakdown: int | str | float | list[int | str | float] | None = Field(
- default=None,
- description=(
- "The variant key for filtering actors. For experiments, this filters by"
- " feature flag variant (e.g., 'control', 'test')."
- ),
- )
- includeRecordings: bool | None = None
- kind: Literal["ExperimentActorsQuery"] = "ExperimentActorsQuery"
- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
- multipleVariantHandling: MultipleVariantHandling | None = Field(
- default=None, description="How to handle users with multiple variant exposures."
- )
- response: ActorsQueryResponse | None = None
- source: ExperimentQuery
- tags: QueryLogTags | None = None
- version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-
-
class ExperimentFunnelsQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -22279,6 +22218,39 @@ class ExperimentFunnelsQueryResponse(BaseModel):
variants: list[ExperimentVariantFunnelsBaseStats]
+class ExperimentMetricTimeseries(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ computed_at: str | None = None
+ created_at: str
+ errors: dict[str, str] | None = None
+ experiment_id: float
+ metric_uuid: str
+ recalculation_created_at: str | None = None
+ recalculation_status: str | None = None
+ status: Status
+ timeseries: dict[str, ExperimentQueryResponse] | None = None
+ updated_at: str
+
+
+class ExperimentQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ experiment_id: int | None = None
+ kind: Literal["ExperimentQuery"] = "ExperimentQuery"
+ metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric = Field(
+ ..., discriminator="metric_type"
+ )
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ name: str | None = None
+ precomputation_mode: PrecomputationMode | None = None
+ response: ExperimentQueryResponse | None = None
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class ExperimentTrendsQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -22497,6 +22469,44 @@ class DocumentArtifactContent(BaseModel):
blocks: list[MarkdownBlock | VisualizationBlock | SessionReplayBlock | LoadingBlock | ErrorBlock]
+class ExperimentActorsQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ exposureConfig: ExperimentEventExposureConfig | ActionsNode | None = Field(
+ default=None,
+ description=(
+ "Exposure configuration for filtering events. Defines when users were first exposed to the experiment."
+ ),
+ )
+ featureFlagKey: str | None = Field(default=None, description="Feature flag key for breakdown filtering.")
+ funnelStep: int | None = Field(
+ default=None,
+ description=(
+ "Index of the step for which we want to get actors for, per experiment"
+ " variant. Positive for converted persons, negative for dropped off"
+ " persons."
+ ),
+ )
+ funnelStepBreakdown: int | str | float | list[int | str | float] | None = Field(
+ default=None,
+ description=(
+ "The variant key for filtering actors. For experiments, this filters by"
+ " feature flag variant (e.g., 'control', 'test')."
+ ),
+ )
+ includeRecordings: bool | None = None
+ kind: Literal["ExperimentActorsQuery"] = "ExperimentActorsQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ multipleVariantHandling: MultipleVariantHandling | None = Field(
+ default=None, description="How to handle users with multiple variant exposures."
+ )
+ response: ActorsQueryResponse | None = None
+ source: ExperimentQuery
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class ExperimentFunnelsQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
diff --git a/posthog/test/test_experiment_metric_discriminator.py b/posthog/test/test_experiment_metric_discriminator.py
new file mode 100644
index 000000000000..6c3ebac4730d
--- /dev/null
+++ b/posthog/test/test_experiment_metric_discriminator.py
@@ -0,0 +1,103 @@
+from django.test.testcases import SimpleTestCase
+
+from parameterized import parameterized
+from pydantic import ValidationError
+
+from posthog.schema import ExperimentMetric
+
+
+class TestExperimentMetricDiscriminator(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # Each payload uses the mean-metric shape (`source`) but declares a non-mean
+ # `metric_type`. A correctly-routed error must (a) start with the declared
+ # tag in the loc, and (b) name a field that is REQUIRED by the target class
+ # but missing here — proving Pydantic validated against the right shape,
+ # not just emitted the right tag prefix.
+ ("funnel_routes_to_funnel", "funnel", "series"),
+ ("ratio_routes_to_ratio", "ratio", "numerator"),
+ ("retention_routes_to_retention", "retention", "start_event"),
+ ]
+ )
+ def test_invalid_payload_routes_to_class_named_by_metric_type(
+ self, _name: str, metric_type: str, target_class_required_field: str
+ ) -> None:
+ payload = {"metric_type": metric_type, "source": {"kind": "EventsNode", "event": "x"}}
+
+ with self.assertRaises(ValidationError) as ctx:
+ ExperimentMetric.model_validate(payload)
+
+ errors = ctx.exception.errors()
+ assert errors, "expected at least one validation error"
+
+ for err in errors:
+ assert err["loc"][0] == metric_type, (
+ f"error loc[0] should be the discriminator tag {metric_type!r}, "
+ f"got {err['loc'][0]!r} — discriminator likely dropped"
+ )
+
+ # Positive routing check: the field the *target* class requires must appear as
+ # missing. An undiscriminated union would walk variants in order, fail on
+ # ExperimentMeanMetric's metric_type literal, and never reach this field.
+ missing_field_locs = {err["loc"] for err in errors if err["type"] == "missing"}
+ assert (metric_type, target_class_required_field) in missing_field_locs, (
+ f"expected missing-field error on ({metric_type!r}, {target_class_required_field!r}) "
+ f"to prove routing to the target class; got {missing_field_locs}"
+ )
+
+ assert "ExperimentMeanMetric" not in str(ctx.exception), (
+ "error should target the variant named by metric_type, not ExperimentMeanMetric — "
+ "discriminator likely dropped"
+ )
+
+ def test_unknown_metric_type_returns_clean_tag_error(self) -> None:
+ # Anything that isn't one of the four literals produces `union_tag_invalid` with
+ # the valid tag list, instead of cascading errors from every variant.
+ with self.assertRaises(ValidationError) as ctx:
+ ExperimentMetric.model_validate(
+ {"metric_type": "banana", "source": {"kind": "EventsNode", "event": "purchase"}}
+ )
+
+ errors = ctx.exception.errors()
+ assert len(errors) == 1
+ assert errors[0]["type"] == "union_tag_invalid"
+ expected_tags_str = errors[0]["ctx"]["expected_tags"]
+ for tag in ("mean", "funnel", "ratio", "retention"):
+ assert f"'{tag}'" in expected_tags_str, f"expected tag {tag!r} not found in {expected_tags_str!r}"
+
+ def test_missing_metric_type_returns_clean_tag_error(self) -> None:
+ with self.assertRaises(ValidationError) as ctx:
+ ExperimentMetric.model_validate({"source": {"kind": "EventsNode", "event": "purchase"}})
+
+ errors = ctx.exception.errors()
+ assert len(errors) == 1
+ assert errors[0]["type"] == "union_tag_not_found"
+
+ @parameterized.expand(
+ [
+ ("mean", {"metric_type": "mean", "source": {"kind": "EventsNode", "event": "purchase"}}),
+ ("funnel", {"metric_type": "funnel", "series": [{"kind": "EventsNode", "event": "view"}]}),
+ (
+ "ratio",
+ {
+ "metric_type": "ratio",
+ "numerator": {"kind": "EventsNode", "event": "revenue"},
+ "denominator": {"kind": "EventsNode", "event": "pageview"},
+ },
+ ),
+ (
+ "retention",
+ {
+ "metric_type": "retention",
+ "start_event": {"kind": "EventsNode", "event": "signup"},
+ "completion_event": {"kind": "EventsNode", "event": "activated"},
+ "retention_window_start": 0,
+ "retention_window_end": 7,
+ "retention_window_unit": "day",
+ "start_handling": "first_seen",
+ },
+ ),
+ ]
+ )
+ def test_valid_payload_per_metric_type_still_validates(self, _name: str, payload: dict) -> None:
+ ExperimentMetric.model_validate(payload)