: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
feat(insights): excludeIncompletePeriods option on DateRange (#68303)
Sam Pennington95bd80aa3765
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex cd4eb7535def..5a6574e79dce 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -17684,6 +17684,11 @@],"description": "Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries."},+ "excludeIncompletePeriods": {+ "default": false,+ "description": "Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries.",+ "type": ["boolean", "null"]+ },"explicitDate": {"default": false,"description": "Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period.",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 5528a748892c..0b1654eb9bfa 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5110,6 +5110,14 @@ export interface DateRange {* Omit or empty for all days. Only applied by insight queries.*/daysOfWeek?: (1 | 2 | 3 | 4 | 5 | 6 | 7)[] | null+ /**+ * Exclude the current, still-collecting period by clipping date_to to the+ * end of the last complete interval (evaluated in the project timezone).+ * No-op when the range contains no complete interval. Only applied by+ * insight queries.+ * @default false+ */+ excludeIncompletePeriods?: boolean | null}export interface ResolvedDateRangeResponse {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 c00dfe8cc418..41f029f4f583 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@@ -658,6 +658,19 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):with self.assertRaises(DRFValidationError):TrendsQueryRunner(team=self.team, query=query).calculate()+ def test_exclude_incomplete_periods_drops_current_bucket(self):+ self._create_test_events()++ with freeze_time("2020-01-15T12:00:00Z"):+ query = TrendsQuery(+ series=[EventsNode(event="$pageview")],+ dateRange=DateRange(date_from="-7d", excludeIncompletePeriods=True),+ interval=IntervalType.DAY,+ )+ response = TrendsQueryRunner(team=self.team, query=query).calculate()++ self.assertEqual("2020-01-14", response.results[0]["days"][-1])+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.pyindex ed934f5366d8..0b3b0c73d145 100644--- a/posthog/hogql_queries/utils/query_date_range.py+++ b/posthog/hogql_queries/utils/query_date_range.py@@ -100,7 +100,7 @@ class QueryDateRange:team_week_start_day=self._team.week_start_day,)elif self._exact_timerange:- return date_to+ return self._clip_incomplete_period(date_to)if not self._date_range or not self._date_range.explicitDate:is_relative = not self._date_range or not self._date_range.date_to or delta_mapping is not None@@ -113,7 +113,30 @@ class QueryDateRange:date_to = date_to.replace(second=59, microsecond=999999)elif self.interval_type == IntervalType.SECOND:date_to = (date_to - timedelta(seconds=1)).replace(microsecond=999999)- return date_to++ return self._clip_incomplete_period(date_to)++ def _clip_incomplete_period(self, date_to: datetime) -> datetime:+ """Clip date_to to the end of the last complete interval when the range reaches into the+ current, still-collecting one (DateRange.excludeIncompletePeriods)."""+ if not (self._date_range and self._date_range.excludeIncompletePeriods):+ return date_to+ if self._interval_count != 1:+ # Multi-unit buckets don't sit on single-interval boundaries, so a clip here would+ # truncate the trailing bucket mid-bucket instead of excluding it.+ return date_to+ current_interval_start = self.align_with_interval(self.now_with_timezone)+ if date_to < current_interval_start:+ return date_to+ 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):+ # 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 clippeddef get_earliest_timestamp(self) -> datetime:if self._earliest_timestamp_fallback:diff --git a/posthog/hogql_queries/utils/query_previous_period_date_range.py b/posthog/hogql_queries/utils/query_previous_period_date_range.pyindex d4ec5a2f3018..9e0d9c43f7a1 100644--- a/posthog/hogql_queries/utils/query_previous_period_date_range.py+++ b/posthog/hogql_queries/utils/query_previous_period_date_range.py@@ -61,6 +61,7 @@ class QueryPreviousPeriodDateRange(QueryDateRange):self.date_from_delta_mappings(),self.date_to_delta_mappings(),self.interval_name,+ exclude_incomplete_periods=bool(self._date_range and self._date_range.excludeIncompletePeriods),)return previous_period_date_from, previous_period_date_todiff --git a/posthog/hogql_queries/utils/test/test_query_date_range.py b/posthog/hogql_queries/utils/test/test_query_date_range.pyindex e3ebe4700ba4..59e70582b8bf 100644--- a/posthog/hogql_queries/utils/test/test_query_date_range.py+++ b/posthog/hogql_queries/utils/test/test_query_date_range.py@@ -1,4 +1,4 @@-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import Optionalfrom zoneinfo import ZoneInfo@@ -116,6 +116,104 @@ class TestQueryDateRange(APIBaseTest):[parser.isoparse(f"{start}T00:00:00Z") for start in expected_starts],)+ @parameterized.expand(+ [+ # now is 2021-08-25T10:00Z (a Wednesday): clip to the end of the last complete interval+ ("day", IntervalType.DAY, "-7d", "2021-08-24T23:59:59.999999Z"),+ ("week_sunday_start", IntervalType.WEEK, "-30d", "2021-08-21T23:59:59.999999Z"),+ ("week_monday_start", IntervalType.WEEK, "-30d", "2021-08-22T23:59:59.999999Z"),+ ("month", IntervalType.MONTH, "-3m", "2021-07-31T23:59:59.999999Z"),+ ("quarter", IntervalType.QUARTER, "-2y", "2021-06-30T23:59:59.999999Z"),+ ("year", IntervalType.YEAR, "-3y", "2020-12-31T23:59:59.999999Z"),+ ]+ )+ def test_exclude_incomplete_periods_clips_date_to(self, _name, interval, date_from, expected_date_to):+ now = parser.isoparse("2021-08-25T10:00:00.000Z")+ if interval == IntervalType.WEEK and "monday" in _name:+ self.team.week_start_day = WeekStartDay.MONDAY+ 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_to(), parser.isoparse(expected_date_to))++ 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.+ now = parser.isoparse("2021-08-25T10:00:00.000Z")+ query_date_range = QueryDateRange(+ team=self.team,+ date_range=DateRange(+ date_from="-3m", date_to="2021-08-26", explicitDate=True, excludeIncompletePeriods=True+ ),+ interval=IntervalType.MONTH,+ now=now,+ )+ self.assertEqual(query_date_range.date_to(), parser.isoparse("2021-07-31T23:59:59.999999Z"))++ def test_exclude_incomplete_periods_no_op_for_complete_range(self):+ now = parser.isoparse("2021-08-25T10:00:00.000Z")+ query_date_range = QueryDateRange(+ team=self.team,+ date_range=DateRange(date_from="-3m", date_to="2021-06-15", excludeIncompletePeriods=True),+ interval=IntervalType.MONTH,+ now=now,+ )+ self.assertEqual(query_date_range.date_to(), parser.isoparse("2021-06-15T23:59:59.999999Z"))++ @parameterized.expand(+ [+ # A range entirely inside the current period must not be clipped into an inverted+ # (date_to < date_from) range: the partial current period is kept instead.+ ("range_within_current_day", "dStart", IntervalType.DAY, None, "2021-08-25T23:59:59.999999Z"),+ ("range_within_current_month", "mStart", IntervalType.MONTH, None, "2021-08-25T23:59:59.999999Z"),+ # Multi-unit buckets don't sit on single-interval boundaries: clipping would truncate+ # the trailing bucket mid-bucket, so the flag is a no-op there.+ ("multi_unit_interval", "-1d", IntervalType.HOUR, 2, "2021-08-25T10:00:59.999999Z"),+ ]+ )+ def test_exclude_incomplete_periods_no_op_edge_cases(+ self, _name, date_from, interval, interval_count, expected_date_to+ ):+ 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_to(), parser.isoparse(expected_date_to))++ def test_exclude_incomplete_periods_clips_exact_timerange(self):+ # exact_timerange returns early (no end-of-period padding), but the clip must still apply.+ now = parser.isoparse("2021-08-25T10:00:00.000Z")+ query_date_range = QueryDateRange(+ team=self.team,+ date_range=DateRange(date_from="-7d", excludeIncompletePeriods=True),+ interval=IntervalType.DAY,+ now=now,+ exact_timerange=True,+ )+ self.assertEqual(query_date_range.date_to(), parser.isoparse("2021-08-24T23:59:59.999999Z"))++ def test_exclude_incomplete_periods_clips_in_project_timezone(self):+ # now=2021-08-25T02:00Z is still Aug 24 19:00 in US/Pacific (PDT, UTC-7),+ # so the clip must land at the end of Aug 23 Pacific, not Aug 24.+ self.team.timezone = "US/Pacific"+ self.team.save()+ now = parser.isoparse("2021-08-25T02:00:00.000Z")+ query_date_range = QueryDateRange(+ team=self.team,+ date_range=DateRange(date_from="-7d", excludeIncompletePeriods=True),+ interval=IntervalType.DAY,+ now=now,+ )+ expected = datetime(2021, 8, 23, 23, 59, 59, 999999, tzinfo=ZoneInfo("US/Pacific"))+ self.assertEqual(query_date_range.date_to().isoformat(), expected.isoformat())+def test_date_to_explicit(self):now = parser.isoparse("2021-08-25T00:00:00.000Z")date_range = DateRange(@@ -466,10 +564,20 @@ class TestPreviousPeriodDateFrom(APIBaseTest):# previous = 2021-08-10 - 10 days = 2021-07-31"2021-07-31T00:00:00Z",),+ (+ "7d_with_exclude_incomplete",+ DateRange(date_from="-7d", excludeIncompletePeriods=True),+ IntervalType.DAY,+ # now=2021-08-25T10:00Z → date_to clipped to 2021-08-24T23:59:59.999999Z+ # date_from = 2021-08-18T00:00:00Z+ # delta = 2021-08-24T23:59:59.999999Z - 2021-08-18T00:00:00Z ≈ 6d23h59m59.999999s+ # previous = 2021-08-18 - delta = 2021-08-11T00:00:00.000001Z+ "2021-08-11T00:00:00.000001Z",+ ),])def test_previous_period_date_from(self, _name, date_range, interval, expected_str):- now = parser.isoparse("2021-08-25T00:00:00.000Z")+ now = parser.isoparse("2021-08-25T10:00:00.000Z")qdr = QueryDateRange(team=self.team, date_range=date_range, interval=interval, now=now)self.assertEqual(qdr.previous_period_date_from, parser.isoparse(expected_str))diff --git a/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py b/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.pyindex eac0d1425269..1d5206306ae0 100644--- a/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py+++ b/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py@@ -21,6 +21,19 @@ class TestQueryPreviousPeriodDateRange(APIBaseTest):self.assertEqual(query_date_range.date_from(), parser.isoparse("2021-08-20T00:00:00Z"))self.assertEqual(query_date_range.date_to(), parser.isoparse("2021-08-22T23:59:59.999999Z"))+ def test_previous_period_with_exclude_incomplete_periods_stays_aligned(self):+ # The "-7d is really 8 days" kludge in get_compare_period_dates adds a day to counteract+ # the ongoing day, but a clipped range no longer includes it: current period is exactly+ # Wed Aug 18 - Tue Aug 24, so the previous period must be Wed Aug 11 - Tue Aug 17+ # (weekday-aligned, non-overlapping), not Aug 12 - Aug 18.+ now = parser.isoparse("2021-08-25T10:00:00.000Z")+ date_range = DateRange(date_from="-7d", excludeIncompletePeriods=True)+ query_date_range = QueryPreviousPeriodDateRange(+ team=self.team, date_range=date_range, interval=IntervalType.DAY, now=now+ )+ self.assertEqual(query_date_range.date_from(), parser.isoparse("2021-08-11T00:00:00Z"))+ self.assertEqual(query_date_range.date_to(), parser.isoparse("2021-08-17T23:59:59.999999Z"))+def test_explicit_timezone_info_overrides_team_timezone(self):# The previous-period delta parsing used to read directly from# `self._team.timezone_info`, so a `timezone_info=UTC` override on the constructordiff --git a/posthog/schema.py b/posthog/schema.pyindex d3e8289f512f..1e46647a1677 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -1010,6 +1010,15 @@ class DateRange(BaseModel):" days. Only applied by insight queries."),)+ excludeIncompletePeriods: bool | None = Field(+ default=False,+ description=(+ "Exclude the current, still-collecting period by clipping date_to to the"+ " end of the last complete interval (evaluated in the project timezone)."+ " No-op when the range contains no complete interval. Only applied by"+ " insight queries."+ ),+ )explicitDate: bool | None = Field(default=False,description=(diff --git a/posthog/tasks/alerts/detector.py b/posthog/tasks/alerts/detector.pyindex 8c8b8d3899f1..ab2cf2ae7f14 100644--- a/posthog/tasks/alerts/detector.py+++ b/posthog/tasks/alerts/detector.py@@ -42,7 +42,7 @@ class PreparedSeries:label: str-def _prepare_series(series: TrendResult, is_non_time_series: bool) -> PreparedSeries | None:+def _prepare_series(series: TrendResult, is_non_time_series: bool, *, drop_current: bool) -> PreparedSeries | None:"""Extract data + dates from a TrendResult and drop the incomplete interval.Returns None if the series has too few points for detection.@@ -56,7 +56,7 @@ def _prepare_series(series: TrendResult, is_non_time_series: bool) -> PreparedSereturn Nonedates: list[str] = series.get("days") or series.get("labels") or []- data, dates = _drop_incomplete_current_interval(data, dates, is_non_time_series)+ data, dates = _drop_incomplete_current_interval(data, dates, is_non_time_series, drop_current=drop_current)return PreparedSeries(data=data, dates=dates, label=series.get("label", "Series"))diff --git a/posthog/tasks/alerts/trends.py b/posthog/tasks/alerts/trends.pyindex 8622dba62107..c2c78e0c6613 100644--- a/posthog/tasks/alerts/trends.py+++ b/posthog/tasks/alerts/trends.py@@ -2,7 +2,7 @@ from typing import NotRequired, Optional, TypedDict, castimport numpy as np-from posthog.schema import IntervalType, TrendsAlertConfig, TrendsQuery+from posthog.schema import FunnelsQuery, IntervalType, TrendsAlertConfig, TrendsQueryfrom posthog.caching.fetch_from_cache import InsightResultfrom posthog.hogql_queries.insights.utils.breakdowns import has_breakdown_filter@@ -33,17 +33,26 @@ def _is_non_time_series_trend(query: TrendsQuery) -> bool:return bool(query.trendsFilter and query.trendsFilter.display in NON_TIME_SERIES_DISPLAY_TYPES)+def query_excludes_incomplete_periods(query: TrendsQuery | FunnelsQuery) -> bool:+ """When the insight already clips the ongoing interval via+ DateRange.excludeIncompletePeriods, every returned point is complete and+ the alert machinery must not drop or skip the trailing one."""+ return bool(query.dateRange and query.dateRange.excludeIncompletePeriods)++def _drop_incomplete_current_interval(- data: np.ndarray, dates: list[str], is_non_time_series: bool+ data: np.ndarray, dates: list[str], is_non_time_series: bool, *, drop_current: bool) -> tuple[np.ndarray, list[str]]:"""Drop the current (incomplete) interval — always the last element.The query does not set date_to, so the result includes the ongoinginterval whose value is still accumulating. Comparing this partialvalue against complete historical intervals causes systematic false- positives.+ positives. Pass drop_current=False when the query already excludes+ incomplete periods, so a complete trailing interval isn't lost too;+ it has no default so callers can't silently drop a complete point."""- if not is_non_time_series and len(data) > 1:+ if drop_current and not is_non_time_series and len(data) > 1:data = data[:-1]dates = dates[:-1] if dates else datesreturn data, datesdiff --git a/posthog/utils.py b/posthog/utils.pyindex cbe2927a3ccf..1096a8e97748 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -1153,6 +1153,7 @@ def get_compare_period_dates(date_from_delta_mapping: Optional[dict[str, int]],date_to_delta_mapping: Optional[dict[str, int]],interval: str,+ exclude_incomplete_periods: bool = False,) -> tuple[datetime.datetime, datetime.datetime]:diff = date_to - date_fromnew_date_from = date_from - diff@@ -1178,6 +1179,9 @@ def get_compare_period_dates(and date_from_delta_mapping.get("days", None)and date_from_delta_mapping["days"] % 7 == 0and not date_to_delta_mapping+ # With excludeIncompletePeriods the ongoing day is clipped out of the range, so -7d+ # covers exactly 7 complete days and the extra day would misalign the previous period.+ and not exclude_incomplete_periods):# KLUDGE: Unfortunately common relative date ranges such as "Last 7 days" (-7d) or "Last 14 days" (-14d)# are wrong because they treat the current ongoing day as an _extra_ one. This means that those rangesdiff --git a/products/alerts/backend/evaluation/detector.py b/products/alerts/backend/evaluation/detector.pyindex 49021d9d91db..a3feb5a5e368 100644--- a/products/alerts/backend/evaluation/detector.py+++ b/products/alerts/backend/evaluation/detector.py@@ -21,7 +21,13 @@ from posthog.tasks.alerts.detector import (_prepare_series,)from posthog.tasks.alerts.detectors import get_detector-from posthog.tasks.alerts.trends import TrendResult, _has_breakdown, _is_non_time_series_trend, _pick_series_result+from posthog.tasks.alerts.trends import (+ TrendResult,+ _has_breakdown,+ _is_non_time_series_trend,+ _pick_series_result,+ query_excludes_incomplete_periods,+)from posthog.tasks.alerts.utils import WRAPPER_NODE_KINDS, AlertEvaluationResultfrom posthog.utils import get_from_dict_or_attr, relative_date_parse@@ -57,6 +63,7 @@ def extract_detector_series("""min_samples = _compute_min_samples_for_detector(detector_config) + 1is_non_time_series = _is_non_time_series_trend(query)+ already_complete = query_excludes_incomplete_periods(query)has_breakdown = _has_breakdown(query)if is_non_time_series:@@ -90,7 +97,7 @@ def extract_detector_series(series: list[ComparableSeries] = []for result in results:- prepared = _prepare_series(result, is_non_time_series)+ prepared = _prepare_series(result, is_non_time_series, drop_current=not already_complete)if prepared is None:continuepoints = [diff --git a/products/alerts/backend/evaluation/funnel_strategies.py b/products/alerts/backend/evaluation/funnel_strategies.pyindex ed4afcd87465..6fad2ff799ac 100644--- a/products/alerts/backend/evaluation/funnel_strategies.py+++ b/products/alerts/backend/evaluation/funnel_strategies.py@@ -29,8 +29,11 @@ class FunnelVizStrategy:Default: nothing to reject — only the steps funnel has a per-step config to range-check."""return None- def to_series(self, result: Any, config: FunnelsAlertConfig) -> list[ComparableSeries]:- """Normalize the funnel query result into one ``ComparableSeries`` per breakdown value."""+ def to_series(self, result: Any, config: FunnelsAlertConfig, *, already_complete: bool) -> list[ComparableSeries]:+ """Normalize the funnel query result into one ``ComparableSeries`` per breakdown value.++ ``already_complete`` is true when the query clips the ongoing interval+ (DateRange.excludeIncompletePeriods), so the trailing point is a complete period."""raise NotImplementedError@@ -54,9 +57,9 @@ class StepsFunnelStrategy(FunnelVizStrategy):"conversion_from_previous is undefined at the first step; use conversion_from_start instead")- def to_series(self, result: Any, config: FunnelsAlertConfig) -> list[ComparableSeries]:+ def to_series(self, result: Any, config: FunnelsAlertConfig, *, already_complete: bool) -> list[ComparableSeries]:# A steps funnel is a single snapshot: the condition is always absolute (enforced upstream) and- # check_ongoing_interval has no meaning (there are no periods), so neither is read here.+ # check_ongoing_interval/already_complete have no meaning (there are no periods).rows = _require_list(_current_period_only(result), "steps")if not rows:return _no_data_series()@@ -79,16 +82,25 @@ class HistoricalTrendsFunnelStrategy(FunnelVizStrategy):unit = _CONVERSION_RATE_UNITsupports_relative_conditions = True- def to_series(self, result: Any, config: FunnelsAlertConfig) -> list[ComparableSeries]:+ def to_series(self, result: Any, config: FunnelsAlertConfig, *, already_complete: bool) -> list[ComparableSeries]:+ # The clip removes the ongoing interval from the results, so an alert asking to check it can+ # never do what it says: reject the conflicting configuration instead of silently degrading.+ if config.check_ongoing_interval and already_complete:+ raise AlertExtractionError(+ "check_ongoing_interval is not supported when the insight excludes incomplete periods "+ "(DateRange.excludeIncompletePeriods): the ongoing interval is clipped from the query results."+ )series_dicts = _require_list(_current_period_only(result), "trends")# Empty = no one entered the funnel: benign, not a misconfig.if not series_dicts:return _no_data_series()# By default evaluate the last *complete* period — the latest one is still in progress, so# anchoring there would read a partial rate (and, for relative, diff a partial against a complete- # one). check_ongoing_interval opts into that in-progress period. The anchor is the same for- # absolute and relative conditions; relative then diffs it against the period before it.- anchor_current = bool(config.check_ongoing_interval)+ # one). check_ongoing_interval opts into that in-progress period; on a clipped query+ # (already_complete) the last period is complete, so it is the one to evaluate. The anchor is+ # the same for absolute and relative conditions; relative then diffs it against the period+ # before it.+ anchor_last = bool(config.check_ongoing_interval) or already_completeseries: list[ComparableSeries] = []for entry in series_dicts:if not isinstance(entry, dict):@@ -101,7 +113,7 @@ class HistoricalTrendsFunnelStrategy(FunnelVizStrategy):if not points:# No periods in range — represent as a single missing point so the comparator skips it.points = [SeriesPoint(date=None, value=None)]- current_index = max(len(points) - 1 if anchor_current else len(points) - 2, 0)+ current_index = max(len(points) - 1 if anchor_last else len(points) - 2, 0)label = _label_for_breakdown(entry.get("breakdown_value"))series.append(ComparableSeries(label=label, points=points, current_index=current_index))return seriesdiff --git a/products/alerts/backend/evaluation/funnels.py b/products/alerts/backend/evaluation/funnels.pyindex bcf3cfc65e3b..faf62958d2cc 100644--- a/products/alerts/backend/evaluation/funnels.py+++ b/products/alerts/backend/evaluation/funnels.py@@ -5,6 +5,7 @@ from posthog.schema import AlertCondition, AlertConditionType, FunnelsAlertConfifrom posthog.api.services.query import ExecutionModefrom posthog.caching.calculate_results import calculate_for_query_based_insightfrom posthog.event_usage import EventSource+from posthog.tasks.alerts.trends import query_excludes_incomplete_periodsfrom products.alerts.backend.evaluation.contract import AlertExtractionError, ExtractionResult, lookback_intervals_forfrom products.alerts.backend.evaluation.funnel_strategies import strategy_for_viz@@ -58,6 +59,9 @@ class FunnelsExtractor:if condition.type != AlertConditionType.ABSOLUTE_VALUE and not strategy.supports_relative_conditions:raise AlertExtractionError("This funnel only supports absolute value conditions.")+ # The query clips the ongoing interval, so the trailing point is complete.+ already_complete = query_excludes_incomplete_periods(funnels_query)+# A relative condition diffs against the prior period, but the insight's own date range may be# too short to yield one — leaving the alert silently inert. Widen it to the trailing intervals# the comparator needs (mirroring the trends extractor). Absolute conditions read the insight's@@ -83,7 +87,7 @@ class FunnelsExtractor:if calculation_result.result is None:raise RuntimeError(f"No results found for insight with alert id = {alert.id}")- series = strategy.to_series(calculation_result.result, config)+ series = strategy.to_series(calculation_result.result, config, already_complete=already_complete)return ExtractionResult(series=series,is_breakdown=len(series) > 1,diff --git a/products/alerts/backend/evaluation/test/test_date_range_overrides.py b/products/alerts/backend/evaluation/test/test_date_range_overrides.pyindex 9c446f31d64d..7f3be4beac62 100644--- a/products/alerts/backend/evaluation/test/test_date_range_overrides.py+++ b/products/alerts/backend/evaluation/test/test_date_range_overrides.py@@ -1,13 +1,23 @@from unittest import TestCase+from unittest.mock import MagicMock, patch+import numpy as npfrom parameterized import parameterized-from posthog.schema import IntervalType, TrendsQuery+from posthog.schema import AlertConditionType, DateRange, IntervalType, TrendsQuery+from posthog.api.services.query import ExecutionModefrom posthog.tasks.alerts.detector import _date_range_override_for_detector-from posthog.tasks.alerts.trends import _date_range_override_for_intervals+from posthog.tasks.alerts.trends import (+ _date_range_override_for_intervals,+ _drop_incomplete_current_interval,+ query_excludes_incomplete_periods,+)from products.alerts.backend.evaluation.funnels import _trailing_date_range_override+from products.alerts.backend.evaluation.trends import TrendsExtractor++TRENDS_CALC_PATH = "products.alerts.backend.evaluation.trends.calculate_for_query_based_insight"class TestDateRangeOverrides(TestCase):@@ -29,3 +39,87 @@ class TestDateRangeOverrides(TestCase):)self.assertEqual(_date_range_override_for_detector(query, min_samples=2), {"date_from": expected_date_from})self.assertEqual(_trailing_date_range_override(interval, periods=2), {"date_from": expected_date_from})+++class TestIncompletePeriodInteraction(TestCase):+ @parameterized.expand(+ [+ ("drops_ongoing_interval_by_default", True, [1.0, 2.0], ["d1", "d2"]),+ ("keeps_complete_trailing_interval_when_query_clips", False, [1.0, 2.0, 3.0], ["d1", "d2", "d3"]),+ ]+ )+ def test_drop_current_polarity(self, _name, drop_current, expected_data, expected_dates):+ data, dates = _drop_incomplete_current_interval(+ np.array([1.0, 2.0, 3.0]), ["d1", "d2", "d3"], False, drop_current=drop_current+ )+ self.assertEqual(list(data), expected_data)+ self.assertEqual(dates, expected_dates)++ @parameterized.expand(+ [+ ("flag_set", DateRange(date_from="-7d", excludeIncompletePeriods=True), True),+ ("flag_unset", DateRange(date_from="-7d"), False),+ ("no_date_range", None, False),+ ]+ )+ def test_query_excludes_incomplete_periods(self, _name, date_range, expected):+ query = TrendsQuery(series=[], dateRange=date_range)+ self.assertEqual(query_excludes_incomplete_periods(query), expected)+++def _trends_alert(condition_type: AlertConditionType, check_ongoing: bool = False) -> MagicMock:+ alert = MagicMock()+ alert.config = {"type": "TrendsAlertConfig", "series_index": 0, "check_ongoing_interval": check_ongoing}+ alert.condition = {"type": condition_type}+ threshold = MagicMock()+ threshold.configuration = {"type": "absolute", "bounds": {"upper": 100}}+ alert.threshold = threshold+ return alert+++def _clipped_trends_query() -> dict:+ return {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ "interval": "day",+ "dateRange": {"date_from": "-7d", "excludeIncompletePeriods": True},+ }+++class TestTrendsExtractorIncompletePeriods(TestCase):+ @parameterized.expand(+ [+ ("absolute", AlertConditionType.ABSOLUTE_VALUE),+ ("relative_increase", AlertConditionType.RELATIVE_INCREASE),+ ("relative_decrease", AlertConditionType.RELATIVE_DECREASE),+ ]+ )+ def test_clipped_query_anchors_last_point_worded_as_previous(self, _name, condition_type):+ # A clipped query's last returned point is the last complete interval: it must be the+ # comparison anchor (not one further back), but the breach wording must still call it a+ # previous interval, since the ongoing one was never queried.+ row = {"data": [1.0, 2.0, 3.0], "days": ["d1", "d2", "d3"], "label": "series"}+ with patch(TRENDS_CALC_PATH) as calc:+ calc.return_value = MagicMock(result=[row])+ result = TrendsExtractor().extract(+ _trends_alert(condition_type),+ MagicMock(),+ _clipped_trends_query(),+ ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ )+ series = result.series[0]+ self.assertEqual(series.current_index, 2)+ self.assertFalse(series.is_current_interval)++ def test_check_ongoing_interval_conflicts_with_clipped_query(self):+ # The clip removes the ongoing interval from the results, so an alert asking to check it+ # can never do what it says: reject the configuration instead of silently degrading.+ with patch(TRENDS_CALC_PATH) as calc:+ calc.return_value = MagicMock(result=[{"data": [1.0, 2.0], "days": ["d1", "d2"], "label": "series"}])+ with self.assertRaisesRegex(ValueError, "excludes incomplete periods"):+ TrendsExtractor().extract(+ _trends_alert(AlertConditionType.ABSOLUTE_VALUE, check_ongoing=True),+ MagicMock(),+ _clipped_trends_query(),+ ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ )diff --git a/products/alerts/backend/evaluation/test/test_funnels_extractor.py b/products/alerts/backend/evaluation/test/test_funnels_extractor.pyindex c14559d6f1a0..5f8d205d9377 100644--- a/products/alerts/backend/evaluation/test/test_funnels_extractor.py+++ b/products/alerts/backend/evaluation/test/test_funnels_extractor.py@@ -16,13 +16,15 @@ def _steps(*counts: int) -> list[dict]:return [{"order": i, "count": c, "breakdown_value": None} for i, c in enumerate(counts)]-def _query(viz: str | None = None) -> dict:+def _query(viz: str | None = None, exclude_incomplete: bool = False) -> dict:query: dict = {"kind": "FunnelsQuery","series": [{"kind": "EventsNode", "event": "step_a"}, {"kind": "EventsNode", "event": "step_b"}],}if viz is not None:query["funnelsFilter"] = {"funnelVizType": viz}+ if exclude_incomplete:+ query["dateRange"] = {"date_from": "-7d", "excludeIncompletePeriods": True}return query@@ -34,11 +36,18 @@ def _alert(config: dict | None = None, condition_type: str = AlertConditionType.def _extract(- result, *, config: dict | None = None, viz: str | None = None, condition_type=AlertConditionType.ABSOLUTE_VALUE+ result,+ *,+ config: dict | None = None,+ viz: str | None = None,+ condition_type=AlertConditionType.ABSOLUTE_VALUE,+ exclude_incomplete: bool = False,):with patch(CALC_PATH) as calc:calc.return_value = MagicMock(result=result)- return FunnelsExtractor().extract(_alert(config, condition_type), MagicMock(), _query(viz), IF_STALE)+ return FunnelsExtractor().extract(+ _alert(config, condition_type), MagicMock(), _query(viz, exclude_incomplete), IF_STALE+ )def _config(@@ -112,23 +121,31 @@ def _trends_series(data: list[float], *, breakdown_value=None) -> dict:@pytest.mark.parametrize(- "condition_type,check_ongoing,expected_index,expected_value",+ "condition_type,check_ongoing,exclude_incomplete,expected_index,expected_value",[# Default: the latest period is in progress, so anchor the last *complete* one.- (AlertConditionType.ABSOLUTE_VALUE, False, 1, 20.0),+ (AlertConditionType.ABSOLUTE_VALUE, False, False, 1, 20.0),# check_ongoing_interval anchors the latest (in-progress) period instead.- (AlertConditionType.ABSOLUTE_VALUE, True, 2, 40.0),+ (AlertConditionType.ABSOLUTE_VALUE, True, False, 2, 40.0),# Relative conditions use the same anchor (then diff it against the period before it).- (AlertConditionType.RELATIVE_INCREASE, False, 1, 20.0),- (AlertConditionType.RELATIVE_INCREASE, True, 2, 40.0),+ (AlertConditionType.RELATIVE_INCREASE, False, False, 1, 20.0),+ (AlertConditionType.RELATIVE_INCREASE, True, False, 2, 40.0),+ # A clipped query (excludeIncompletePeriods) already excludes the in-progress period, so the+ # last returned point is complete and must be the anchor: skipping back one more would+ # evaluate a period-stale value.+ (AlertConditionType.ABSOLUTE_VALUE, False, True, 2, 40.0),+ (AlertConditionType.RELATIVE_INCREASE, False, True, 2, 40.0),],)-def test_trends_funnel_anchor_selection(condition_type, check_ongoing, expected_index, expected_value):+def test_trends_funnel_anchor_selection(+ condition_type, check_ongoing, exclude_incomplete, expected_index, expected_value+):result = _extract([_trends_series([10.0, 20.0, 40.0])],viz="trends",condition_type=condition_type,config=_config(check_ongoing_interval=check_ongoing),+ exclude_incomplete=exclude_incomplete,)assert result.subject == "The funnel conversion rate"assert result.unit == "%"@@ -138,6 +155,18 @@ def test_trends_funnel_anchor_selection(condition_type, check_ongoing, expected_assert series.points[series.current_index].value == expected_value+def test_check_ongoing_interval_conflicts_with_clipped_query():+ # The clip removes the ongoing interval from the results, so an alert asking to check it can+ # never do what it says — reject the conflicting configuration instead of silently degrading.+ with pytest.raises(AlertExtractionError, match="excludes incomplete periods"):+ _extract(+ [_trends_series([10.0, 20.0])],+ viz="trends",+ config=_config(check_ongoing_interval=True),+ exclude_incomplete=True,+ )++def test_trends_funnel_breakdown_yields_one_series_per_value():# check_ongoing_interval so the anchor is the latest (only) interesting point per breakdown.result = _extract(diff --git a/products/alerts/backend/evaluation/trends.py b/products/alerts/backend/evaluation/trends.pyindex 33e196fc0699..686868f72eb2 100644--- a/products/alerts/backend/evaluation/trends.py+++ b/products/alerts/backend/evaluation/trends.py@@ -23,6 +23,7 @@ from posthog.tasks.alerts.trends import (_has_breakdown,_is_non_time_series_trend,_pick_series_result,+ query_excludes_incomplete_periods,)from products.alerts.backend.evaluation.contract import (@@ -71,6 +72,13 @@ class TrendsExtractor:is_non_time_series = _is_non_time_series_trend(query)has_breakdown = _has_breakdown(query)check_current_interval = bool(config.check_ongoing_interval)+ # The query clips the ongoing interval, so the trailing point is complete.+ already_complete = query_excludes_incomplete_periods(query)+ if check_current_interval and already_complete:+ raise ValueError(+ "check_ongoing_interval is not supported when the insight excludes incomplete periods "+ "(DateRange.excludeIncompletePeriods): the ongoing interval is clipped from the query results"+ )lookback_intervals = lookback_intervals_for(condition)interval_type = None if is_non_time_series else query.interval@@ -132,7 +140,16 @@ class TrendsExtractor:case _:raise NotImplementedError(f"Unsupported alert condition type: {condition.type}")- series = self._to_series(config, calculation_result, has_breakdown, is_non_time_series, anchor_is_current)+ # A clipped query's trailing point is complete: anchor on it instead of skipping back one+ # more period, while keeping is_current_interval false so breach wording stays "previous".+ series = self._to_series(+ config,+ calculation_result,+ has_breakdown,+ is_non_time_series,+ anchor_last_point=anchor_is_current or already_complete,+ is_current_interval=anchor_is_current,+ )# subject/framed use the ExtractionResult defaults ("The insight value", framed).return ExtractionResult(series=series,@@ -188,7 +205,9 @@ class TrendsExtractor:calculation_result: InsightResult,has_breakdown: bool,is_non_time_series: bool,- anchor_is_current: bool,+ *,+ anchor_last_point: bool,+ is_current_interval: bool,) -> list[ComparableSeries]:if has_breakdown:results = cast(list[dict[str, Any]], calculation_result.result)@@ -204,16 +223,17 @@ class TrendsExtractor:dates = result.get("dates") or result.get("days") or [None] * len(data)points = [SeriesPoint(date=date, value=value) for date, value in zip(dates, data)]- # Anchor on the current (ongoing) interval, or the last complete one. On a series- # shorter than expected this can go negative and wrap, which the comparator then- # treats as having no previous point — acceptable for a degenerate sparse series.- current_index = len(points) - 1 if anchor_is_current else len(points) - 2+ # Anchor on the last point (the ongoing interval, or the last complete one on a clipped+ # query), or the second-to-last. On a series shorter than expected this can go negative+ # and wrap, which the comparator then treats as having no previous point — acceptable+ # for a degenerate sparse series.+ current_index = len(points) - 1 if anchor_last_point else len(points) - 2series.append(ComparableSeries(label=humanize_breakdown_label(result["label"]),points=points,current_index=current_index,- is_current_interval=anchor_is_current,+ is_current_interval=is_current_interval,))return seriesdiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 8ddd607721cc..2c964eb7a26a 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -992,6 +992,8 @@ export interface DateRangeApi {date_to?: string | null/** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */daysOfWeek?: DaysOfWeekEnumApi[] | null+ /** Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries. */+ excludeIncompletePeriods?: boolean | null/** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */explicitDate?: boolean | null}diff --git a/products/product_analytics/backend/models/test/test_insight_model.py b/products/product_analytics/backend/models/test/test_insight_model.pyindex 40d60736927c..ad3ce688adf4 100644--- a/products/product_analytics/backend/models/test/test_insight_model.py+++ b/products/product_analytics/backend/models/test/test_insight_model.py@@ -152,6 +152,7 @@ class TestInsightModel(BaseTest):"date_to": "-7d","explicitDate": False,"daysOfWeek": None,+ "excludeIncompletePeriods": False,},"filterTestAccounts": None,"properties": None,@@ -167,6 +168,7 @@ class TestInsightModel(BaseTest):"date_to": "-3d","explicitDate": False,"daysOfWeek": None,+ "excludeIncompletePeriods": False,},"filterTestAccounts": None,"properties": None,@@ -182,6 +184,7 @@ class TestInsightModel(BaseTest):"date_to": None,"explicitDate": False,"daysOfWeek": None,+ "excludeIncompletePeriods": False,},"filterTestAccounts": None,"properties": None,diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 9bdef6212857..143fb5c5a995 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -306,6 +306,8 @@ export interface DateRangeApi {date_to?: string | null/** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */daysOfWeek?: DaysOfWeekEnumApi[] | null+ /** Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries. */+ excludeIncompletePeriods?: boolean | null/** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */explicitDate?: boolean | null}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0b2a68d05343..440ffb011954 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -2375,6 +2375,8 @@ export namespace Schemas {date_to?: string | null;/** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */daysOfWeek?: DaysOfWeekEnum[] | null;+ /** Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries. */+ excludeIncompletePeriods?: boolean | null;/** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */explicitDate?: boolean | null;}diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.tsindex ad7311eb4159..b1cc19651113 100644--- a/services/mcp/src/tools/generated/mcp_analytics.ts+++ b/services/mcp/src/tools/generated/mcp_analytics.ts@@ -236,6 +236,14 @@ const DateRange = z.object({'Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries.').optional(),+ excludeIncompletePeriods: z.coerce+ .boolean()+ .nullable()+ .describe(+ 'Exclude the current, still-collecting period by clipping date_to to the end of the last complete interval (evaluated in the project timezone). No-op when the range contains no complete interval. Only applied by insight queries.'+ )+ .default(false)+ .optional(),explicitDate: z.coerce.boolean().nullable()