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.

refactor(aio): label insight results from the query series (#120253)

Thomas Obermüller79f5a6ca5e2b
diff --git a/ee/hogai/context/insight/format/__init__.py b/ee/hogai/context/insight/format/__init__.py
index 53502d12bf73..a86814352a97 100644
--- a/ee/hogai/context/insight/format/__init__.py
+++ b/ee/hogai/context/insight/format/__init__.py
@@ -24,6 +24,8 @@ from posthog.schema import (
TrendsQuery,
)
+from posthog.hogql_queries.utils.result_series import get_action_names
+
from .boxplot import BoxPlotResultsFormatter
from .funnel import FunnelResultsFormatter
from .lifecycle import LifecycleResultsFormatter
@@ -106,15 +108,20 @@ def format_query_results_for_llm(
utc_now,
resolved_date_range=response.get("resolved_date_range"),
resolved_compare_date_range=response.get("resolved_compare_date_range"),
+ action_names=get_action_names(team, query.model_dump(mode="json")),
).format()
elif isinstance(query, AssistantFunnelsQuery | FunnelsQuery):
formatted = FunnelResultsFormatter(query, response["results"], team, utc_now).format()
elif isinstance(query, AssistantLifecycleQuery | LifecycleQuery):
- formatted = LifecycleResultsFormatter(query, response["results"]).format()
+ formatted = LifecycleResultsFormatter(
+ query, response["results"], action_names=get_action_names(team, query.model_dump(mode="json"))
+ ).format()
elif isinstance(query, AssistantPathsQuery | PathsQuery):
formatted = PathsResultsFormatter(response["results"]).format()
elif isinstance(query, AssistantStickinessQuery | StickinessQuery):
- formatted = StickinessResultsFormatter(query, response["results"]).format()
+ formatted = StickinessResultsFormatter(
+ query, response["results"], action_names=get_action_names(team, query.model_dump(mode="json"))
+ ).format()
elif isinstance(query, AssistantRetentionQuery | RetentionQuery):
formatted = RetentionResultsFormatter(query, response["results"]).format()
elif isinstance(query, AssistantHogQLQuery | HogQLQuery):
diff --git a/ee/hogai/context/insight/format/lifecycle.py b/ee/hogai/context/insight/format/lifecycle.py
index a268f3966630..42fa7d59ad66 100644
--- a/ee/hogai/context/insight/format/lifecycle.py
+++ b/ee/hogai/context/insight/format/lifecycle.py
@@ -1,8 +1,11 @@
from collections import defaultdict
-from typing import Any
+from collections.abc import Mapping
+from typing import Any, Optional
from posthog.schema import AssistantLifecycleQuery, LifecycleQuery
+from posthog.hogql_queries.utils.result_series import get_result_order, get_result_series, get_series_key
+
from .utils import format_matrix, format_number, strip_datetime_seconds
STATUS_ORDER = ["new", "returning", "resurrecting", "dormant"]
@@ -36,20 +39,22 @@ class LifecycleResultsFormatter:
self,
query: AssistantLifecycleQuery | LifecycleQuery,
results: list[dict[str, Any]],
+ action_names: Optional[Mapping[int, str | None]] = None,
):
self._query = query
+ self._query_dict = query.model_dump(mode="json")
self._results = results
+ self._action_names = action_names
def format(self) -> str:
if not self._results:
return "No data recorded for this time period."
- # Group results by event series (using action order as key)
+ # Group results by event series
series_groups: dict[int, dict[str, dict[str, Any]]] = defaultdict(dict)
for result in self._results:
- order = result.get("action", {}).get("order", 0)
status = result.get("status", "")
- series_groups[order][status] = result
+ series_groups[get_result_order(result)][status] = result
sections: list[str] = []
multi_series = len(series_groups) > 1
@@ -90,14 +95,10 @@ class LifecycleResultsFormatter:
return f"Event: {series_name}\n{formatted}"
return formatted
- @staticmethod
- def _extract_series_name(result: dict[str, Any]) -> str:
- action = result.get("action")
- if isinstance(action, dict):
- custom_name = action.get("custom_name")
- if custom_name:
- return custom_name
- name = action.get("name")
+ def _extract_series_name(self, result: dict[str, Any]) -> str:
+ node = get_result_series(self._query_dict, result)
+ if node is not None:
+ name = node.get("custom_name") or node.get("name") or get_series_key(node, self._action_names)
if name:
return name
# Fallback: strip status suffix from label
diff --git a/ee/hogai/context/insight/format/stickiness.py b/ee/hogai/context/insight/format/stickiness.py
index 1617df7bd04f..983dfe93c787 100644
--- a/ee/hogai/context/insight/format/stickiness.py
+++ b/ee/hogai/context/insight/format/stickiness.py
@@ -1,7 +1,10 @@
-from typing import Any
+from collections.abc import Mapping
+from typing import Any, Optional
from posthog.schema import AssistantStickinessQuery, Compare, StickinessQuery
+from posthog.hogql_queries.utils.result_series import get_result_series, get_series_custom_name
+
from .utils import format_matrix, format_number
@@ -21,9 +24,12 @@ class StickinessResultsFormatter:
self,
query: AssistantStickinessQuery | StickinessQuery,
results: list[dict[str, Any]],
+ action_names: Optional[Mapping[int, str | None]] = None,
):
self._query = query
+ self._query_dict = query.model_dump(mode="json")
self._results = results
+ self._action_names = action_names
def format(self) -> str:
results = self._results
@@ -66,10 +72,6 @@ class StickinessResultsFormatter:
return format_matrix(matrix)
def _extract_series_label(self, series: dict[str, Any]) -> str:
- action = series.get("action")
- name = series["label"]
- if isinstance(action, dict):
- custom_name = action.get("custom_name")
- if custom_name is not None:
- name = custom_name
- return name
+ node = get_result_series(self._query_dict, series)
+ custom_name = get_series_custom_name(node, self._action_names) if node is not None else None
+ return custom_name if custom_name is not None else series["label"]
diff --git a/ee/hogai/context/insight/format/test/test_lifecycle.py b/ee/hogai/context/insight/format/test/test_lifecycle.py
index b815d8f54f97..b42c6bc3c6fa 100644
--- a/ee/hogai/context/insight/format/test/test_lifecycle.py
+++ b/ee/hogai/context/insight/format/test/test_lifecycle.py
@@ -5,16 +5,9 @@ from posthog.schema import AssistantLifecycleEventsNode, AssistantLifecycleQuery
from .. import LifecycleResultsFormatter
-def _make_result(event_id, event_name, status, data, days, order=0, custom_name=None):
+def _make_result(event_name, status, data, days, order=0):
return {
- "action": {
- "id": event_id,
- "type": "events",
- "order": order,
- "name": event_name,
- "custom_name": custom_name,
- "math": "total",
- },
+ "order": order,
"label": f"{event_name} - {status}",
"count": sum(data),
"data": data,
@@ -27,16 +20,10 @@ def _make_result(event_id, event_name, status, data, days, order=0, custom_name=
class TestLifecycleResultsFormatter(SimpleTestCase):
def test_format_single_series(self):
results = [
- _make_result("$pageview", "$pageview", "new", [100, 80, 60], ["2025-01-01", "2025-01-02", "2025-01-03"]),
- _make_result(
- "$pageview", "$pageview", "returning", [50, 40, 30], ["2025-01-01", "2025-01-02", "2025-01-03"]
- ),
- _make_result(
- "$pageview", "$pageview", "resurrecting", [10, 8, 6], ["2025-01-01", "2025-01-02", "2025-01-03"]
- ),
- _make_result(
- "$pageview", "$pageview", "dormant", [-20, -15, -10], ["2025-01-01", "2025-01-02", "2025-01-03"]
- ),
+ _make_result("$pageview", "new", [100, 80, 60], ["2025-01-01", "2025-01-02", "2025-01-03"]),
+ _make_result("$pageview", "returning", [50, 40, 30], ["2025-01-01", "2025-01-02", "2025-01-03"]),
+ _make_result("$pageview", "resurrecting", [10, 8, 6], ["2025-01-01", "2025-01-02", "2025-01-03"]),
+ _make_result("$pageview", "dormant", [-20, -15, -10], ["2025-01-01", "2025-01-02", "2025-01-03"]),
]
self.assertEqual(
@@ -52,14 +39,14 @@ class TestLifecycleResultsFormatter(SimpleTestCase):
def test_format_multi_series(self):
results = [
- _make_result("$pageview", "$pageview", "new", [100, 80], ["2025-01-01", "2025-01-02"], order=0),
- _make_result("$pageview", "$pageview", "returning", [50, 40], ["2025-01-01", "2025-01-02"], order=0),
- _make_result("$pageview", "$pageview", "resurrecting", [10, 8], ["2025-01-01", "2025-01-02"], order=0),
- _make_result("$pageview", "$pageview", "dormant", [-20, -15], ["2025-01-01", "2025-01-02"], order=0),
- _make_result("sign_up", "sign_up", "new", [30, 25], ["2025-01-01", "2025-01-02"], order=1),
- _make_result("sign_up", "sign_up", "returning", [15, 12], ["2025-01-01", "2025-01-02"], order=1),
- _make_result("sign_up", "sign_up", "resurrecting", [5, 3], ["2025-01-01", "2025-01-02"], order=1),
- _make_result("sign_up", "sign_up", "dormant", [-8, -6], ["2025-01-01", "2025-01-02"], order=1),
+ _make_result("$pageview", "new", [100, 80], ["2025-01-01", "2025-01-02"], order=0),
+ _make_result("$pageview", "returning", [50, 40], ["2025-01-01", "2025-01-02"], order=0),
+ _make_result("$pageview", "resurrecting", [10, 8], ["2025-01-01", "2025-01-02"], order=0),
+ _make_result("$pageview", "dormant", [-20, -15], ["2025-01-01", "2025-01-02"], order=0),
+ _make_result("sign_up", "new", [30, 25], ["2025-01-01", "2025-01-02"], order=1),
+ _make_result("sign_up", "returning", [15, 12], ["2025-01-01", "2025-01-02"], order=1),
+ _make_result("sign_up", "resurrecting", [5, 3], ["2025-01-01", "2025-01-02"], order=1),
+ _make_result("sign_up", "dormant", [-8, -6], ["2025-01-01", "2025-01-02"], order=1),
]
self.assertEqual(
@@ -95,42 +82,34 @@ class TestLifecycleResultsFormatter(SimpleTestCase):
def test_format_custom_name(self):
results = [
_make_result(
- "255320",
"[growth] Soft Activation",
"new",
[6936],
["2025-10-01"],
- custom_name="Yes",
),
_make_result(
- "255320",
"[growth] Soft Activation",
"returning",
[29541],
["2025-10-01"],
- custom_name="Yes",
),
_make_result(
- "255320",
"[growth] Soft Activation",
"resurrecting",
[13263],
["2025-10-01"],
- custom_name="Yes",
),
_make_result(
- "255320",
"[growth] Soft Activation",
"dormant",
[-16735],
["2025-10-01"],
- custom_name="Yes",
),
]
# Single series should not include the Event: header
formatted = LifecycleResultsFormatter(
- AssistantLifecycleQuery(series=[AssistantLifecycleEventsNode(event="$pageview")]),
+ AssistantLifecycleQuery(series=[AssistantLifecycleEventsNode(event="$pageview", custom_name="Yes")]),
results,
).format()
@@ -142,8 +121,8 @@ class TestLifecycleResultsFormatter(SimpleTestCase):
def test_format_missing_status(self):
# Only new and dormant statuses present
results = [
- _make_result("$pageview", "$pageview", "new", [100, 80], ["2025-01-01", "2025-01-02"]),
- _make_result("$pageview", "$pageview", "dormant", [-20, -15], ["2025-01-01", "2025-01-02"]),
+ _make_result("$pageview", "new", [100, 80], ["2025-01-01", "2025-01-02"]),
+ _make_result("$pageview", "dormant", [-20, -15], ["2025-01-01", "2025-01-02"]),
]
self.assertEqual(
@@ -157,28 +136,24 @@ class TestLifecycleResultsFormatter(SimpleTestCase):
def test_format_with_datetime_seconds(self):
results = [
_make_result(
- "$pageview",
"$pageview",
"new",
[100],
["2025-01-01T00:00:00-08:00"],
),
_make_result(
- "$pageview",
"$pageview",
"returning",
[50],
["2025-01-01T00:00:00-08:00"],
),
_make_result(
- "$pageview",
"$pageview",
"resurrecting",
[10],
["2025-01-01T00:00:00-08:00"],
),
_make_result(
- "$pageview",
"$pageview",
"dormant",
[-20],
diff --git a/ee/hogai/context/insight/format/test/test_stickiness.py b/ee/hogai/context/insight/format/test/test_stickiness.py
index ad1bfe110c49..639687fad63e 100644
--- a/ee/hogai/context/insight/format/test/test_stickiness.py
+++ b/ee/hogai/context/insight/format/test/test_stickiness.py
@@ -1,6 +1,8 @@
from django.test import SimpleTestCase
-from posthog.schema import AssistantStickinessQuery
+from parameterized import parameterized
+
+from posthog.schema import AssistantStickinessEventsNode, AssistantStickinessQuery
from .. import StickinessResultsFormatter
@@ -14,13 +16,7 @@ class TestStickinessResultsFormatter(SimpleTestCase):
"days": [1, 2, 3, 4],
"labels": ["1 day", "2 days", "3 days", "4 days"],
"label": "$pageview",
- "action": {
- "order": 0,
- "type": "events",
- "name": "$pageview",
- "id": "$pageview",
- "custom_name": None,
- },
+ "order": 0,
}
]
@@ -37,13 +33,7 @@ class TestStickinessResultsFormatter(SimpleTestCase):
"days": [1, 2, 3],
"labels": ["1 day", "2 days", "3 days"],
"label": "$pageview",
- "action": {
- "order": 0,
- "type": "events",
- "name": "$pageview",
- "id": "$pageview",
- "custom_name": None,
- },
+ "order": 0,
},
{
"count": 300,
@@ -51,13 +41,7 @@ class TestStickinessResultsFormatter(SimpleTestCase):
"days": [1, 2, 3],
"labels": ["1 day", "2 days", "3 days"],
"label": "signup",
- "action": {
- "order": 1,
- "type": "events",
- "name": "signup",
- "id": "signup",
- "custom_name": None,
- },
+ "order": 1,
},
]
@@ -76,13 +60,7 @@ class TestStickinessResultsFormatter(SimpleTestCase):
"label": "$pageview",
"compare": True,
"compare_label": "previous",
- "action": {
- "order": 0,
- "type": "events",
- "name": "$pageview",
- "id": "$pageview",
- "custom_name": None,
- },
+ "order": 0,
},
{
"count": 500,
@@ -92,13 +70,7 @@ class TestStickinessResultsFormatter(SimpleTestCase):
"label": "$pageview",
"compare": True,
"compare_label": "current",
- "action": {
- "order": 0,
- "type": "events",
- "name": "$pageview",
- "id": "$pageview",
- "custom_name": None,
- },
+ "order": 0,
},
]
@@ -113,7 +85,13 @@ class TestStickinessResultsFormatter(SimpleTestCase):
"No data recorded for this time period.",
)
- def test_stickiness_custom_name(self):
+ @parameterized.expand(
+ [
+ ("custom_name", AssistantStickinessEventsNode(event="$pageview", custom_name="Page Views")),
+ ("name_rename", AssistantStickinessEventsNode(event="$pageview", name="Page Views")),
+ ]
+ )
+ def test_stickiness_renamed_series(self, _name, series):
results = [
{
"count": 300,
@@ -121,18 +99,12 @@ class TestStickinessResultsFormatter(SimpleTestCase):
"days": [1, 2, 3],
"labels": ["1 day", "2 days", "3 days"],
"label": "$pageview",
- "action": {
- "order": 0,
- "type": "events",
- "name": "$pageview",
- "id": "$pageview",
- "custom_name": "Page Views",
- },
+ "order": 0,
}
]
self.assertEqual(
- StickinessResultsFormatter(AssistantStickinessQuery(series=[]), results).format(),
+ StickinessResultsFormatter(AssistantStickinessQuery(series=[series]), results).format(),
"Interval|Page Views\n1 day|100\n2 days|120\n3 days|80",
)
@@ -144,13 +116,7 @@ class TestStickinessResultsFormatter(SimpleTestCase):
"days": [1, 2, 3],
"labels": ["1 day or more", "2 days or more", "3 days or more"],
"label": "$pageview",
- "action": {
- "order": 0,
- "type": "events",
- "name": "$pageview",
- "id": "$pageview",
- "custom_name": None,
- },
+ "order": 0,
}
]
diff --git a/ee/hogai/context/insight/format/test/test_trends.py b/ee/hogai/context/insight/format/test/test_trends.py
index d32f99204218..27e6afe93c9c 100644
--- a/ee/hogai/context/insight/format/test/test_trends.py
+++ b/ee/hogai/context/insight/format/test/test_trends.py
@@ -5,7 +5,16 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
-from posthog.schema import AssistantDateRange, AssistantTrendsQuery, Compare, IntervalType
+from posthog.schema import (
+ AssistantDateRange,
+ AssistantTrendsActionsNode,
+ AssistantTrendsEventsNode,
+ AssistantTrendsFilter,
+ AssistantTrendsQuery,
+ Compare,
+ IntervalType,
+ TrendsFormulaNode,
+)
from .. import TrendsResultsFormatter
@@ -19,19 +28,7 @@ class TestTrendsResultsFormatter(BaseTest):
"days": ["2025-01-23", "2025-01-24", "2025-01-25"],
"count": 288,
"label": "$pageview",
- "action": {
- "days": ["2025-01-23T00:00:00+01:00", "2025-01-24T00:00:00+01:00", "2025-01-25T00:00:00+01:00"],
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "name": "$pageview",
- "custom_name": None,
- "math": "total",
- "math_property": None,
- "math_hogql": None,
- "math_group_type_index": None,
- "properties": {},
- },
+ "order": 0,
}
]
@@ -107,22 +104,64 @@ class TestTrendsResultsFormatter(BaseTest):
"Date|$pageview\n2025-01-20|242\n2025-01-21|46\n2025-01-22|0",
)
- def test_trends_breakdown_and_custom_name_label(self):
- series = {
- "data": [242, 46, 0],
- "labels": ["20-Jan-2025", "21-Jan-2025", "22-Jan-2025"],
- "days": ["2025-01-20", "2025-01-21", "2025-01-22"],
- "breakdown_value": 0,
- "label": "$pageview",
- "action": {
- "custom_name": "Custom Name",
- },
- }
- formatter = TrendsResultsFormatter(AssistantTrendsQuery(series=[]), [series])
+ @parameterized.expand(
+ [
+ (
+ "breakdown_with_custom_name",
+ AssistantTrendsQuery(series=[AssistantTrendsEventsNode(event="$pageview", custom_name="Views")]),
+ [{"label": "Chrome", "order": 0, "breakdown_value": "Chrome"}],
+ None,
+ "Date|Views breakdown for the value `Chrome`",
+ ),
+ (
+ "breakdown_without_rename",
+ AssistantTrendsQuery(series=[AssistantTrendsEventsNode(event="$pageview", name="$pageview")]),
+ [{"label": "Chrome", "order": 0, "breakdown_value": "Chrome"}],
+ None,
+ "Date|Chrome breakdown for the value `Chrome`",
+ ),
+ (
+ "each_row_takes_the_series_at_its_order",
+ AssistantTrendsQuery(
+ series=[
+ AssistantTrendsEventsNode(event="$pageview", name="$pageview"),
+ AssistantTrendsEventsNode(event="sign up", name="Registrations"),
+ ]
+ ),
+ [{"label": "$pageview", "order": 0}, {"label": "sign up", "order": 1}],
+ None,
+ "Date|$pageview|Registrations",
+ ),
+ (
+ "an_action_keeps_the_name_it_was_saved_with",
+ AssistantTrendsQuery(series=[AssistantTrendsActionsNode(id=7, name="Old purchase name")]),
+ [{"label": "Purchase made", "order": 0}],
+ {7: "Purchase made"},
+ "Date|Old purchase name",
+ ),
+ (
+ "formula_rows_take_no_series_name",
+ AssistantTrendsQuery(
+ series=[
+ AssistantTrendsEventsNode(event="$pageview", custom_name="Views"),
+ AssistantTrendsEventsNode(event="sign up", custom_name="Registrations"),
+ ],
+ trendsFilter=AssistantTrendsFilter(
+ formulaNodes=[TrendsFormulaNode(formula="A+B"), TrendsFormulaNode(formula="A-B")]
+ ),
+ ),
+ [{"label": "Formula (A+B)", "order": 0}, {"label": "Formula (A-B)", "order": 1}],
+ None,
+ "Date|Formula (A+B)|Formula (A-B)",
+ ),
+ ]
+ )
+ def test_trends_series_label(self, _name, query, rows, action_names, expected_header):
+ results = [{"data": [1], "labels": ["20-Jan-2025"], "days": ["2025-01-20"], **row} for row in rows]
- self.assertEqual(formatter._extract_series_label(series), "Custom Name breakdown for the value `0`")
- series.pop("action")
- self.assertEqual(formatter._extract_series_label(series), "$pageview breakdown for the value `0`")
+ formatted = TrendsResultsFormatter(query, results, action_names=action_names).format()
+
+ self.assertEqual(formatted.split("\n")[0], expected_header)
def test_trends_marks_partial_current_and_future_buckets(self):
# now is midday on the 25th (UTC), so the 25th's bucket is still collecting and the 26th is
@@ -218,14 +257,11 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 993,
"label": "$pageview",
- "action": {
- "days": ["2025-01-20", "2025-01-21", "2025-01-22"],
- },
}
]
self.assertEqual(
TrendsResultsFormatter(AssistantTrendsQuery(series=[]), results).format(),
- "Date range|Aggregated value for $pageview\n2025-01-20 to 2025-01-22|993",
+ "Date range|Aggregated value for $pageview\nAll time|993",
)
@parameterized.expand(
@@ -253,7 +289,6 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 82,
"label": "$pageview",
- "action": {"days": ["2026-10-12 00:00:00-07:00", "2026-10-13 00:00:00-07:00"]},
}
]
self.assertEqual(
@@ -271,9 +306,6 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 993,
"label": "$pageview",
- "action": {
- "days": ["2025-01-20", "2025-01-21", "2025-01-22"],
- },
},
{
"data": [],
@@ -281,14 +313,11 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 1000,
"label": "$pageleave",
- "action": {
- "days": ["2025-01-20", "2025-01-21", "2025-01-22"],
- },
},
]
self.assertEqual(
TrendsResultsFormatter(AssistantTrendsQuery(series=[]), results).format(),
- "Date range|Aggregated value for $pageview|Aggregated value for $pageleave\n2025-01-20 to 2025-01-22|993|1000",
+ "Date range|Aggregated value for $pageview|Aggregated value for $pageleave\nAll time|993|1000",
)
@parameterized.expand(
@@ -302,17 +331,15 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 993,
"label": "$pageview",
- "action": {"days": ["2025-01-20", "2025-01-21", "2025-01-22"]},
},
{
"data": [],
"days": [],
"count": 0,
"label": "$pageleave",
- "action": {"days": ["2025-01-20", "2025-01-21", "2025-01-22"]},
},
],
- "Date range|Aggregated value for $pageview|Aggregated value for $pageleave\n2025-01-20 to 2025-01-22|993|N/A",
+ "Date range|Aggregated value for $pageview|Aggregated value for $pageleave\nAll time|993|N/A",
),
(
"aggregated_series_second",
@@ -322,7 +349,6 @@ class TestTrendsResultsFormatter(BaseTest):
"days": [],
"count": 0,
"label": "$pageleave",
- "action": {"days": ["2025-01-20", "2025-01-21", "2025-01-22"]},
},
{
"data": [],
@@ -330,10 +356,9 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 993,
"label": "$pageview",
- "action": {"days": ["2025-01-20", "2025-01-21", "2025-01-22"]},
},
],
- "Date range|Aggregated value for $pageleave|Aggregated value for $pageview\n2025-01-20 to 2025-01-22|N/A|993",
+ "Date range|Aggregated value for $pageleave|Aggregated value for $pageview\nAll time|N/A|993",
),
]
)
@@ -351,7 +376,6 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 92.22,
"label": "Bounce rate",
- "action": None,
"breakdown_value": ["/news-research"],
}
]
@@ -368,9 +392,6 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 993,
"label": "$pageview",
- "action": {
- "days": ["2025-01-20", "2025-01-21", "2025-01-22"],
- },
"compare": True,
"compare_label": Compare.PREVIOUS,
},
@@ -380,9 +401,6 @@ class TestTrendsResultsFormatter(BaseTest):
"count": 0,
"aggregated_value": 1000,
"label": "$pageview",
- "action": {
- "days": ["2025-01-20", "2025-01-21", "2025-01-22"],
- },
"compare": True,
"compare_label": Compare.CURRENT,
},
diff --git a/ee/hogai/context/insight/format/trends.py b/ee/hogai/context/insight/format/trends.py
index 90f0ad3b0381..1b1aa633aefb 100644
--- a/ee/hogai/context/insight/format/trends.py
+++ b/ee/hogai/context/insight/format/trends.py
@@ -1,3 +1,4 @@
+from collections.abc import Mapping
from datetime import UTC, datetime
from typing import Any, Optional
@@ -5,6 +6,7 @@ from posthog.schema import AssistantTrendsQuery, Compare, DateRange, TrendsQuery
from posthog.hogql_queries.utils.breakdowns import humanize_breakdown_label
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.hogql_queries.utils.result_series import get_result_series, get_series_custom_name
from posthog.models import Team
from .utils import (
@@ -43,13 +45,16 @@ class TrendsResultsFormatter:
utc_now_datetime: Optional[datetime] = None,
resolved_date_range: Optional[dict[str, Any]] = None,
resolved_compare_date_range: Optional[dict[str, Any]] = None,
+ action_names: Optional[Mapping[int, str | None]] = None,
):
self._query = query
+ self._query_dict = query.model_dump(mode="json")
self._results = results
self._team = team
self._utc_now_datetime = utc_now_datetime or datetime.now(UTC)
self._resolved_date_range = resolved_date_range
self._resolved_compare_date_range = resolved_compare_date_range
+ self._action_names = action_names
def format(self) -> str:
results = self._results
@@ -67,7 +72,7 @@ class TrendsResultsFormatter:
# If there isn't data in comparison, the series will be omitted.
if len(previous) > 0 and len(current) > 0:
- # `action.days` holds the current period's days on both series, so aggregated rows take their range from the response.
+ # Each period labels its aggregated rows with its own resolved range.
previous_formatted = self._format_results(previous, self._resolved_compare_date_range)
current_formatted = self._format_results(current, self._resolved_date_range)
template = f"Previous period:\n{previous_formatted}\n\nCurrent period:\n{current_formatted}"
@@ -80,9 +85,8 @@ class TrendsResultsFormatter:
def _format_aggregated_values(
self, results: list[dict[str, Any]], resolved_date_range: Optional[dict[str, Any]] = None
) -> str:
- # Get dates and series labels
- result = results[0]
- dates = (result.get("action") or {}).get("days") or []
+ # Aggregated rows hold no `days`, so without a resolved range only a leading time-series row supplies dates.
+ dates = results[0].get("days") or []
if resolved_date_range and resolved_date_range.get("date_from") and resolved_date_range.get("date_to"):
range = f"{_format_range_bound(resolved_date_range['date_from'])} to {_format_range_bound(resolved_date_range['date_to'])}"
elif len(dates) == 0:
@@ -154,12 +158,9 @@ class TrendsResultsFormatter:
return partial_bucket_flags(dates, current_interval_start), self._team.timezone
def _extract_series_label(self, series: dict[str, Any]) -> str:
- action = series.get("action")
- name = series["label"]
- if isinstance(action, dict):
- custom_name = action.get("custom_name")
- if custom_name is not None:
- name = custom_name
+ node = get_result_series(self._query_dict, series)
+ custom_name = get_series_custom_name(node, self._action_names) if node is not None else None
+ name = custom_name if custom_name is not None else series["label"]
if series.get("breakdown_value") is not None:
if isinstance(series["breakdown_value"], list):
breakdown_label = ", ".join(str(v) for v in series["breakdown_value"])
diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.py
index ddf632607e1c..eebb58cb46a9 100644
--- a/ee/hogai/context/insight/query_executor.py
+++ b/ee/hogai/context/insight/query_executor.py
@@ -71,6 +71,7 @@ from posthog.exceptions import (
QueryRanConcurrently,
)
from posthog.hogql_queries.query_runner import BLOCKING_EXECUTION_MODES, ExecutionMode
+from posthog.hogql_queries.utils.result_series import get_action_names
from posthog.models import Team
from posthog.sync import database_sync_to_async
@@ -646,6 +647,12 @@ class AssistantQueryExecutor:
logger.warning(f"{TIMING_LOG_PREFIX} aexecute_query completed successfully in {total_elapsed:.3f}s")
return response_dict
+ async def _get_action_names(self, query: BaseModel) -> dict[int, str | None]:
+ # The formatters label an action series by the action's current name, which only the database holds.
+ return await database_sync_to_async(get_action_names, thread_sensitive=False)(
+ self._team, query.model_dump(mode="json")
+ )
+
async def _compress_results(
self,
query: AnyPydanticModelQuery | AnyAssistantGeneratedQuery,
@@ -698,6 +705,7 @@ class AssistantQueryExecutor:
self._utc_now_datetime,
resolved_date_range=response.get("resolved_date_range"),
resolved_compare_date_range=response.get("resolved_compare_date_range"),
+ action_names=await self._get_action_names(query),
).format()
elif isinstance(query, AssistantFunnelsQuery | FunnelsQuery):
formatter_name = "FunnelResultsFormatter"
@@ -706,13 +714,17 @@ class AssistantQueryExecutor:
result = await database_sync_to_async(formatter.format, thread_sensitive=False)()
elif isinstance(query, AssistantLifecycleQuery | LifecycleQuery):
formatter_name = "LifecycleResultsFormatter"
- result = LifecycleResultsFormatter(query, response["results"]).format()
+ result = LifecycleResultsFormatter(
+ query, response["results"], action_names=await self._get_action_names(query)
+ ).format()
elif isinstance(query, AssistantPathsQuery | PathsQuery):
formatter_name = "PathsResultsFormatter"
result = PathsResultsFormatter(response["results"]).format()
elif isinstance(query, AssistantStickinessQuery | StickinessQuery):
formatter_name = "StickinessResultsFormatter"
- result = StickinessResultsFormatter(query, response["results"]).format()
+ result = StickinessResultsFormatter(
+ query, response["results"], action_names=await self._get_action_names(query)
+ ).format()
elif isinstance(query, AssistantRetentionQuery | RetentionQuery):
formatter_name = "RetentionResultsFormatter"
result = RetentionResultsFormatter(query, response["results"]).format()
diff --git a/posthog/caching/calculate_results.py b/posthog/caching/calculate_results.py
index de6142ecfffd..acec9e39ccdf 100644
--- a/posthog/caching/calculate_results.py
+++ b/posthog/caching/calculate_results.py
@@ -172,6 +172,7 @@ def calculate_for_query_based_insight(
hogql=getattr(process_response, "hogql", None),
types=getattr(process_response, "types", None),
resolved_date_range=_model_field_as_dict(process_response, "resolved_date_range"),
+ resolved_compare_date_range=_model_field_as_dict(process_response, "resolved_compare_date_range"),
query_scan=_model_field_as_dict(process_response, "query_scan"),
warnings=_model_list_field_as_dicts(process_response, "warnings"),
)
@@ -196,6 +197,7 @@ def calculate_for_query_based_insight(
hogql=response.get("hogql"),
types=response.get("types"),
resolved_date_range=response.get("resolved_date_range"),
+ resolved_compare_date_range=response.get("resolved_compare_date_range"),
query_scan=response.get("query_scan"),
warnings=response.get("warnings"),
)
diff --git a/posthog/caching/insight_result.py b/posthog/caching/insight_result.py
index 0429c121dc95..24b2ed219a0b 100644
--- a/posthog/caching/insight_result.py
+++ b/posthog/caching/insight_result.py
@@ -20,8 +20,9 @@ class InsightResult:
query_status: Optional[Any] = None
hogql: Optional[str] = None
types: Optional[list] = None
- # A ResolvedDateRangeResponse-shaped dict — the field carries model_dump output
+ # ResolvedDateRangeResponse-shaped dicts — the fields carry model_dump output
resolved_date_range: Optional[dict] = None
+ resolved_compare_date_range: Optional[dict] = None
# A QueryScanSummary dict. The insight serializer puts the stored analysis on it.
query_scan: Optional[dict] = None
warnings: Optional[list] = None
diff --git a/posthog/hogql_queries/utils/result_series.py b/posthog/hogql_queries/utils/result_series.py
new file mode 100644
index 000000000000..9181acd91e0d
--- /dev/null
+++ b/posthog/hogql_queries/utils/result_series.py
@@ -0,0 +1,135 @@
+"""Resolve a trends, stickiness or lifecycle result row to the query series it reports.
+
+These mirror `getResultSeries` and `getResultSeriesIndex` in `frontend/src/scenes/insights/utils/resultSeries.ts`, so
+backend readers identify series by the rules the frontend uses, without the legacy `action` field on result rows.
+Queries, rows and series nodes are JSON-shaped, as stored on an insight or dumped from a schema model.
+"""
+
+from collections.abc import Iterator, Mapping
+from typing import TYPE_CHECKING, Any
+
+from products.actions.backend.models.action import Action
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+WAREHOUSE_NODE_KINDS = frozenset({"DataWarehouseNode", "LifecycleDataWarehouseNode"})
+
+
+def get_result_order(result: Mapping[str, Any]) -> int:
+ """The row's series index, or its formula index on a formula row."""
+ order = result.get("order")
+ return order if isinstance(order, int) else 0
+
+
+def has_formula_results(query: Mapping[str, Any]) -> bool:
+ """Whether the query returns formula rows in place of series rows.
+
+ This mirrors the trends runner, which reads `formulaNodes`, then `formulas`, then `formula`, and ignores an empty
+ list or string. The calendar heatmap runner ignores formulas and reports series 0, so its query keeps its formulas
+ without returning formula rows.
+ """
+ if query.get("kind") != "TrendsQuery":
+ return False
+ trends_filter = query.get("trendsFilter") or {}
+ if trends_filter.get("display") == "CalendarHeatmap":
+ return False
+ return bool(trends_filter.get("formulaNodes") or trends_filter.get("formulas") or trends_filter.get("formula"))
+
+
+def get_result_series_index(query: Mapping[str, Any], result: Mapping[str, Any]) -> int | None:
+ """The query series index of a series row. None on a formula row, because its `order` indexes the formulas."""
+ return None if has_formula_results(query) else get_result_order(result)
+
+
+def get_result_series(query: Mapping[str, Any], result: Mapping[str, Any]) -> Mapping[str, Any] | None:
+ """The query series node the row reports. None on a formula row, and on a row whose series the query does not hold."""
+ index = get_result_series_index(query, result)
+ series = query.get("series")
+ if index is None or not isinstance(series, list) or not 0 <= index < len(series):
+ return None
+ node = series[index]
+ return node if isinstance(node, Mapping) else None
+
+
+def get_action_names(team: "Team", query: Mapping[str, Any]) -> dict[int, str | None]:
+ """The current names of the actions the query's series reference, which the runners label action series with."""
+ action_ids = {action_id for node in _series_nodes(query) if (action_id := _action_id(node)) is not None}
+ if not action_ids:
+ return {}
+ return dict(Action.objects.filter(pk__in=action_ids, team__project_id=team.project_id).values_list("pk", "name"))
+
+
+def get_series_key(node: Mapping[str, Any], action_names: Mapping[int, str | None] | None = None) -> str | None:
+ """The key the runners label a series with: its event, its table, its action's name, or a group's member keys.
+
+ None for an all-events series. The query does not hold an action's name, so without `action_names` an action has
+ no key, as on the frontend, and a group takes the names its member actions were saved with.
+ """
+ kind = node.get("kind")
+ if kind == "EventsNode":
+ return node.get("event")
+ if kind in WAREHOUSE_NODE_KINDS:
+ return node.get("table_name")
+ if kind == "ActionsNode":
+ action_id = _action_id(node)
+ return action_names.get(action_id) if action_names is not None and action_id is not None else None
+ if kind != "GroupNode":
+ return None
+ member_keys: list[str] = []
+ for member in node.get("nodes") or []:
+ member_key = _group_member_key(member, action_names)
+ if member_key is None:
+ return None
+ member_keys.append(member_key)
+ return ", ".join(member_keys)
+
+
+def get_series_custom_name(node: Mapping[str, Any], action_names: Mapping[int, str | None] | None = None) -> str | None:
+ """The series' rename, by the rule the trends runner applies to `custom_name`.
+
+ That is the custom name, or a `name` other than the key the series queries. Without `action_names` an action has
+ no key, so only its custom name counts.
+ """
+ custom_name = node.get("custom_name")
+ if isinstance(custom_name, str) and custom_name:
+ return custom_name
+ name = node.get("name")
+ if not isinstance(name, str) or not name:
+ return None
+ if node.get("kind") == "ActionsNode" and action_names is None:
+ return None
+ return name if name != get_series_key(node, action_names) else None
+
+
+def _series_nodes(query: Mapping[str, Any]) -> Iterator[Mapping[str, Any]]:
+ # Actors queries hold the index of one series in `series`, not a list of nodes.
+ series = query.get("series")
+ if not isinstance(series, list):
+ return
+ for node in series:
+ if isinstance(node, Mapping):
+ yield node
+ yield from (member for member in node.get("nodes") or [] if isinstance(member, Mapping))
+
+
+def _action_id(node: Mapping[str, Any]) -> int | None:
+ if node.get("kind") != "ActionsNode":
+ return None
+ try:
+ return int(node["id"])
+ except (KeyError, TypeError, ValueError):
+ return None
+
+
+def _group_member_key(member: Mapping[str, Any], action_names: Mapping[int, str | None] | None) -> str | None:
+ kind = member.get("kind")
+ if kind == "EventsNode":
+ event = member.get("event")
+ return "All events" if event is None else event
+ if kind == "ActionsNode":
+ if action_names is None:
+ return member.get("name") or None
+ action_id = _action_id(member)
+ return (action_names.get(action_id) if action_id is not None else None) or "Unnamed action"
+ return get_series_key(member, action_names)
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index c7e0a0c94f10..588296a43847 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -66,6 +66,7 @@ from posthog.api.sharing_publish_gate import (
from posthog.api.streaming import sse_streaming_response
from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin
from posthog.api.utils import action
+from posthog.caching.insight_result import InsightResult
from posthog.clickhouse.client.async_task_chain import task_chain_context
from posthog.constants import GENERATED_DASHBOARD_PREFIX, AvailableFeature
from posthog.dataclasses import frozen
@@ -3755,13 +3756,18 @@ class DashboardsViewSet(
break
tile_context = {**context, "dashboard_tile": tile, "order": order}
- tile_data = DashboardTileResultSerializer(tile, context=tile_context).data
+ tile_serializer = DashboardTileResultSerializer(tile, context=tile_context)
+ tile_data = tile_serializer.data
if output_format == "optimized":
insight_data = tile_data.get("insight") or {}
raw_result = insight_data.get("result")
if insight_data and raw_result is not None:
- formatted = self._format_insight_for_llm(insight, insight_data)
+ # The serializer memoizes the insight result, so this reads the response it just rendered.
+ insight_result = cast(InsightResultSerializer, tile_serializer.fields["insight"]).insight_result(
+ insight
+ )
+ formatted = self._format_insight_for_llm(insight, insight_data, insight_result)
if formatted is None:
# No formatter covers this query type, so the raw result still has to be bounded.
formatted = render_unsupported_result(raw_result)
@@ -4086,7 +4092,9 @@ class DashboardsViewSet(
return tile
- def _format_insight_for_llm(self, insight: Insight, insight_data: dict) -> str | None:
+ def _format_insight_for_llm(
+ self, insight: Insight, insight_data: dict, insight_result: InsightResult
+ ) -> str | None:
if not settings.EE_AVAILABLE:
return None
try:
@@ -4098,7 +4106,13 @@ class DashboardsViewSet(
query = InsightVizNode.model_validate(query_dict)
if not query.source:
return None
- result_dict = {"results": insight_data.get("result"), "columns": insight_data.get("columns")}
+ result_dict = {
+ "results": insight_data.get("result"),
+ "columns": insight_data.get("columns"),
+ # Total-value rows carry no dates, so the formatter labels them with the ranges the query ran over.
+ "resolved_date_range": insight_result.resolved_date_range,
+ "resolved_compare_date_range": insight_result.resolved_compare_date_range,
+ }
return format_query_results_for_llm(query.source, result_dict, self.team)
except Exception:
logger.warning("dashboard_run_insights_format_failed", exc_info=True, insight_id=insight.id)
diff --git a/products/dashboards/backend/api/test/test_run_insights.py b/products/dashboards/backend/api/test/test_run_insights.py
index c09cc3fe75fd..127e77b5e466 100644
--- a/products/dashboards/backend/api/test/test_run_insights.py
+++ b/products/dashboards/backend/api/test/test_run_insights.py
@@ -3,18 +3,29 @@ import json
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
-from posthog.schema import DateRange, EventsNode, InsightVizNode, TrendsFilter, TrendsQuery
+from posthog.schema import (
+ ActionsNode,
+ ChartDisplayType,
+ CompareFilter,
+ DateRange,
+ EventsNode,
+ InsightVizNode,
+ TrendsFilter,
+ TrendsQuery,
+)
from posthog.api.test.dashboards import DashboardAPI
from posthog.caching.insight_result import InsightResult
from posthog.models.organization import Organization
from posthog.models.team import Team
+from products.actions.backend.models.action import Action
from products.dashboards.backend.access import DashboardAccessMethod
from products.dashboards.backend.api.dashboard import DashboardsViewSet
from products.dashboards.backend.constants import RUN_INSIGHTS_MIN_TILE_CHARS
@@ -23,12 +34,20 @@ from products.dashboards.backend.models.dashboard_tile import DashboardTile, Tex
from products.product_analytics.backend.facade.models import Insight, InsightVariable
-def _trends_query_dict(event: str = "$pageview", date_from: str = "-7d") -> dict:
+def _trends_query_dict(
+ event: str = "$pageview",
+ date_from: str = "-7d",
+ *,
+ series: list[EventsNode | ActionsNode] | None = None,
+ display: ChartDisplayType = ChartDisplayType.ACTIONS_LINE_GRAPH,
+ compare_filter: CompareFilter | None = None,
+) -> dict:
return InsightVizNode(
source=TrendsQuery(
- series=[EventsNode(event=event)],
+ series=series or [EventsNode(event=event)],
dateRange=DateRange(date_from=date_from),
- trendsFilter=TrendsFilter(display="ActionsLineGraph"),
+ trendsFilter=TrendsFilter(display=display),
+ compareFilter=compare_filter,
),
).model_dump()
@@ -107,6 +126,23 @@ class TestDashboardRunInsights(APIBaseTest):
if isinstance(result, str):
self.assertIn("|", result)
+ @override_settings(IN_UNIT_TESTING=True)
+ def test_optimized_format_labels_compared_totals_with_their_ranges_and_saved_series_names(self) -> None:
+ action = Action.objects.create(team=self.team, name="Purchase made", steps_json=[{"event": "purchase"}])
+ query = _trends_query_dict(
+ series=[ActionsNode(id=action.pk, name="Old purchase name")],
+ display=ChartDisplayType.BOLD_NUMBER,
+ compare_filter=CompareFilter(compare=True),
+ )
+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})
+ self.dashboard_api.create_insight({"name": "A", "query": query, "dashboards": [dashboard_id]})
+
+ result = self._run(dashboard_id, refresh="blocking")["results"][0]["insight"]["result"]
+
+ assert isinstance(result, str)
+ self.assertEqual(result.count("Aggregated value for Old purchase name"), 2)
+ self.assertNotIn("All time", result)
+
@parameterized.expand([("json",), ("optimized",)])
@patch("posthog.caching.calculate_results.calculate_for_query_based_insight")
def test_a_tile_carries_its_warehouse_sync_warnings(self, output_format: str, mock_calculate: MagicMock) -> None: