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(funnels): discriminate FunnelsQuery.series union on kind (#70552)

Thomas Obermüller4d78e67b1128
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index c9518b19bac7..58b3b022fa5d 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -1036,19 +1036,6 @@
}
]
},
- "AnyEntityNode<FunnelsDataWarehouseNode>": {
- "anyOf": [
- {
- "$ref": "#/definitions/EventsNode"
- },
- {
- "$ref": "#/definitions/ActionsNode"
- },
- {
- "$ref": "#/definitions/FunnelsDataWarehouseNode"
- }
- ]
- },
"AnyEntityNode<LifecycleDataWarehouseNode>": {
"anyOf": [
{
@@ -24659,14 +24646,7 @@
"series": {
"description": "Events and actions to include",
"items": {
- "anyOf": [
- {
- "$ref": "#/definitions/AnyEntityNode%3CFunnelsDataWarehouseNode%3E"
- },
- {
- "$ref": "#/definitions/GroupNode"
- }
- ]
+ "$ref": "#/definitions/FunnelsQuerySeriesNode"
},
"type": "array"
},
@@ -24739,6 +24719,30 @@
"required": ["results"],
"type": "object"
},
+ "FunnelsQuerySeriesNode": {
+ "$ref": "#/definitions/FunnelsQuerySeriesNodeUnion"
+ },
+ "FunnelsQuerySeriesNodeUnion": {
+ "discriminator": {
+ "propertyName": "kind"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/definitions/EventsNode"
+ },
+ {
+ "$ref": "#/definitions/ActionsNode"
+ },
+ {
+ "$ref": "#/definitions/FunnelsDataWarehouseNode"
+ },
+ {
+ "$ref": "#/definitions/GroupNode"
+ }
+ ],
+ "required": ["kind"],
+ "type": "object"
+ },
"GenericCachedQueryResponse": {
"properties": {
"cache_key": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 5b8c0cf163c3..8fb8ff03a2f0 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1821,12 +1821,23 @@ export type FunnelsFilter = {
chartStyle?: ChartStyle
}
+// Named separately from `FunnelsQuerySeriesNode` so the JSDoc `@discriminator` tag
+// can attach without tripping ts-json-schema-generator's dedup (same workaround
+// pattern as `ExperimentMetricSourceUnion = ExperimentMetricSource`). The alias is
+// the public type — callers continue to use `FunnelsQuerySeriesNode`.
+/**
+ * @discriminator kind
+ */
+export type FunnelsQuerySeriesNodeUnion = EventsNode | ActionsNode | FunnelsDataWarehouseNode | GroupNode
+
+export type FunnelsQuerySeriesNode = FunnelsQuerySeriesNodeUnion
+
export interface FunnelsQuery extends InsightsQueryBase<FunnelsQueryResponse> {
kind: NodeKind.FunnelsQuery
/** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */
interval?: IntervalType
/** Events and actions to include */
- series: (AnyEntityNode<FunnelsDataWarehouseNode> | GroupNode)[]
+ series: FunnelsQuerySeriesNode[]
/** Properties specific to the funnels insight */
funnelsFilter?: FunnelsFilter
/** Breakdown of the events and actions */
diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel.py b/posthog/hogql_queries/insights/funnels/test/test_funnel.py
index 32e879764b0e..94b2af767ac0 100644
--- a/posthog/hogql_queries/insights/funnels/test/test_funnel.py
+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel.py
@@ -201,26 +201,27 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
)
if properties is not None:
- query = FunnelsQuery(
- **query.model_dump(exclude_defaults=True, exclude_none=True, mode="json"),
- properties={
- "type": "AND",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": key,
- "operator": "exact",
- "type": "event",
- "value": value,
- }
- for key, value in properties.items()
- ],
- }
- ],
- },
- )
+ # exclude_defaults would strip the default-valued `kind` from series items,
+ # which the discriminated series union requires on re-validation
+ query_data = query.model_dump(exclude_none=True, mode="json")
+ query_data["properties"] = {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "key": key,
+ "operator": "exact",
+ "type": "event",
+ "value": value,
+ }
+ for key, value in properties.items()
+ ],
+ }
+ ],
+ }
+ query = FunnelsQuery(**query_data)
return FunnelsQueryRunner(query=query, team=self.team)
diff --git a/posthog/schema.py b/posthog/schema.py
index 440cbae93a6a..cc6cb8a227ce 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -23060,10 +23060,6 @@ class AnyEntityNodeDataWarehouseNode(RootModel[EventsNode | ActionsNode | DataWa
root: EventsNode | ActionsNode | DataWarehouseNode
-class AnyEntityNodeFunnelsDataWarehouseNode(RootModel[EventsNode | ActionsNode | FunnelsDataWarehouseNode]):
- root: EventsNode | ActionsNode | FunnelsDataWarehouseNode
-
-
class AnyEntityNodeLifecycleDataWarehouseNode(RootModel[EventsNode | ActionsNode | LifecycleDataWarehouseNode]):
root: EventsNode | ActionsNode | LifecycleDataWarehouseNode
@@ -26427,83 +26423,6 @@ class ExperimentTrendsQueryResponse(BaseModel):
)
-class FunnelsQuery(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- aggregation_group_type_index: int | None = Field(default=None, description="Groups aggregation")
- breakdownFilter: BreakdownFilter | None = Field(default=None, description="Breakdown of the events and actions")
- compareFilter: CompareFilter | None = Field(default=None, description="Compare to date range")
- dataColorTheme: float | None = Field(default=None, description="Colors used in the insight's visualization")
- dateRange: DateRange | None = Field(default=None, description="Date range for the query")
- filterTestAccounts: bool | None = Field(
- default=False,
- description=("Exclude internal and test users by applying the respective filters"),
- )
- funnelsFilter: FunnelsFilter | None = Field(default=None, description="Properties specific to the funnels insight")
- interval: IntervalType | None = Field(
- default=None,
- description=("Granularity of the response. Can be one of `hour`, `day`, `week` or `month`"),
- )
- kind: Literal["FunnelsQuery"] = "FunnelsQuery"
- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
- properties: (
- list[
- EventPropertyFilter
- | PersonPropertyFilter
- | PersonMetadataPropertyFilter
- | ElementPropertyFilter
- | EventMetadataPropertyFilter
- | SessionPropertyFilter
- | CohortPropertyFilter
- | RecordingPropertyFilter
- | LogEntryPropertyFilter
- | GroupPropertyFilter
- | FeaturePropertyFilter
- | FlagPropertyFilter
- | HogQLPropertyFilter
- | EmptyPropertyFilter
- | DataWarehousePropertyFilter
- | DataWarehousePersonPropertyFilter
- | ErrorTrackingIssueFilter
- | LogPropertyFilter
- | MetricPropertyFilter
- | SpanPropertyFilter
- | RevenueAnalyticsPropertyFilter
- | WorkflowVariablePropertyFilter
- ]
- | PropertyGroupFilter
- | None
- ) = Field(default=[], description="Property filters for all series")
- response: FunnelsQueryResponse | None = None
- samplingFactor: float | None = Field(default=None, description="Sampling rate")
- series: list[GroupNode | EventsNode | ActionsNode | FunnelsDataWarehouseNode] = Field(
- ..., description="Events and actions to include"
- )
- tags: QueryLogTags | None = Field(default=None, description="Tags that will be added to the Query log comment")
- version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-
-
-class QueryResponseAlternative18(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- credible_intervals: dict[str, list[float]]
- expected_loss: float
- funnels_query: FunnelsQuery | None = None
- insight: list[list[dict[str, Any]]]
- kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
- probability: dict[str, float]
- significance_code: ExperimentSignificanceCode
- significant: bool
- stats_version: int | None = None
- variants: list[ExperimentVariantFunnelsBaseStats]
- warnings: list[DataWarehouseSyncWarning] | None = Field(
- default=None,
- description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
- )
-
-
class QueryResponseAlternative19(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -26525,47 +26444,6 @@ class QueryResponseAlternative19(BaseModel):
)
-class QueryResponseAlternative62(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- credible_intervals: dict[str, list[float]]
- expected_loss: float
- funnels_query: FunnelsQuery | None = None
- insight: list[list[dict[str, Any]]]
- kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
- probability: dict[str, float]
- significance_code: ExperimentSignificanceCode
- significant: bool
- stats_version: int | None = None
- variants: list[ExperimentVariantFunnelsBaseStats]
- warnings: list[DataWarehouseSyncWarning] | None = Field(
- default=None,
- description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
- )
-
-
-class QueryResponseAlternative63(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- count_query: TrendsQuery | None = None
- credible_intervals: dict[str, list[float]]
- exposure_query: TrendsQuery | None = None
- insight: list[dict[str, Any]]
- kind: Literal["ExperimentTrendsQuery"] = "ExperimentTrendsQuery"
- p_value: float
- probability: dict[str, float]
- significance_code: ExperimentSignificanceCode
- significant: bool
- stats_version: int | None = None
- variants: list[ExperimentVariantTrendsBaseStats]
- warnings: list[DataWarehouseSyncWarning] | None = Field(
- default=None,
- description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
- )
-
-
class QueryResponseAlternative75(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -26584,61 +26462,6 @@ class QueryResponseAlternative75(BaseModel):
]
-class CachedExperimentFunnelsQueryResponse(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]]
- expected_loss: float
- funnels_query: FunnelsQuery | None = None
- insight: list[list[dict[str, Any]]]
- is_cached: bool
- kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
- last_refresh: AwareDatetime
- next_allowed_client_refresh: AwareDatetime
- 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[ExperimentVariantFunnelsBaseStats]
- warnings: list[DataWarehouseSyncWarning] | None = Field(
- default=None,
- description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
- )
-
-
-class Response23(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- credible_intervals: dict[str, list[float]]
- expected_loss: float
- funnels_query: FunnelsQuery | None = None
- insight: list[list[dict[str, Any]]]
- kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
- probability: dict[str, float]
- significance_code: ExperimentSignificanceCode
- significant: bool
- stats_version: int | None = None
- variants: list[ExperimentVariantFunnelsBaseStats]
- warnings: list[DataWarehouseSyncWarning] | None = Field(
- default=None,
- description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
- )
-
-
class DatabaseSchemaQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -26657,26 +26480,6 @@ class DatabaseSchemaQueryResponse(BaseModel):
]
-class ExperimentFunnelsQueryResponse(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- credible_intervals: dict[str, list[float]]
- expected_loss: float
- funnels_query: FunnelsQuery | None = None
- insight: list[list[dict[str, Any]]]
- kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
- probability: dict[str, float]
- significance_code: ExperimentSignificanceCode
- significant: bool
- stats_version: int | None = None
- variants: list[ExperimentVariantFunnelsBaseStats]
- warnings: list[DataWarehouseSyncWarning] | None = Field(
- default=None,
- description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
- )
-
-
class ExperimentMetric(
RootModel[ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric]
):
@@ -26738,58 +26541,6 @@ class ExperimentTrendsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class FunnelPathsFilter(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- funnelPathType: FunnelPathType | None = None
- funnelSource: FunnelsQuery
- funnelStep: int | None = None
-
-
-class FunnelsActorsQuery(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- compare: Compare | None = Field(
- default=None,
- description=(
- "When the source funnel has compare-to-previous enabled, scopes the actors"
- " to a single period. The runner resolves `'previous'` to the shifted date"
- " range; `'current'` (or unset) uses the source's own date range."
- ),
- )
- funnelStep: int | None = Field(
- default=None,
- description=(
- "Index of the step for which we want to get the timestamp for, per person."
- " Positive for converted persons, negative for dropped of persons."
- ),
- )
- funnelStepBreakdown: int | str | float | list[int | str | float] | None = Field(
- default=None,
- description=(
- "The breakdown value for which to get persons for. This is an array for"
- " person and event properties, a string for groups and an integer for"
- " cohorts."
- ),
- )
- funnelTrendsDropOff: bool | None = None
- funnelTrendsEntrancePeriodStart: str | None = Field(
- default=None,
- description=(
- "Used together with `funnelTrendsDropOff` for funnels time conversion date for the persons modal."
- ),
- )
- includeRecordings: bool | None = None
- kind: Literal["FunnelsActorsQuery"] = "FunnelsActorsQuery"
- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
- response: ActorsQueryResponse | None = None
- source: FunnelsQuery
- tags: QueryLogTags | None = None
- version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-
-
class LegacyExperimentQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -26812,24 +26563,223 @@ class LegacyExperimentQueryResponse(BaseModel):
)
-class PathsQuery(BaseModel):
+class QueryResponseAlternative20(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
- aggregation_group_type_index: int | None = Field(default=None, description="Groups aggregation")
- dataColorTheme: float | None = Field(default=None, description="Colors used in the insight's visualization")
- dateRange: DateRange | None = Field(default=None, description="Date range for the query")
- filterTestAccounts: bool | None = Field(
- default=False,
- description=("Exclude internal and test users by applying the respective filters"),
- )
- funnelPathsFilter: FunnelPathsFilter | None = Field(
+ baseline: ExperimentStatsBaseValidated | None = None
+ breakdown_results: list[ExperimentBreakdownResult] | None = Field(
default=None,
- description="Used for displaying paths in relation to funnel steps.",
+ description=(
+ "Results grouped by breakdown value. When present, baseline and variant_results contain aggregated data."
+ ),
)
- kind: Literal["PathsQuery"] = "PathsQuery"
+ 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
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
+ )
+
+
+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 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
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
+ )
+
+
+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]
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
+ )
+
+
+class DatabaseSchemaQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ connectionId: str | None = Field(
+ default=None,
+ description="Optional direct external data source id for schema introspection",
+ )
+ kind: Literal["DatabaseSchemaQuery"] = "DatabaseSchemaQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ response: DatabaseSchemaQueryResponse | None = None
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
+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 FunnelsQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ aggregation_group_type_index: int | None = Field(default=None, description="Groups aggregation")
+ breakdownFilter: BreakdownFilter | None = Field(default=None, description="Breakdown of the events and actions")
+ compareFilter: CompareFilter | None = Field(default=None, description="Compare to date range")
+ dataColorTheme: float | None = Field(default=None, description="Colors used in the insight's visualization")
+ dateRange: DateRange | None = Field(default=None, description="Date range for the query")
+ filterTestAccounts: bool | None = Field(
+ default=False,
+ description=("Exclude internal and test users by applying the respective filters"),
+ )
+ funnelsFilter: FunnelsFilter | None = Field(default=None, description="Properties specific to the funnels insight")
+ interval: IntervalType | None = Field(
+ default=None,
+ description=("Granularity of the response. Can be one of `hour`, `day`, `week` or `month`"),
+ )
+ kind: Literal["FunnelsQuery"] = "FunnelsQuery"
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
- pathsFilter: PathsFilter = Field(..., description="Properties specific to the paths insight")
properties: (
list[
EventPropertyFilter
@@ -26858,48 +26808,29 @@ class PathsQuery(BaseModel):
| PropertyGroupFilter
| None
) = Field(default=[], description="Property filters for all series")
- response: PathsQueryResponse | None = None
+ response: FunnelsQueryResponse | None = None
samplingFactor: float | None = Field(default=None, description="Sampling rate")
+ series: list[
+ Annotated[EventsNode | ActionsNode | FunnelsDataWarehouseNode | GroupNode, Field(discriminator="kind")]
+ ] = Field(..., description="Events and actions to include")
tags: QueryLogTags | None = Field(default=None, description="Tags that will be added to the Query log comment")
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class ProductAnalyticsInsightQueryNode(
- RootModel[TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery]
-):
- root: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery
-
-
-class QueryResponseAlternative20(BaseModel):
+class QueryResponseAlternative18(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
+ credible_intervals: dict[str, list[float]]
+ expected_loss: float
+ funnels_query: FunnelsQuery | None = None
+ insight: list[list[dict[str, Any]]]
+ kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
+ probability: dict[str, float]
+ significance_code: ExperimentSignificanceCode
+ significant: bool
stats_version: int | None = None
- variant_results: list[ExperimentVariantResultFrequentist] | list[ExperimentVariantResultBayesian] | None = None
- variants: list[ExperimentVariantTrendsBaseStats] | list[ExperimentVariantFunnelsBaseStats] | None = None
+ variants: list[ExperimentVariantFunnelsBaseStats]
warnings: list[DataWarehouseSyncWarning] | None = Field(
default=None,
description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
@@ -26967,8 +26898,6 @@ class QueryResponseAlternative(
| QueryResponseAlternative58
| QueryResponseAlternative59
| QueryResponseAlternative60
- | QueryResponseAlternative62
- | QueryResponseAlternative63
| QueryResponseAlternative64
| QueryResponseAlternative66
| QueryResponseAlternative67
@@ -27071,8 +27000,6 @@ class QueryResponseAlternative(
| QueryResponseAlternative58
| QueryResponseAlternative59
| QueryResponseAlternative60
- | QueryResponseAlternative62
- | QueryResponseAlternative63
| QueryResponseAlternative64
| QueryResponseAlternative66
| QueryResponseAlternative67
@@ -27116,6 +27043,229 @@ class QueryResponseAlternative(
)
+class CachedExperimentFunnelsQueryResponse(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]]
+ expected_loss: float
+ funnels_query: FunnelsQuery | None = None
+ insight: list[list[dict[str, Any]]]
+ is_cached: bool
+ kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
+ last_refresh: AwareDatetime
+ next_allowed_client_refresh: AwareDatetime
+ 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[ExperimentVariantFunnelsBaseStats]
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
+ )
+
+
+class Response23(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ credible_intervals: dict[str, list[float]]
+ expected_loss: float
+ funnels_query: FunnelsQuery | None = None
+ insight: list[list[dict[str, Any]]]
+ kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
+ probability: dict[str, float]
+ significance_code: ExperimentSignificanceCode
+ significant: bool
+ stats_version: int | None = None
+ variants: list[ExperimentVariantFunnelsBaseStats]
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
+ )
+
+
+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",
+ )
+ credible_intervals: dict[str, list[float]]
+ expected_loss: float
+ funnels_query: FunnelsQuery | None = None
+ insight: list[list[dict[str, Any]]]
+ kind: Literal["ExperimentFunnelsQuery"] = "ExperimentFunnelsQuery"
+ probability: dict[str, float]
+ significance_code: ExperimentSignificanceCode
+ significant: bool
+ stats_version: int | None = None
+ variants: list[ExperimentVariantFunnelsBaseStats]
+ warnings: list[DataWarehouseSyncWarning] | None = Field(
+ default=None,
+ description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
+ )
+
+
+class FunnelPathsFilter(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ funnelPathType: FunnelPathType | None = None
+ funnelSource: FunnelsQuery
+ funnelStep: int | None = None
+
+
+class FunnelsActorsQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ compare: Compare | None = Field(
+ default=None,
+ description=(
+ "When the source funnel has compare-to-previous enabled, scopes the actors"
+ " to a single period. The runner resolves `'previous'` to the shifted date"
+ " range; `'current'` (or unset) uses the source's own date range."
+ ),
+ )
+ funnelStep: int | None = Field(
+ default=None,
+ description=(
+ "Index of the step for which we want to get the timestamp for, per person."
+ " Positive for converted persons, negative for dropped of persons."
+ ),
+ )
+ funnelStepBreakdown: int | str | float | list[int | str | float] | None = Field(
+ default=None,
+ description=(
+ "The breakdown value for which to get persons for. This is an array for"
+ " person and event properties, a string for groups and an integer for"
+ " cohorts."
+ ),
+ )
+ funnelTrendsDropOff: bool | None = None
+ funnelTrendsEntrancePeriodStart: str | None = Field(
+ default=None,
+ description=(
+ "Used together with `funnelTrendsDropOff` for funnels time conversion date for the persons modal."
+ ),
+ )
+ includeRecordings: bool | None = None
+ kind: Literal["FunnelsActorsQuery"] = "FunnelsActorsQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ response: ActorsQueryResponse | None = None
+ source: FunnelsQuery
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
+class PathsQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ aggregation_group_type_index: int | None = Field(default=None, description="Groups aggregation")
+ dataColorTheme: float | None = Field(default=None, description="Colors used in the insight's visualization")
+ dateRange: DateRange | None = Field(default=None, description="Date range for the query")
+ filterTestAccounts: bool | None = Field(
+ default=False,
+ description=("Exclude internal and test users by applying the respective filters"),
+ )
+ funnelPathsFilter: FunnelPathsFilter | None = Field(
+ default=None,
+ description="Used for displaying paths in relation to funnel steps.",
+ )
+ kind: Literal["PathsQuery"] = "PathsQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ pathsFilter: PathsFilter = Field(..., description="Properties specific to the paths insight")
+ properties: (
+ list[
+ EventPropertyFilter
+ | PersonPropertyFilter
+ | PersonMetadataPropertyFilter
+ | ElementPropertyFilter
+ | EventMetadataPropertyFilter
+ | SessionPropertyFilter
+ | CohortPropertyFilter
+ | RecordingPropertyFilter
+ | LogEntryPropertyFilter
+ | GroupPropertyFilter
+ | FeaturePropertyFilter
+ | FlagPropertyFilter
+ | HogQLPropertyFilter
+ | EmptyPropertyFilter
+ | DataWarehousePropertyFilter
+ | DataWarehousePersonPropertyFilter
+ | ErrorTrackingIssueFilter
+ | LogPropertyFilter
+ | MetricPropertyFilter
+ | SpanPropertyFilter
+ | RevenueAnalyticsPropertyFilter
+ | WorkflowVariablePropertyFilter
+ ]
+ | PropertyGroupFilter
+ | None
+ ) = Field(default=[], description="Property filters for all series")
+ response: PathsQueryResponse | None = None
+ samplingFactor: float | None = Field(default=None, description="Sampling rate")
+ tags: QueryLogTags | None = Field(default=None, description="Tags that will be added to the Query log comment")
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
+class ProductAnalyticsInsightQueryNode(
+ RootModel[TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery]
+):
+ root: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery
+
+
class VisualizationBlock(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -27212,134 +27362,6 @@ class VisualizationMessage(BaseModel):
type: Literal["ai/viz"] = "ai/viz"
-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 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
- warnings: list[DataWarehouseSyncWarning] | None = Field(
- default=None,
- description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
- )
-
-
-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]
- warnings: list[DataWarehouseSyncWarning] | None = Field(
- default=None,
- description=("Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics."),
- )
-
-
-class DatabaseSchemaQuery(BaseModel):
- model_config = ConfigDict(
- extra="forbid",
- )
- connectionId: str | None = Field(
- default=None,
- description="Optional direct external data source id for schema introspection",
- )
- kind: Literal["DatabaseSchemaQuery"] = "DatabaseSchemaQuery"
- modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
- response: DatabaseSchemaQueryResponse | None = None
- 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",
@@ -27356,39 +27378,6 @@ class ExperimentFunnelsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-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 FunnelCorrelationQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -27533,44 +27522,6 @@ 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 FunnelCorrelationActorsQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
diff --git a/posthog/test/test_funnels_series_discriminator.py b/posthog/test/test_funnels_series_discriminator.py
new file mode 100644
index 000000000000..71f3a098b586
--- /dev/null
+++ b/posthog/test/test_funnels_series_discriminator.py
@@ -0,0 +1,120 @@
+from django.test.testcases import SimpleTestCase
+
+from parameterized import parameterized
+from pydantic import ValidationError
+
+from posthog.schema import FunnelsQuery
+
+
+class TestFunnelsSeriesDiscriminator(SimpleTestCase):
+ # `FunnelsQuery.series` was an undiscriminated union — Pydantic would walk every
+ # variant and report errors for each, so a single malformed series item produced
+ # a dozen-plus errors per item (hundreds for real-world malformed queries), and
+ # items missing `kind` silently coerced to EventsNode. These tests pin the `kind`
+ # discriminator so a schema regeneration that drops it (generator config change,
+ # patch-script miss in bin/patch-schema-array-discriminators.py) fails here.
+
+ _ALL_KINDS = ("EventsNode", "ActionsNode", "FunnelsDataWarehouseNode", "GroupNode")
+
+ @staticmethod
+ def _query(series: list[dict]) -> dict:
+ return {"kind": "FunnelsQuery", "series": series}
+
+ @parameterized.expand(
+ [
+ # (case_name, series_item, declared_kind)
+ ("events_node_extra_field", {"kind": "EventsNode", "event": "$pageview", "id": 5}, "EventsNode"),
+ ("actions_node_bad_id", {"kind": "ActionsNode", "id": "not-an-int"}, "ActionsNode"),
+ ("group_node_missing_required", {"kind": "GroupNode"}, "GroupNode"),
+ ("data_warehouse_node_missing_required", {"kind": "FunnelsDataWarehouseNode"}, "FunnelsDataWarehouseNode"),
+ ]
+ )
+ def test_invalid_item_routes_to_declared_kind_only(self, _name: str, series_item: dict, declared_kind: str) -> None:
+ with self.assertRaises(ValidationError) as ctx:
+ FunnelsQuery.model_validate(self._query([series_item]))
+
+ errors = ctx.exception.errors()
+ assert errors, "expected at least one validation error"
+
+ item_errors = [err for err in errors if err["loc"][:2] == ("series", 0)]
+ assert item_errors, f"expected errors under ('series', 0); got locs {[err['loc'] for err in errors]}"
+
+ kinds_in_locs = {
+ err["loc"][2] for err in item_errors if len(err["loc"]) > 2 and err["loc"][2] in self._ALL_KINDS
+ }
+ assert kinds_in_locs == {declared_kind}, (
+ f"errors should reach exactly one variant tag {declared_kind!r}; "
+ f"got {kinds_in_locs!r} — series discriminator likely dropped"
+ )
+
+ @parameterized.expand(
+ [
+ # Positive routing proof: fields REQUIRED by the declared variant are reported
+ # missing — an undiscriminated union would drown these in other variants' noise.
+ ("group_node", "GroupNode", {"operator", "nodes"}),
+ (
+ "data_warehouse_node",
+ "FunnelsDataWarehouseNode",
+ {"id", "id_field", "table_name", "timestamp_field", "aggregation_target_field"},
+ ),
+ ]
+ )
+ def test_missing_required_fields_reported_for_declared_kind(
+ self, _name: str, declared_kind: str, expected_missing: set[str]
+ ) -> None:
+ with self.assertRaises(ValidationError) as ctx:
+ FunnelsQuery.model_validate(self._query([{"kind": declared_kind}]))
+
+ errors = ctx.exception.errors()
+ missing = {
+ err["loc"][3]
+ for err in errors
+ if err["type"] == "missing" and err["loc"][:3] == ("series", 0, declared_kind)
+ }
+ assert missing == expected_missing, f"expected missing fields {expected_missing!r}, got {missing!r}"
+ assert len(errors) == len(expected_missing), f"expected only missing-field errors, got {errors}"
+
+ def test_unknown_kind_returns_single_clean_tag_error(self) -> None:
+ with self.assertRaises(ValidationError) as ctx:
+ FunnelsQuery.model_validate(self._query([{"kind": "banana", "event": "$pageview"}]))
+
+ errors = ctx.exception.errors()
+ assert len(errors) == 1, f"expected exactly one error, got {len(errors)}: {errors}"
+ assert errors[0]["type"] == "union_tag_invalid"
+ expected_tags_str = errors[0]["ctx"]["expected_tags"]
+ for tag in self._ALL_KINDS:
+ assert f"'{tag}'" in expected_tags_str, f"expected tag {tag!r} in {expected_tags_str!r}"
+
+ def test_missing_kind_returns_one_error_per_item(self) -> None:
+ # Regression for the error explosion this discriminator fixes: three malformed
+ # items must produce exactly three errors, not one per (item x variant x field).
+ with self.assertRaises(ValidationError) as ctx:
+ FunnelsQuery.model_validate(self._query([{"event": "a"}, {"event": "b"}, {"event": "c"}]))
+
+ errors = ctx.exception.errors()
+ assert len(errors) == 3, f"expected exactly one error per series item, got {len(errors)}: {errors}"
+ assert all(err["type"] == "union_tag_not_found" for err in errors)
+
+ @parameterized.expand(
+ [
+ ("events_node", {"kind": "EventsNode", "event": "$pageview"}),
+ ("actions_node", {"kind": "ActionsNode", "id": 1}),
+ (
+ "group_node",
+ {"kind": "GroupNode", "operator": "AND", "nodes": [{"kind": "EventsNode", "event": "$pageview"}]},
+ ),
+ (
+ "data_warehouse_node",
+ {
+ "kind": "FunnelsDataWarehouseNode",
+ "id": "orders",
+ "id_field": "id",
+ "table_name": "orders",
+ "timestamp_field": "created_at",
+ "aggregation_target_field": "user_id",
+ },
+ ),
+ ]
+ )
+ def test_valid_item_per_kind_still_validates(self, _name: str, series_item: dict) -> None:
+ FunnelsQuery.model_validate(self._query([series_item]))
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index a1e99019a731..e3d55372c193 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -2882,7 +2882,7 @@ export interface FunnelsQueryApi {
/** Sampling rate */
samplingFactor?: number | null
/** Events and actions to include */
- series: (GroupNodeApi | EventsNodeApi | ActionsNodeApi | FunnelsDataWarehouseNodeApi)[]
+ series: (EventsNodeApi | ActionsNodeApi | FunnelsDataWarehouseNodeApi | GroupNodeApi)[]
/** Tags that will be added to the Query log comment */
tags?: QueryLogTagsApi | null
/** version of the node, used for schema migrations */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 6c4aa15f2699..2601b6631a47 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -2235,7 +2235,7 @@ export interface FunnelsQueryApi {
/** Sampling rate */
samplingFactor?: number | null
/** Events and actions to include */
- series: (GroupNodeApi | EventsNodeApi | ActionsNodeApi | FunnelsDataWarehouseNodeApi)[]
+ series: (EventsNodeApi | ActionsNodeApi | FunnelsDataWarehouseNodeApi | GroupNodeApi)[]
/** Tags that will be added to the Query log comment */
tags?: QueryLogTagsApi | null
/** version of the node, used for schema migrations */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b011ee253542..a43a2d3ab890 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -3028,7 +3028,7 @@ export namespace Schemas {
/** Sampling rate */
samplingFactor?: number | null;
/** Events and actions to include */
- series: (GroupNode | EventsNode | ActionsNode | FunnelsDataWarehouseNode)[];
+ series: (EventsNode | ActionsNode | FunnelsDataWarehouseNode | GroupNode)[];
/** Tags that will be added to the Query log comment */
tags?: QueryLogTags | null;
/** version of the node, used for schema migrations */
@@ -50461,49 +50461,6 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative62CredibleIntervals = {[key: string]: number[]};
-
- export type QueryResponseAlternative62InsightItemItem = { [key: string]: unknown };
-
- export type QueryResponseAlternative62Probability = {[key: string]: number};
-
- export interface QueryResponseAlternative62 {
- credible_intervals: QueryResponseAlternative62CredibleIntervals;
- expected_loss: number;
- funnels_query?: FunnelsQuery | null;
- insight: QueryResponseAlternative62InsightItemItem[][];
- kind?: 'ExperimentFunnelsQuery';
- probability: QueryResponseAlternative62Probability;
- significance_code: ExperimentSignificanceCode;
- significant: boolean;
- stats_version?: number | null;
- variants: ExperimentVariantFunnelsBaseStats[];
- /** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
- warnings?: DataWarehouseSyncWarning[] | null;
- }
-
- export type QueryResponseAlternative63CredibleIntervals = {[key: string]: number[]};
-
- export type QueryResponseAlternative63InsightItem = { [key: string]: unknown };
-
- export type QueryResponseAlternative63Probability = {[key: string]: number};
-
- export interface QueryResponseAlternative63 {
- count_query?: TrendsQuery | null;
- credible_intervals: QueryResponseAlternative63CredibleIntervals;
- exposure_query?: TrendsQuery | null;
- insight: QueryResponseAlternative63InsightItem[];
- kind?: 'ExperimentTrendsQuery';
- p_value: number;
- probability: QueryResponseAlternative63Probability;
- significance_code: ExperimentSignificanceCode;
- significant: boolean;
- stats_version?: number | null;
- variants: ExperimentVariantTrendsBaseStats[];
- /** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
- warnings?: DataWarehouseSyncWarning[] | null;
- }
-
export interface QueryResponseAlternative64 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -51350,7 +51307,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107;
+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative64 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106 | QueryResponseAlternative107;
export interface QueryStatusResponse {
query_status: QueryStatus;