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(insights): backfill missing kind on stored series and exclusion nodes (#70799)

Thomas Obermüller7aa7a4d5d1b6
diff --git a/frontend/src/queries/latest-versions.json b/frontend/src/queries/latest-versions.json
index 542cc33843c3..a922342a5c02 100644
--- a/frontend/src/queries/latest-versions.json
+++ b/frontend/src/queries/latest-versions.json
@@ -1,6 +1,9 @@
{
"//": "THIS FILE IS AUTOGENERATED. DO NOT EDIT MANUALLY. To update: pnpm run schema:build",
+ "CalendarHeatmapQuery": 2,
+ "FunnelsQuery": 2,
+ "LifecycleQuery": 2,
"RetentionQuery": 2,
- "StickinessQuery": 3,
- "TrendsQuery": 3
+ "StickinessQuery": 4,
+ "TrendsQuery": 4
}
diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
index 05f910107d45..267dade8e07b 100644
--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
@@ -92,7 +92,7 @@ describe('insightNavLogic', () => {
await expectLogic(builtInsightDataLogic, () => {
logic.actions.setActiveView(InsightType.FUNNELS)
}).toMatchValues({
- query: {
+ query: setLatestVersionsOnQuery({
kind: NodeKind.InsightVizNode,
source: {
...nodeKindToDefaultQuery[NodeKind.FunnelsQuery],
@@ -106,7 +106,7 @@ describe('insightNavLogic', () => {
],
tags: PRODUCT_ANALYTICS_DEFAULT_QUERY_TAGS,
},
- },
+ }),
})
})
@@ -281,6 +281,7 @@ describe('insightNavLogic', () => {
kind: 'LifecycleQuery',
series: [{ kind: 'EventsNode', name: '$pageview', event: '$pageview' }],
filterTestAccounts: true,
+ version: LATEST_VERSIONS[NodeKind.LifecycleQuery],
lifecycleFilter: { showValuesOnSeries: true },
tags: PRODUCT_ANALYTICS_DEFAULT_QUERY_TAGS,
},
@@ -484,6 +485,7 @@ describe('insightNavLogic', () => {
kind: 'LifecycleQuery',
series: [{ kind: 'EventsNode', name: '$pageview', event: '$pageview' }],
filterTestAccounts: true,
+ version: LATEST_VERSIONS[NodeKind.LifecycleQuery],
interval: 'hour',
lifecycleFilter: { showValuesOnSeries: true },
tags: PRODUCT_ANALYTICS_DEFAULT_QUERY_TAGS,
@@ -517,6 +519,7 @@ describe('insightNavLogic', () => {
series: [{ kind: 'EventsNode', name: '$pageview', event: '$pageview' }],
funnelsFilter: { funnelVizType: 'steps', showValuesOnSeries: true },
filterTestAccounts: true,
+ version: LATEST_VERSIONS[NodeKind.FunnelsQuery],
interval: 'hour',
breakdownFilter: {
breakdowns: undefined,
@@ -600,6 +603,7 @@ describe('insightNavLogic', () => {
series: [{ kind: 'EventsNode', name: '$pageview', event: '$pageview' }],
funnelsFilter: { funnelVizType: 'steps', showValuesOnSeries: true },
filterTestAccounts: true,
+ version: LATEST_VERSIONS[NodeKind.FunnelsQuery],
interval: 'hour',
breakdownFilter: {
breakdowns: undefined,
@@ -660,6 +664,7 @@ describe('insightNavLogic', () => {
series: [{ kind: 'EventsNode', name: '$pageview', event: '$pageview' }],
funnelsFilter: { funnelVizType: 'steps', showValuesOnSeries: true },
filterTestAccounts: true,
+ version: LATEST_VERSIONS[NodeKind.FunnelsQuery],
interval: 'hour',
tags: PRODUCT_ANALYTICS_DEFAULT_QUERY_TAGS,
},
diff --git a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts
index dfe82ad8f5cf..359406636b62 100644
--- a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts
@@ -17,9 +17,15 @@ describe('migrate()', () => {
'/api/environments/:team_id/query/upgrade': async ({ request }) => {
const data = (await request.json()) as any
const kind = data?.query?.source?.kind
- // These fixtures have no result customizations, so the trends/stickiness
- // migration past v2 is a no-op beyond the version bump the backend applies.
- if (kind === 'TrendsQuery' || kind === 'StickinessQuery') {
+ // These fixtures have no result customizations and fully tagged series, so
+ // the backend migrations are a no-op beyond the version bump they apply.
+ if (
+ kind === 'TrendsQuery' ||
+ kind === 'StickinessQuery' ||
+ kind === 'FunnelsQuery' ||
+ kind === 'LifecycleQuery' ||
+ kind === 'CalendarHeatmapQuery'
+ ) {
return [
200,
{
@@ -280,6 +286,7 @@ describe('migrate()', () => {
funnelWindowIntervalUnit: 'day',
},
aggregation_group_type_index: 0,
+ version: LATEST_VERSIONS[NodeKind.FunnelsQuery],
},
},
title: 'Organisation signed up -> recording analyzed, last 6 weeks',
diff --git a/posthog/schema_migrations/0004_entity_node_kind.py b/posthog/schema_migrations/0004_entity_node_kind.py
new file mode 100644
index 000000000000..e50f179b7803
--- /dev/null
+++ b/posthog/schema_migrations/0004_entity_node_kind.py
@@ -0,0 +1,70 @@
+from posthog.schema_migrations.base import SchemaMigration
+
+# Data warehouse series nodes use a different kind per insight type; exclusions have no
+# data warehouse member, so table_name-shaped exclusion items fall through to EventsNode.
+SERIES_DATA_WAREHOUSE_KIND = {
+ "TrendsQuery": "DataWarehouseNode",
+ "StickinessQuery": "DataWarehouseNode",
+ "LifecycleQuery": "LifecycleDataWarehouseNode",
+ "CalendarHeatmapQuery": "DataWarehouseNode",
+ "FunnelsQuery": "FunnelsDataWarehouseNode",
+}
+
+# Only these series unions include GroupNode; elsewhere (and in exclusions) a group-shaped
+# item was invalid before discrimination too, so it falls through to EventsNode unchanged.
+SERIES_WITH_GROUP_NODE = {"TrendsQuery", "FunnelsQuery"}
+
+
+class Migration(SchemaMigration):
+ """Stamp the `kind` discriminator onto entity nodes (series, funnel exclusions) that lack it.
+
+ These unions used to be undiscriminated: pydantic's smart union coerced a kind-less dict
+ to the first structurally-matching member, so stored insights contain series items like
+ `{"event": "$pageview"}` or `{}`. With the unions now discriminated on `kind`, such items
+ fail validation with `union_tag_not_found` unless the tag is backfilled. The stamping
+ mirrors the old coercion: event-shaped (and empty) dicts were EventsNode, id-only dicts
+ were ActionsNode, table_name-shaped dicts were the data warehouse node, and nodes-shaped
+ dicts were GroupNode where the union has it.
+ """
+
+ targets = {
+ "TrendsQuery": 3,
+ "StickinessQuery": 3,
+ "LifecycleQuery": 1,
+ "CalendarHeatmapQuery": 1,
+ "FunnelsQuery": 1,
+ }
+
+ def transform(self, query: dict) -> dict:
+ query_kind = str(query.get("kind"))
+ data_warehouse_kind = SERIES_DATA_WAREHOUSE_KIND[query_kind]
+ allow_group = query_kind in SERIES_WITH_GROUP_NODE
+
+ series = query.get("series")
+ if isinstance(series, list):
+ query["series"] = [self._stamp_kind(item, data_warehouse_kind, allow_group) for item in series]
+
+ funnels_filter = query.get("funnelsFilter")
+ if query_kind == "FunnelsQuery" and isinstance(funnels_filter, dict):
+ exclusions = funnels_filter.get("exclusions")
+ if isinstance(exclusions, list):
+ query["funnelsFilter"] = {
+ **funnels_filter,
+ "exclusions": [self._stamp_kind(item, None, False) for item in exclusions],
+ }
+
+ return query
+
+ @staticmethod
+ def _stamp_kind(item: object, data_warehouse_kind: str | None, allow_group: bool) -> object:
+ if not isinstance(item, dict) or "kind" in item:
+ return item
+ if data_warehouse_kind is not None and "table_name" in item:
+ kind = data_warehouse_kind
+ elif allow_group and "nodes" in item:
+ kind = "GroupNode"
+ elif "id" in item and "event" not in item:
+ kind = "ActionsNode"
+ else:
+ kind = "EventsNode"
+ return {**item, "kind": kind}
diff --git a/posthog/schema_migrations/test/test_0004_entity_node_kind.py b/posthog/schema_migrations/test/test_0004_entity_node_kind.py
new file mode 100644
index 000000000000..51032269cba9
--- /dev/null
+++ b/posthog/schema_migrations/test/test_0004_entity_node_kind.py
@@ -0,0 +1,157 @@
+import importlib
+
+from parameterized import parameterized
+
+from posthog.schema import FunnelsQuery, LifecycleQuery, TrendsQuery
+
+from posthog.schema_migrations.upgrade import upgrade
+
+
+def _get_migration():
+ migration_module = importlib.import_module("posthog.schema_migrations.0004_entity_node_kind")
+ return migration_module.Migration()
+
+
+ [
+ # (case_name, query_kind, series_item, expected_kind)
+ ("event_shaped", "TrendsQuery", {"event": "$pageview"}, "EventsNode"),
+ ("empty_dict", "TrendsQuery", {}, "EventsNode"),
+ ("math_only", "TrendsQuery", {"math": "dau", "event": "$pageview"}, "EventsNode"),
+ ("id_only", "TrendsQuery", {"id": 5}, "ActionsNode"),
+ ("id_and_event", "TrendsQuery", {"id": "$pageview", "event": "$pageview"}, "EventsNode"),
+ ("data_warehouse_shaped", "TrendsQuery", {"table_name": "orders", "id": "orders"}, "DataWarehouseNode"),
+ ("group_shaped", "TrendsQuery", {"nodes": [{"kind": "EventsNode"}], "operator": "OR"}, "GroupNode"),
+ ("funnels_event_shaped", "FunnelsQuery", {"event": "$pageview"}, "EventsNode"),
+ (
+ "funnels_data_warehouse_shaped",
+ "FunnelsQuery",
+ {"table_name": "orders", "id": "orders"},
+ "FunnelsDataWarehouseNode",
+ ),
+ ("funnels_group_shaped", "FunnelsQuery", {"nodes": [{"kind": "EventsNode"}], "operator": "OR"}, "GroupNode"),
+ ("lifecycle_event_shaped", "LifecycleQuery", {"event": "$pageview"}, "EventsNode"),
+ (
+ "lifecycle_data_warehouse_shaped",
+ "LifecycleQuery",
+ {"table_name": "orders", "id": "orders"},
+ "LifecycleDataWarehouseNode",
+ ),
+ ("stickiness_event_shaped", "StickinessQuery", {"event": "$pageview"}, "EventsNode"),
+ (
+ "stickiness_data_warehouse_shaped",
+ "StickinessQuery",
+ {"table_name": "orders", "id": "orders"},
+ "DataWarehouseNode",
+ ),
+ # StickinessQuery.series has no GroupNode member — group-shaped items were invalid
+ # before discrimination and stay invalid (stamped EventsNode) rather than resurrected.
+ (
+ "stickiness_group_shaped",
+ "StickinessQuery",
+ {"nodes": [{"kind": "EventsNode"}], "operator": "OR"},
+ "EventsNode",
+ ),
+ ("calendar_heatmap_event_shaped", "CalendarHeatmapQuery", {"event": "$pageview"}, "EventsNode"),
+ (
+ "calendar_heatmap_data_warehouse_shaped",
+ "CalendarHeatmapQuery",
+ {"table_name": "orders", "id": "orders"},
+ "DataWarehouseNode",
+ ),
+ ]
+)
+def test_kindless_series_item_gets_stamped(_name, query_kind, series_item, expected_kind):
+ migration = _get_migration()
+ result = migration.transform({"kind": query_kind, "series": [series_item]})
+ assert result["series"][0] == {**series_item, "kind": expected_kind}
+
+
+ [
+ # (case_name, series) — items the migration must pass through untouched
+ ("tagged_item", [{"kind": "ActionsNode", "id": 5}]),
+ ("string_placeholder", ["{SIGNED_UP}"]),
+ ("null_item", [None]),
+ ]
+)
+def test_non_stampable_series_items_unchanged(_name, series):
+ migration = _get_migration()
+ result = migration.transform({"kind": "TrendsQuery", "series": list(series)})
+ assert result["series"] == series
+
+
+def test_missing_or_invalid_series_unchanged():
+ migration = _get_migration()
+ assert migration.transform({"kind": "TrendsQuery"}) == {"kind": "TrendsQuery"}
+ assert migration.transform({"kind": "TrendsQuery", "series": None}) == {"kind": "TrendsQuery", "series": None}
+
+
+def test_funnel_exclusions_get_stamped():
+ migration = _get_migration()
+ query = {
+ "kind": "FunnelsQuery",
+ "series": [{"kind": "EventsNode", "event": "a"}, {"kind": "EventsNode", "event": "b"}],
+ "funnelsFilter": {
+ "exclusions": [
+ {"event": "$pageleave", "funnelFromStep": 0, "funnelToStep": 1},
+ {"id": 5, "funnelFromStep": 0, "funnelToStep": 1},
+ # exclusions have no GroupNode member, so group-shaped items fall through
+ {"nodes": [{"kind": "EventsNode"}], "operator": "OR"},
+ ],
+ "funnelVizType": "steps",
+ },
+ }
+ result = migration.transform(query)
+ assert [e["kind"] for e in result["funnelsFilter"]["exclusions"]] == ["EventsNode", "ActionsNode", "EventsNode"]
+ assert result["funnelsFilter"]["funnelVizType"] == "steps"
+
+
+def test_upgraded_stored_funnels_query_validates():
+ # The end-to-end guarantee: a stored insight query written under the undiscriminated
+ # unions passes pydantic validation again after upgrade().
+ stored = {
+ "kind": "FunnelsQuery",
+ "series": [{"event": "signed_up"}, {"event": "activated"}],
+ "funnelsFilter": {"exclusions": [{"event": "$pageleave", "funnelFromStep": 0, "funnelToStep": 1}]},
+ }
+ upgraded = upgrade(stored)
+ query = FunnelsQuery.model_validate(upgraded)
+ assert [s.kind for s in query.series] == ["EventsNode", "EventsNode"]
+ assert query.funnelsFilter is not None and query.funnelsFilter.exclusions is not None
+ assert query.funnelsFilter.exclusions[0].kind == "EventsNode"
+ assert query.version == 2
+
+
+def test_upgraded_stored_trends_query_validates():
+ stored = {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [
+ {"math": "dau", "event": "$pageview"},
+ {"nodes": [{"kind": "EventsNode", "event": "$pageview"}], "operator": "OR"},
+ ],
+ },
+ }
+ upgraded = upgrade(stored)
+ query = TrendsQuery.model_validate(upgraded["source"])
+ assert [s.kind for s in query.series] == ["EventsNode", "GroupNode"]
+
+
+def test_upgraded_stored_lifecycle_warehouse_query_validates():
+ stored = {
+ "kind": "LifecycleQuery",
+ "series": [
+ {
+ "table_name": "orders",
+ "id": "orders",
+ "timestamp_field": "created_at",
+ "created_at_field": "created_at",
+ "aggregation_target_field": "customer_id",
+ }
+ ],
+ }
+ upgraded = upgrade(stored)
+ query = LifecycleQuery.model_validate(upgraded)
+ assert query.series[0].kind == "LifecycleDataWarehouseNode"