: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(insights): stop month/quarter/year intervals including events before date_from (#71938)
Sam Penningtonaba1c21ef3b6
diff --git a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_boxplot_trends_query_runner.ambr b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_boxplot_trends_query_runner.ambrindex fabdecebb6e4..95dab6eb5ffe 100644--- a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_boxplot_trends_query_runner.ambr+++ b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_boxplot_trends_query_runner.ambr@@ -279,7 +279,7 @@max(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'revenue'), ''), 'null'), '^"|"$', ''), 'Float64')) AS max_val,avg(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'revenue'), ''), 'null'), '^"|"$', ''), 'Float64')) AS mean_valFROM events AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2023-10-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2023-12-31 23:59:59', 'UTC'))))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2023-10-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2023-12-31 23:59:59', 'UTC'))))GROUP BY day_startORDER BY day_start ASCLIMIT 100 SETTINGS readonly=2,@@ -306,7 +306,7 @@max(accurateCastOrNull(if(notEquals(toJSONString(e.properties.^revenue), '{}'), toJSONString(e.properties.^revenue), if(isNull(e.properties.revenue), NULL, if(startsWith(dynamicType(e.properties.revenue), 'DateTime'), replaceOne(toString(e.properties.revenue), ' ', 'T'), if(or(startsWith(dynamicType(e.properties.revenue), 'Array'), startsWith(dynamicType(e.properties.revenue), 'Map'), startsWith(dynamicType(e.properties.revenue), 'Tuple')), toJSONString(e.properties.revenue), toString(e.properties.revenue))))), 'Float64')) AS max_val,avg(accurateCastOrNull(if(notEquals(toJSONString(e.properties.^revenue), '{}'), toJSONString(e.properties.^revenue), if(isNull(e.properties.revenue), NULL, if(startsWith(dynamicType(e.properties.revenue), 'DateTime'), replaceOne(toString(e.properties.revenue), ' ', 'T'), if(or(startsWith(dynamicType(e.properties.revenue), 'Array'), startsWith(dynamicType(e.properties.revenue), 'Map'), startsWith(dynamicType(e.properties.revenue), 'Tuple')), toJSONString(e.properties.revenue), toString(e.properties.revenue))))), 'Float64')) AS mean_valFROM events_json AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2023-10-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2023-12-31 23:59:59', 'UTC'))))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2023-10-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2023-12-31 23:59:59', 'UTC'))))GROUP BY day_startORDER BY day_start ASCLIMIT 100 SETTINGS readonly=2,diff --git a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_slope_graph_trends_query_runner.ambr b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_slope_graph_trends_query_runner.ambrindex 35aefbeeda1f..dd95cac03c7e 100644--- a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_slope_graph_trends_query_runner.ambr+++ b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_slope_graph_trends_query_runner.ambr@@ -267,7 +267,7 @@(SELECT count() AS total,toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-03-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-01-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-02-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-31 23:59:59', 6, 'UTC')))))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-03-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-01-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-02-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-31 23:59:59', 6, 'UTC')))))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -298,7 +298,7 @@(SELECT count() AS total,toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events_json AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-03-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-01-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-02-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-31 23:59:59', 6, 'UTC')))))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-03-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-01-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-02-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-31 23:59:59', 6, 'UTC')))))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -453,7 +453,7 @@(SELECT count() AS total,toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-06-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-04-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-15 23:59:59', 6, 'UTC')))))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-06-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-04-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-15 23:59:59', 6, 'UTC')))))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -484,7 +484,7 @@(SELECT count() AS total,toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events_json AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-06-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-04-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-15 23:59:59', 6, 'UTC')))))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-06-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-04-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-15 23:59:59', 6, 'UTC')))))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -927,7 +927,7 @@(SELECT count() AS total,toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-31 23:59:59', 6, 'UTC')))))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-31 23:59:59', 6, 'UTC')))))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -958,7 +958,7 @@(SELECT count() AS total,toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events_json AS e- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-31 23:59:59', 6, 'UTC')))))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-31 23:59:59', 6, 'UTC')))))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)diff --git a/posthog/hogql_queries/insights/trends/test/test_trends.py b/posthog/hogql_queries/insights/trends/test/test_trends.pyindex 8daaab79f672..a1918c369812 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends.py@@ -2404,7 +2404,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):self._test_events_with_dates(dates=["2020-06-2", "2020-07-30"],interval="month",- date_from="2020-6-7", # should round down to 6-1+ date_from="2020-6-7", # rounds labels down to 6-1 but only includes events on or after date_fromdate_to="2020-7-30",result=[{@@ -2421,8 +2421,8 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):"properties": [],},"label": "event_name",- "count": 2.0,- "data": [1.0, 1.0],+ "count": 1.0,+ "data": [0.0, 1.0],"labels": ["Jun 2020", "Jul 2020"],"days": ["2020-06-01", "2020-07-01"],}diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.pyindex 6f9551cee01f..f2d3e356bea2 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py@@ -7072,7 +7072,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):)flush_persons_and_events()- # Test 1: Without explicitDate, filtering last 7 days with monthly interval includes entire month+ # Test 1: Without explicitDate, filtering last 7 days with monthly interval only includes events in rangewith freeze_time("2020-01-31 23:59:59"):response_default = TrendsQueryRunner(query=TrendsQuery(@@ -7085,9 +7085,9 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(1, len(response_default.results))self.assertEqual(- 31,+ 8,response_default.results[0]["count"],- "Without explicitDate, includes entire month due to interval boundary adjustment",+ "Without explicitDate, only includes events within the date range, not the entire month",)# Test 2: With explicitDate=True and explicit dates, STILL has issues (gets 6 instead of 7)diff --git a/posthog/hogql_queries/utils/query_date_range.py b/posthog/hogql_queries/utils/query_date_range.pyindex 0b3b0c73d145..0a628f6ffa2d 100644--- a/posthog/hogql_queries/utils/query_date_range.py+++ b/posthog/hogql_queries/utils/query_date_range.py@@ -365,15 +365,17 @@ class QueryDateRange:return self.date_to_start_of_interval_hogql(self.date_from_as_hogql())def date_from_with_adjusted_start_of_interval_hogql(self) -> ast.Call:- if self.interval_name == "week":- # in `where` queries with week intervals, we need to return the date_from instead of the start of the week- # this ensures that we only fetch records after the date_from+ if self.interval_name in ("week", "month", "quarter", "year"):+ # in `where` queries with intervals coarser than a day, filter from the start of `date_from`'s day+ # rather than the start of the interval bucket. This ensures we only fetch records at or after+ # date_from, matching how the day interval already behaves and keeping grouped totals consistent+ # with the selected date range.return ast.Call(name="toStartOfInterval",args=[self.date_from_as_hogql(),ast.Call(- name=f"toIntervalDay",+ name="toIntervalDay",args=[ast.Constant(value=1)],),],diff --git a/posthog/hogql_queries/utils/test/test_query_date_range.py b/posthog/hogql_queries/utils/test/test_query_date_range.pyindex 59e70582b8bf..604045d3c9a2 100644--- a/posthog/hogql_queries/utils/test/test_query_date_range.py+++ b/posthog/hogql_queries/utils/test/test_query_date_range.py@@ -116,6 +116,29 @@ class TestQueryDateRange(APIBaseTest):[parser.isoparse(f"{start}T00:00:00Z") for start in expected_starts],)+ @parameterized.expand(+ [+ ("week", IntervalType.WEEK),+ ("month", IntervalType.MONTH),+ ("quarter", IntervalType.QUARTER),+ ("year", IntervalType.YEAR),+ ]+ )+ def test_adjusted_start_of_interval_filters_from_start_of_day(self, _name, interval):+ # For intervals coarser than a day, the WHERE lower bound must round `date_from` down to the start of+ # its day, not the start of the interval bucket — otherwise a relative range shorter than the bucket+ # (e.g. "last 7 days" grouped by month) pulls in events from before date_from. Guards against the guard+ # being narrowed to only some of these intervals again.+ now = parser.isoparse("2021-08-25T00:00:00.000Z")+ adjusted = QueryDateRange(+ team=self.team, date_range=DateRange(date_from="-3d"), interval=interval, now=now+ ).date_from_with_adjusted_start_of_interval_hogql()++ self.assertEqual(adjusted.name, "toStartOfInterval")+ interval_period = adjusted.args[1]+ assert isinstance(interval_period, ast.Call)+ self.assertEqual(interval_period.name, "toIntervalDay")+@parameterized.expand([# now is 2021-08-25T10:00Z (a Wednesday): clip to the end of the last complete interval