: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(max): label the previous period with its own dates in trends tables (#112040)
posthog[bot]e604720dce86
diff --git a/ee/hogai/context/insight/format/__init__.py b/ee/hogai/context/insight/format/__init__.pyindex a9c3d5daf899..53502d12bf73 100644--- a/ee/hogai/context/insight/format/__init__.py+++ b/ee/hogai/context/insight/format/__init__.py@@ -99,7 +99,14 @@ def format_query_results_for_llm(if is_boxplot_query(query):formatted = BoxPlotResultsFormatter(get_boxplot_results(response)).format()else:- formatted = TrendsResultsFormatter(query, response["results"], team, utc_now).format()+ formatted = TrendsResultsFormatter(+ query,+ response["results"],+ team,+ utc_now,+ resolved_date_range=response.get("resolved_date_range"),+ resolved_compare_date_range=response.get("resolved_compare_date_range"),+ ).format()elif isinstance(query, AssistantFunnelsQuery | FunnelsQuery):formatted = FunnelResultsFormatter(query, response["results"], team, utc_now).format()elif isinstance(query, AssistantLifecycleQuery | LifecycleQuery):diff --git a/ee/hogai/context/insight/format/test/test_trends.py b/ee/hogai/context/insight/format/test/test_trends.pyindex 1beb997f2948..657666bd9a15 100644--- a/ee/hogai/context/insight/format/test/test_trends.py+++ b/ee/hogai/context/insight/format/test/test_trends.py@@ -1,4 +1,5 @@from datetime import UTC, datetime+from zoneinfo import ZoneInfofrom posthog.test.base import BaseTest@@ -333,7 +334,7 @@ class TestTrendsResultsFormatter(BaseTest):"aggregated_value": 993,"label": "$pageview","action": {- "days": ["2025-01-17", "2025-01-18", "2025-01-19"],+ "days": ["2025-01-20", "2025-01-21", "2025-01-22"],},"compare": True,"compare_label": Compare.PREVIOUS,@@ -352,6 +353,17 @@ class TestTrendsResultsFormatter(BaseTest):},]self.assertEqual(- TrendsResultsFormatter(AssistantTrendsQuery(series=[]), results).format(),- "Previous period:\nDate range|Aggregated value for $pageview\n2025-01-17 to 2025-01-19|993\n\nCurrent period:\nDate range|Aggregated value for $pageview\n2025-01-20 to 2025-01-22|1000",+ TrendsResultsFormatter(+ AssistantTrendsQuery(series=[]),+ results,+ resolved_date_range={+ "date_from": "2025-01-20T00:00:00-08:00",+ "date_to": "2025-01-22T23:59:59.999999-08:00",+ },+ resolved_compare_date_range={+ "date_from": datetime(2025, 1, 17, tzinfo=ZoneInfo("America/Los_Angeles")),+ "date_to": datetime(2025, 1, 19, 23, 59, 59, 999999, tzinfo=ZoneInfo("America/Los_Angeles")),+ },+ ).format(),+ "Previous period:\nDate range|Aggregated value for $pageview\n2025-01-17 00:00:00-08:00 to 2025-01-19 23:59:59-08:00|993\n\nCurrent period:\nDate range|Aggregated value for $pageview\n2025-01-20 00:00:00-08:00 to 2025-01-22 23:59:59-08:00|1000",)diff --git a/ee/hogai/context/insight/format/trends.py b/ee/hogai/context/insight/format/trends.pyindex b5ee233845bf..d51cc05bf1c7 100644--- a/ee/hogai/context/insight/format/trends.py+++ b/ee/hogai/context/insight/format/trends.py@@ -17,6 +17,12 @@ from .utils import ()+def _format_range_bound(value: datetime | str) -> str:+ if isinstance(value, str):+ value = datetime.fromisoformat(value)+ return str(value.replace(microsecond=0))++class TrendsResultsFormatter:"""Compresses and formats trends results into a LLM-friendly string.@@ -35,11 +41,15 @@ class TrendsResultsFormatter:results: list[dict[str, Any]],team: Optional[Team] = None,utc_now_datetime: Optional[datetime] = None,+ resolved_date_range: Optional[dict[str, Any]] = None,+ resolved_compare_date_range: Optional[dict[str, Any]] = None,):self._query = queryself._results = resultsself._team = teamself._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_rangedef format(self) -> str:results = self._results@@ -57,16 +67,23 @@ class TrendsResultsFormatter:# If there isn't data in comparison, the series will be omitted.if len(previous) > 0 and len(current) > 0:- template = f"Previous period:\n{self._format_results(previous)}\n\nCurrent period:\n{self._format_results(current)}"+ # `action.days` holds the current period's days on both series, so aggregated rows take their range from the response.+ 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}"return templatereturn self._format_results(results)- def _format_aggregated_values(self, results: list[dict[str, Any]]) -> str:+ def _format_aggregated_values(+ self, results: list[dict[str, Any]], resolved_date_range: Optional[dict[str, Any]] = None+ ) -> str:# Get dates and series labelsresult = results[0]dates = (result.get("action") or {}).get("days") or []- if len(dates) == 0:+ 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:range = "All time"else:range = f"{dates[0]} to {dates[-1]}"@@ -150,11 +167,11 @@ class TrendsResultsFormatter:return humanize_breakdown_label(name)- def _format_results(self, results: list[dict]) -> str:+ def _format_results(self, results: list[dict], resolved_date_range: Optional[dict[str, Any]] = None) -> str:# Route on any aggregated series rather than the first, because a mixed set can lead# with a time-series series while a later one carries the aggregate.aggregation_applied = any(series.get("aggregated_value") is not None for series in results)if aggregation_applied:- return self._format_aggregated_values(results)+ return self._format_aggregated_values(results, resolved_date_range)else:return self._format_non_aggregated_values(results)diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex 8c82e085d326..27c084e9b75d 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -631,7 +631,12 @@ class AssistantQueryExecutor:else:formatter_name = "TrendsResultsFormatter"result = TrendsResultsFormatter(- query, response["results"], self._team, self._utc_now_datetime+ query,+ response["results"],+ self._team,+ self._utc_now_datetime,+ resolved_date_range=response.get("resolved_date_range"),+ resolved_compare_date_range=response.get("resolved_compare_date_range"),).format()elif isinstance(query, AssistantFunnelsQuery | FunnelsQuery):formatter_name = "FunnelResultsFormatter"