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): exclude leading partial bucket with incomplete periods toggle (#81504)

Sam Penningtoncd02d9dadd06
diff --git a/frontend/src/lib/components/DateFilter/DateFilterExclusionsControl.tsx b/frontend/src/lib/components/DateFilter/DateFilterExclusionsControl.tsx
index f7707bf6d49b..e686c30a3769 100644
--- a/frontend/src/lib/components/DateFilter/DateFilterExclusionsControl.tsx
+++ b/frontend/src/lib/components/DateFilter/DateFilterExclusionsControl.tsx
@@ -80,7 +80,7 @@ export function DateFilterExclusionsControl({
<PopoverContent side="right" align="end" {...panelProps} className="w-64 gap-0 p-0">
{showIncomplete && (
<div className="flex items-center justify-between gap-2 px-3 py-2.5">
- <Label htmlFor="date-filter-exclude-incomplete">Incomplete period</Label>
+ <Label htmlFor="date-filter-exclude-incomplete">Incomplete periods</Label>
<Switch
id="date-filter-exclude-incomplete"
size="sm"
diff --git a/frontend/src/lib/components/DateFilter/LemonDateFilterExclusions.tsx b/frontend/src/lib/components/DateFilter/LemonDateFilterExclusions.tsx
index 026749c19b75..eba5d63a5c15 100644
--- a/frontend/src/lib/components/DateFilter/LemonDateFilterExclusions.tsx
+++ b/frontend/src/lib/components/DateFilter/LemonDateFilterExclusions.tsx
@@ -48,7 +48,7 @@ export function LemonDateFilterExclusions({
<div className="px-3 py-2.5">
<LemonSwitch
fullWidth
- label="Incomplete period"
+ label="Incomplete periods"
checked={exclusions.incomplete}
onChange={(incomplete) => onChange({ ...exclusions, incomplete })}
data-attr="date-filter-exclude-incomplete-periods"
diff --git a/frontend/src/queries/nodes/InsightViz/InsightResultMetadata.tsx b/frontend/src/queries/nodes/InsightViz/InsightResultMetadata.tsx
index bd0b24be31d0..d52c41cb26d1 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightResultMetadata.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightResultMetadata.tsx
@@ -45,7 +45,7 @@ export const InsightResultMetadata = ({
{dateRange?.excludeIncompletePeriods ? (
<span className="text-secondary">
<span className="mx-1">•</span>
- Incomplete period excluded
+ Incomplete periods excluded
</span>
) : null}
</>
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.py
index fe80b936c46b..2bc29a2e6172 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
@@ -783,6 +783,21 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual("2020-01-14", response.results[0]["days"][-1])
+ def test_exclude_incomplete_periods_drops_leading_partial_bucket(self):
+ self._create_test_events()
+
+ # 2020-01-19 is a Sunday (default week start), so -13d starts mid-week on Jan 6: the
+ # partial Jan 6-11 bucket is dropped alongside the current week, leaving Jan 12-18 only
+ with freeze_time("2020-01-19T12:00:00Z"):
+ query = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ dateRange=DateRange(date_from="-13d", excludeIncompletePeriods=True),
+ interval=IntervalType.WEEK,
+ )
+ response = TrendsQueryRunner(team=self.team, query=query).calculate()
+
+ self.assertEqual(["2020-01-12"], response.results[0]["days"])
+
def test_trends_days(self):
self._create_test_events()
diff --git a/posthog/hogql_queries/utils/query_date_range.py b/posthog/hogql_queries/utils/query_date_range.py
index bda6b7c29e21..274e7178e79d 100644
--- a/posthog/hogql_queries/utils/query_date_range.py
+++ b/posthog/hogql_queries/utils/query_date_range.py
@@ -131,13 +131,35 @@ class QueryDateRange:
clipped = current_interval_start - timedelta(microseconds=1)
# The base implementation is called explicitly: subclasses redefine date_from() in terms of
# date_to() (e.g. the previous-period range), which would recurse, and the clip must be
- # evaluated against the current range's own start regardless.
- if clipped < QueryDateRange.date_from(self):
+ # evaluated against the current range's own start regardless. The unclipped start is used
+ # because the start clip is itself defined in terms of date_to().
+ if clipped < QueryDateRange._date_from_unclipped(self):
# No complete interval in range: keep the partial current one rather than inverting the
# range (mirrors alerts never dropping the only data point).
return date_to
return clipped
+ def _clip_incomplete_period_start(self, date_from: datetime) -> datetime:
+ """Advance date_from to the next interval boundary when the range starts mid-interval, so
+ the leading partial bucket is excluded too (DateRange.excludeIncompletePeriods) — e.g.
+ "Last 180 days" by week starts mid-week and would otherwise chart a few-day first bucket."""
+ if not (self._date_range and self._date_range.excludeIncompletePeriods):
+ return date_from
+ if self._interval_count != 1:
+ # Multi-unit buckets don't sit on single-interval boundaries, so a clip here would
+ # truncate the leading bucket mid-bucket instead of excluding it.
+ return date_from
+ aligned = self.align_with_interval(date_from)
+ if aligned >= date_from:
+ return date_from
+ advanced = aligned + self.interval_relativedelta()
+ # Explicit base call for the same recursion reasons as in _clip_incomplete_period.
+ if advanced > QueryDateRange.date_to(self):
+ # No complete interval in range: keep the partial leading one rather than inverting the
+ # range (mirrors alerts never dropping the only data point).
+ return date_from
+ return advanced
+
def get_earliest_timestamp(self) -> datetime:
if self._earliest_timestamp_fallback:
return self._earliest_timestamp_fallback
@@ -148,6 +170,9 @@ class QueryDateRange:
return get_earliest_timestamp_unfiltered(self._team)
def date_from(self) -> datetime:
+ return self._clip_incomplete_period_start(self._date_from_unclipped())
+
+ def _date_from_unclipped(self) -> datetime:
date_from: datetime
if self._date_range and self._date_range.date_from == "all":
date_from = self.get_earliest_timestamp()
diff --git a/posthog/hogql_queries/utils/test/test_query_date_range.py b/posthog/hogql_queries/utils/test/test_query_date_range.py
index 604045d3c9a2..47541a816628 100644
--- a/posthog/hogql_queries/utils/test/test_query_date_range.py
+++ b/posthog/hogql_queries/utils/test/test_query_date_range.py
@@ -162,6 +162,64 @@ class TestQueryDateRange(APIBaseTest):
)
self.assertEqual(query_date_range.date_to(), parser.isoparse(expected_date_to))
+ @parameterized.expand(
+ [
+ # now is 2021-08-25T10:00Z (a Wednesday): a relative date_from landing mid-interval is
+ # advanced to the next boundary, so the leading bucket is a complete one
+ ("day_already_aligned", IntervalType.DAY, "-7d", "2021-08-18T00:00:00Z", WeekStartDay.SUNDAY),
+ ("week_sunday_start", IntervalType.WEEK, "-30d", "2021-08-01T00:00:00Z", WeekStartDay.SUNDAY),
+ ("week_monday_start", IntervalType.WEEK, "-33d", "2021-07-26T00:00:00Z", WeekStartDay.MONDAY),
+ ("month", IntervalType.MONTH, "-3m", "2021-06-01T00:00:00Z", WeekStartDay.SUNDAY),
+ ("quarter", IntervalType.QUARTER, "-2y", "2019-10-01T00:00:00Z", WeekStartDay.SUNDAY),
+ ("year", IntervalType.YEAR, "-3y", "2019-01-01T00:00:00Z", WeekStartDay.SUNDAY),
+ ]
+ )
+ def test_exclude_incomplete_periods_clips_date_from(
+ self, _name, interval, date_from, expected_date_from, week_start_day
+ ):
+ now = parser.isoparse("2021-08-25T10:00:00.000Z")
+ self.team.week_start_day = week_start_day
+ query_date_range = QueryDateRange(
+ team=self.team,
+ date_range=DateRange(date_from=date_from, excludeIncompletePeriods=True),
+ interval=interval,
+ now=now,
+ )
+ self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_date_from))
+
+ def test_exclude_incomplete_periods_clips_explicit_historical_date_from(self):
+ # A fixed historical range starting mid-week still gets its leading partial bucket dropped.
+ now = parser.isoparse("2021-08-25T10:00:00.000Z")
+ query_date_range = QueryDateRange(
+ team=self.team,
+ date_range=DateRange(date_from="2021-06-15", date_to="2021-08-01", excludeIncompletePeriods=True),
+ interval=IntervalType.WEEK,
+ now=now,
+ )
+ self.assertEqual(query_date_range.date_from(), parser.isoparse("2021-06-20T00:00:00Z"))
+
+ @parameterized.expand(
+ [
+ # A range without a single complete interval must keep the partial leading bucket
+ # rather than being clipped into an empty or inverted range.
+ ("range_within_current_month", "-3d", IntervalType.MONTH, None, "2021-08-22T00:00:00Z"),
+ # Multi-unit buckets don't sit on single-interval boundaries: the flag is a no-op there.
+ ("multi_unit_interval", "-1d", IntervalType.HOUR, 2, "2021-08-24T10:00:00Z"),
+ ]
+ )
+ def test_exclude_incomplete_periods_date_from_no_op_edge_cases(
+ self, _name, date_from, interval, interval_count, expected_date_from
+ ):
+ now = parser.isoparse("2021-08-25T10:00:00.000Z")
+ query_date_range = QueryDateRange(
+ team=self.team,
+ date_range=DateRange(date_from=date_from, excludeIncompletePeriods=True),
+ interval=interval,
+ interval_count=interval_count,
+ now=now,
+ )
+ self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_date_from))
+
def test_exclude_incomplete_periods_clips_explicit_date_to_in_current_period(self):
# explicitDate=True skips date_to padding, but excludeIncompletePeriods still clips
# when the explicit date_to falls inside the incomplete current period.