: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(phai): flag partial and future trends/funnel buckets in MCP output (#71796)
posthog[bot]2e5f4d143af2
diff --git a/ee/hogai/context/insight/format/__init__.py b/ee/hogai/context/insight/format/__init__.pyindex 1b53144f1be7..a1572e7d4f47 100644--- a/ee/hogai/context/insight/format/__init__.py+++ b/ee/hogai/context/insight/format/__init__.py@@ -109,7 +109,7 @@ def format_query_results_for_llm(if is_boxplot_query(query):formatted = BoxPlotResultsFormatter(get_boxplot_results(response)).format()else:- formatted = TrendsResultsFormatter(query, response["results"]).format()+ formatted = TrendsResultsFormatter(query, response["results"], team, utc_now).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/funnel.py b/ee/hogai/context/insight/format/funnel.pyindex 22c85dea04e6..92da32875899 100644--- a/ee/hogai/context/insight/format/funnel.py+++ b/ee/hogai/context/insight/format/funnel.py@@ -17,7 +17,16 @@ from posthog.schema import (from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models import Team-from .utils import format_duration, format_matrix, format_number, format_percentage, strip_datetime_seconds+from .utils import (+ PARTIAL_BUCKET_MARKER,+ format_duration,+ format_matrix,+ format_number,+ format_percentage,+ partial_bucket_flags,+ partial_bucket_note,+ strip_datetime_seconds,+)class FunnelResultsFormatter:@@ -66,6 +75,7 @@ class FunnelResultsFormatter:):self._query = queryself._results = results+ self._team = teamdate_range = DateRange.model_validate(query.dateRange.model_dump()) if query.dateRange else Noneself._query_date_range = QueryDateRange(date_range, team, query.interval, utc_now_datetime)@@ -198,7 +208,10 @@ class FunnelResultsFormatter:return formatted_matrixdef _format_time_range(self) -> str:- return f"Date range: {self._query_date_range.date_from_str} to {self._query_date_range.date_to_str}"+ return (+ f"Date range: {self._query_date_range.date_from_str} to {self._query_date_range.date_to_str} "+ f"({self._team.timezone})"+ )def _format_filter_series_label(self) -> str:series_labels: list[str] = []@@ -223,6 +236,10 @@ class FunnelResultsFormatter:dates = result["days"]label = self._format_filter_series_label()+ now_local = self._query_date_range.now_with_timezone.replace(tzinfo=None)+ current_interval_start = self._query_date_range.align_with_interval(now_local)+ partial = partial_bucket_flags(dates, current_interval_start)+# Build header rowheader = ["Date"]for series in results:@@ -239,10 +256,16 @@ class FunnelResultsFormatter:# Build data rowsfor i, date in enumerate(dates):- row = [strip_datetime_seconds(date)]+ date_cell = strip_datetime_seconds(date)+ if partial[i]:+ date_cell += PARTIAL_BUCKET_MARKER+ row = [date_cell]for series in results:row.append(format_percentage(series["data"][i] / 100))row.append(format_percentage((100 - series["data"][i]) / 100))matrix.append(row)- return format_matrix(matrix)+ formatted = format_matrix(matrix)+ if any(partial):+ formatted = f"{formatted}\n\n{partial_bucket_note(self._team.timezone)}"+ return formatteddiff --git a/ee/hogai/context/insight/format/test/test_format_query_results_for_llm.py b/ee/hogai/context/insight/format/test/test_format_query_results_for_llm.pyindex b561d6ee0378..ca7d3107d1b4 100644--- a/ee/hogai/context/insight/format/test/test_format_query_results_for_llm.py+++ b/ee/hogai/context/insight/format/test/test_format_query_results_for_llm.py@@ -1,4 +1,5 @@from typing import Any+from zoneinfo import ZoneInfofrom unittest import TestCasefrom unittest.mock import MagicMock@@ -21,6 +22,15 @@ from posthog.schema import (from .. import format_query_results_for_llm+def _mock_team() -> MagicMock:+ # Trends/funnel formatters build a QueryDateRange, which reads a real tzinfo off the team.+ team = MagicMock()+ team.timezone = "UTC"+ team.timezone_info = ZoneInfo("UTC")+ team.week_start_day = None+ return team++class TestFormatQueryResultsForLlm(TestCase):@parameterized.expand([@@ -96,7 +106,7 @@ class TestFormatQueryResultsForLlm(TestCase):])def test_dispatches_correctly(self, _name: str, query, response: dict, expected_substr: str):- team = MagicMock()+ team = _mock_team()result = format_query_results_for_llm(query, response, team)assert result is not Noneself.assertIn(expected_substr, result)@@ -131,7 +141,7 @@ class TestFormatQueryResultsForLlm(TestCase):])def test_envelope_nodes_are_unwrapped(self, _name: str, query, response: dict, expected_substr: str):- team = MagicMock()+ team = _mock_team()result = format_query_results_for_llm(query, response, team)assert result is not None, f"Expected a formatted result, got None for {_name}"self.assertIn(expected_substr, result)diff --git a/ee/hogai/context/insight/format/test/test_funnel.py b/ee/hogai/context/insight/format/test/test_funnel.pyindex dc1325826c95..ca9969f2c1f5 100644--- a/ee/hogai/context/insight/format/test/test_funnel.py+++ b/ee/hogai/context/insight/format/test/test_funnel.py@@ -1,4 +1,4 @@-from datetime import datetime+from datetime import UTC, datetimefrom typing import Anyfrom freezegun import freeze_time@@ -216,7 +216,7 @@ class TestFunnelResultsFormatter(BaseTest):self.team,datetime.now(),).format(),- 'Date range: 2025-01-31 00:00:00 to 2025-02-07 23:59:59\n\n---au\nMetric|$pageview|signup\nTotal person count|5|2\nConversion rate|100%|40%\nDropoff rate|0%|60%\nAverage conversion time|-|10s\nMedian conversion time|-|11s\n\n---us\nMetric|$pageview|signup\nTotal person count|5|2\nConversion rate|100%|40%\nDropoff rate|0%|60%\nAverage conversion time|-|10s\nMedian conversion time|-|11s\n\nConversion and drop-off rates are calculated in overall. For example, "Conversion rate: 9%" means that 9% of users from the first step completed the funnel.',+ 'Date range: 2025-01-31 00:00:00 to 2025-02-07 23:59:59 (UTC)\n\n---au\nMetric|$pageview|signup\nTotal person count|5|2\nConversion rate|100%|40%\nDropoff rate|0%|60%\nAverage conversion time|-|10s\nMedian conversion time|-|11s\n\n---us\nMetric|$pageview|signup\nTotal person count|5|2\nConversion rate|100%|40%\nDropoff rate|0%|60%\nAverage conversion time|-|10s\nMedian conversion time|-|11s\n\nConversion and drop-off rates are calculated in overall. For example, "Conversion rate: 9%" means that 9% of users from the first step completed the funnel.',)def test_funnels_time_to_convert(self):@@ -231,7 +231,7 @@ class TestFunnelResultsFormatter(BaseTest):results = {"average_conversion_time": 600, "bins": [[600, 1], [601, 0]]}self.assertEqual(FunnelResultsFormatter(query, results, self.team, datetime.now()).format(),- "Date range: 2025-01-20 00:00:00 to 2025-01-22 23:59:59\n\nEvents: $pageview (custom) -> $ai_trace\nAverage time to convert|User distribution\n10m|100%\n10m 1s|0%\n\nThe user distribution is the percentage of users who completed the funnel in the given period.",+ "Date range: 2025-01-20 00:00:00 to 2025-01-22 23:59:59 (UTC)\n\nEvents: $pageview (custom) -> $ai_trace\nAverage time to convert|User distribution\n10m|100%\n10m 1s|0%\n\nThe user distribution is the percentage of users who completed the funnel in the given period.",)def test_funnel_trends(self):@@ -256,6 +256,32 @@ class TestFunnelResultsFormatter(BaseTest):"Date|$pageview (custom) -> $ai_trace conversion|$pageview (custom) -> $ai_trace drop-off\n2025-01-08|10%|90%\n2025-01-09|15.5%|84.5%\n2025-01-10|0%|100%",)+ def test_funnel_trends_marks_partial_bucket(self):+ results = [+ {+ "count": 31,+ "data": [10, 15.5, 0],+ "days": ["2025-01-08", "2025-01-09", "2025-01-10"],+ "labels": ["8-Jan-2025", "9-Jan-2025", "10-Jan-2025"],+ }+ ]+ query = AssistantFunnelsQuery(+ series=[+ AssistantFunnelsEventsNode(event="$pageview", custom_name="custom"),+ AssistantFunnelsEventsNode(event="$ai_trace"),+ ],+ dateRange=AssistantDateRange(date_from="2025-01-08"),+ funnelsFilter=AssistantFunnelsFilter(funnelVizType=FunnelVizType.TRENDS),+ )+ # now is midday on the 10th, so the 10th's bucket is still collecting.+ self.assertEqual(+ FunnelResultsFormatter(query, results, self.team, datetime(2025, 1, 10, 12, 0, 0, tzinfo=UTC)).format(),+ "Date|$pageview (custom) -> $ai_trace conversion|$pageview (custom) -> $ai_trace drop-off\n"+ "2025-01-08|10%|90%\n2025-01-09|15.5%|84.5%\n2025-01-10 (partial)|0%|100%\n\n"+ 'Note: rows marked "(partial)" cover an interval that is still in progress as of the query time, '+ "so their values are incomplete. Timezone: UTC.",+ )+def test_funnel_trends_with_breakdown(self):results = [{diff --git a/ee/hogai/context/insight/format/test/test_trends.py b/ee/hogai/context/insight/format/test/test_trends.pyindex 81f865e68d37..091e456f40d9 100644--- a/ee/hogai/context/insight/format/test/test_trends.py+++ b/ee/hogai/context/insight/format/test/test_trends.py@@ -1,6 +1,8 @@+from datetime import UTC, datetime+from posthog.test.base import BaseTest-from posthog.schema import AssistantTrendsQuery, Compare+from posthog.schema import AssistantDateRange, AssistantTrendsQuery, Compare, IntervalTypefrom .. import TrendsResultsFormatter@@ -119,6 +121,73 @@ class TestTrendsResultsFormatter(BaseTest):series.pop("action")self.assertEqual(formatter._extract_series_label(series), "$pageview breakdown for the value `0`")+ 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+ # in the future — both must be flagged so daily automation doesn't treat them as complete.+ results = [+ {+ "data": [242, 46, 0],+ "days": ["2025-01-24", "2025-01-25", "2025-01-26"],+ "count": 288,+ "label": "$pageview",+ }+ ]+ self.assertEqual(+ TrendsResultsFormatter(+ AssistantTrendsQuery(series=[]),+ results,+ self.team,+ datetime(2025, 1, 25, 12, 0, 0, tzinfo=UTC),+ ).format(),+ "Date|$pageview\n2025-01-24|242\n2025-01-25 (partial)|46\n2025-01-26 (partial)|0\n\n"+ 'Note: rows marked "(partial)" cover an interval that is still in progress as of the query time, '+ "so their values are incomplete. Timezone: UTC.",+ )++ def test_trends_does_not_mark_complete_buckets(self):+ # Every bucket ends before now, so nothing is partial and no note is appended.+ results = [+ {+ "data": [242, 46, 0],+ "days": ["2025-01-23", "2025-01-24", "2025-01-25"],+ "count": 288,+ "label": "$pageview",+ }+ ]+ self.assertEqual(+ TrendsResultsFormatter(+ AssistantTrendsQuery(+ series=[], dateRange=AssistantDateRange(date_from="2025-01-23", date_to="2025-01-25")+ ),+ results,+ self.team,+ datetime(2025, 2, 1, 12, 0, 0, tzinfo=UTC),+ ).format(),+ "Date|$pageview\n2025-01-23|242\n2025-01-24|46\n2025-01-25|0",+ )++ def test_trends_marks_partial_hourly_bucket(self):+ # Hourly granularity: only the in-progress hour (and later) is partial.+ results = [+ {+ "data": [5, 9, 0],+ "days": ["2025-01-25 10:00:00", "2025-01-25 11:00:00", "2025-01-25 12:00:00"],+ "count": 14,+ "label": "$pageview",+ }+ ]+ self.assertEqual(+ TrendsResultsFormatter(+ AssistantTrendsQuery(series=[], interval=IntervalType.HOUR),+ results,+ self.team,+ datetime(2025, 1, 25, 12, 30, 0, tzinfo=UTC),+ ).format(),+ "Date|$pageview\n2025-01-25 10:00|5\n2025-01-25 11:00|9\n2025-01-25 12:00 (partial)|0\n\n"+ 'Note: rows marked "(partial)" cover an interval that is still in progress as of the query time, '+ "so their values are incomplete. Timezone: UTC.",+ )+def test_trends_aggregated_value(self):results = [{diff --git a/ee/hogai/context/insight/format/trends.py b/ee/hogai/context/insight/format/trends.pyindex 0a7bb7337317..a852ab773b1c 100644--- a/ee/hogai/context/insight/format/trends.py+++ b/ee/hogai/context/insight/format/trends.py@@ -1,10 +1,20 @@-from typing import Any+from datetime import UTC, datetime+from typing import Any, Optional-from posthog.schema import AssistantTrendsQuery, Compare, TrendsQuery+from posthog.schema import AssistantTrendsQuery, Compare, DateRange, TrendsQueryfrom posthog.hogql_queries.insights.utils.breakdowns import humanize_breakdown_label+from posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.models import Team-from .utils import format_matrix, format_number, strip_datetime_seconds+from .utils import (+ PARTIAL_BUCKET_MARKER,+ format_matrix,+ format_number,+ partial_bucket_flags,+ partial_bucket_note,+ strip_datetime_seconds,+)class TrendsResultsFormatter:@@ -23,9 +33,13 @@ class TrendsResultsFormatter:self,query: AssistantTrendsQuery | TrendsQuery,results: list[dict[str, Any]],+ team: Optional[Team] = None,+ utc_now_datetime: Optional[datetime] = None,):self._query = queryself._results = results+ self._team = team+ self._utc_now_datetime = utc_now_datetime or datetime.now(UTC)def format(self) -> str:results = self._results@@ -79,6 +93,8 @@ class TrendsResultsFormatter:result = results[0]dates = result["days"]+ partial = self._partial_bucket_flags(dates)+series_labels = []for series in results:label = self._extract_series_label(series)@@ -92,12 +108,31 @@ class TrendsResultsFormatter:# Build data rowsfor i, date in enumerate(dates):- row = [strip_datetime_seconds(date)]+ date_cell = strip_datetime_seconds(date)+ if partial and partial[0][i]:+ date_cell += PARTIAL_BUCKET_MARKER+ row = [date_cell]for series in results:row.append(format_number(series["data"][i]))matrix.append(row)- return format_matrix(matrix)+ formatted = format_matrix(matrix)+ if partial and any(partial[0]):+ formatted = f"{formatted}\n\n{partial_bucket_note(partial[1])}"+ return formatted++ def _partial_bucket_flags(self, dates: list[str]) -> Optional[tuple[list[bool], str]]:+ """Flag buckets still collecting data, plus the project timezone name.++ Returns None when the team (hence project timezone) isn't available, so callers+ render results exactly as before rather than guessing at completeness."""+ if self._team is None:+ return None+ date_range = DateRange.model_validate(self._query.dateRange.model_dump()) if self._query.dateRange else None+ query_date_range = QueryDateRange(date_range, self._team, self._query.interval, self._utc_now_datetime)+ now_local = query_date_range.now_with_timezone.replace(tzinfo=None)+ current_interval_start = query_date_range.align_with_interval(now_local)+ return partial_bucket_flags(dates, current_interval_start), self._team.timezonedef _extract_series_label(self, series: dict[str, Any]) -> str:action = series.get("action")diff --git a/ee/hogai/context/insight/format/utils.py b/ee/hogai/context/insight/format/utils.pyindex ddf6b85439c5..5b533ba3418d 100644--- a/ee/hogai/context/insight/format/utils.py+++ b/ee/hogai/context/insight/format/utils.py@@ -101,3 +101,45 @@ def format_date(date: datetime.date) -> str:def strip_datetime_seconds(date: str) -> str:return datetime.datetime.fromisoformat(date).strftime("%Y-%m-%d %H:%M" if ":" in date else "%Y-%m-%d")+++# Appended to a bucket's date cell when that bucket is still collecting data.+PARTIAL_BUCKET_MARKER = " (partial)"+++def parse_bucket_datetime(day: str) -> Optional[datetime.datetime]:+ """Parse a trends/funnel bucket label into a naive datetime (project-local).++ Bucket labels are `%Y-%m-%d` or `%Y-%m-%d %H:%M:%S` strings emitted in the project+ timezone. Returns None if the label can't be parsed, so callers fall back to not+ flagging the bucket rather than crashing on an unexpected format."""+ for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):+ try:+ return datetime.datetime.strptime(day, fmt)+ except ValueError:+ continue+ try:+ return datetime.datetime.fromisoformat(day).replace(tzinfo=None)+ except ValueError:+ return None+++def partial_bucket_flags(days: list[str], current_interval_start: datetime.datetime) -> list[bool]:+ """Flag each bucket that falls in the current (still-collecting) interval or later.++ `current_interval_start` is the start of the interval containing "now", in project-local+ naive time. A bucket at or after it hasn't finished accruing data yet, so its value is+ partial — this is what makes daily/hourly automation over trends results unsafe when the+ last row is silently incomplete or labeled in the future."""+ flags: list[bool] = []+ for day in days:+ bucket_start = parse_bucket_datetime(day)+ flags.append(bucket_start is not None and bucket_start >= current_interval_start)+ return flags+++def partial_bucket_note(timezone: str) -> str:+ return (+ f'Note: rows marked "{PARTIAL_BUCKET_MARKER.strip()}" cover an interval that is still in progress '+ f"as of the query time, so their values are incomplete. Timezone: {timezone}."+ )diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.pyindex 6650f76d3563..ec92b2aad0dd 100644--- a/ee/hogai/context/insight/query_executor.py+++ b/ee/hogai/context/insight/query_executor.py@@ -509,7 +509,9 @@ class AssistantQueryExecutor:result = BoxPlotResultsFormatter(get_boxplot_results(response)).format()else:formatter_name = "TrendsResultsFormatter"- result = TrendsResultsFormatter(query, response["results"]).format()+ result = TrendsResultsFormatter(+ query, response["results"], self._team, self._utc_now_datetime+ ).format()elif isinstance(query, AssistantFunnelsQuery | FunnelsQuery):formatter_name = "FunnelResultsFormatter"formatter = FunnelResultsFormatter(query, response["results"], self._team, self._utc_now_datetime)