: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): show full previous period for hourly compare (#88428)
Sam Pennington1a153a4c331d
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends.py b/posthog/hogql_queries/insights/trends/test/test_trends.pyindex a1918c369812..9eb6a90c7b7b 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends.py@@ -2193,6 +2193,8 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):0, # 20:00],)+ # The previous period spans the full day (00:00–23:00), not just the elapsed part of today,+ # so both series can be compared hour-by-hour across the whole chart.self.assertEqual(response[1]["days"],[@@ -2217,6 +2219,9 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):"2020-01-01 18:00:00","2020-01-01 19:00:00","2020-01-01 20:00:00",+ "2020-01-01 21:00:00",+ "2020-01-01 22:00:00",+ "2020-01-01 23:00:00",],)self.assertEqual(@@ -2243,6 +2248,9 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):0, # 18:000, # 19:000, # 20:00+ 0, # 21:00+ 0, # 22:00+ 0, # 23:00],)diff --git a/posthog/hogql_queries/utils/query_compare_to_date_range.py b/posthog/hogql_queries/utils/query_compare_to_date_range.pyindex 4026ec8ef8f2..7501080c4c6e 100644--- a/posthog/hogql_queries/utils/query_compare_to_date_range.py+++ b/posthog/hogql_queries/utils/query_compare_to_date_range.py@@ -42,7 +42,7 @@ class QueryCompareToDateRange(QueryDateRange):return DateRangeBounds(date_from=start_date,- date_to=start_date + (current_period_date_to - current_period_date_from),+ date_to=start_date + (self.nominal_comparison_date_to(current_period_date_to) - current_period_date_from),)def date_to(self) -> datetime:diff --git a/posthog/hogql_queries/utils/query_date_range.py b/posthog/hogql_queries/utils/query_date_range.pyindex 8ab7126cbd11..59bbdb5cdac6 100644--- a/posthog/hogql_queries/utils/query_date_range.py+++ b/posthog/hogql_queries/utils/query_date_range.py@@ -204,6 +204,33 @@ class QueryDateRange:def previous_period_date_from(self) -> datetime:return self.date_from() - (self.date_to() - self.date_from())+ def nominal_comparison_date_to(self, current_period_date_to: datetime) -> datetime:+ """End of the current period used to size a comparison (previous) period.++ Day and coarser intervals snap `date_to` to the end of the current day, so the comparison+ period comes back complete. Hour and minute intervals snap only to the end of the current+ hour or minute, which sizes the comparison period to the elapsed part of the period and cuts+ it short (the "both lines stop halfway" bug). For a day-anchored range that runs up to now+ (today, this week, "-7d"), extend the end to the end of the current day so hour and minute+ granularity match the coarser intervals. Rolling sub-day windows ("-24h", "-30m") keep their+ real end, since their previous period is just the window before them.+ """+ if self.interval_name not in ("hour", "minute"):+ return current_period_date_to+ if self._exact_timerange or self.explicit:+ return current_period_date_to+ if self._date_range and self._date_range.date_to:+ return current_period_date_to+ date_from = (+ self._date_range.date_from if self._date_range and isinstance(self._date_range.date_from, str) else "-7d"+ )+ if date_from == "all":+ return current_period_date_to+ delta = relative_date_parse_with_delta_mapping(date_from, self._timezone_info, now=self.now_with_timezone)[1]+ if delta is None or any(unit in delta for unit in ("hours", "minutes", "seconds")):+ return current_period_date_to+ return current_period_date_to.replace(hour=23, minute=59, second=59, microsecond=999999)+@cached_propertydef now_with_timezone(self) -> datetime:return self._now_without_timezone.astimezone(self._timezone_info)diff --git a/posthog/hogql_queries/utils/query_previous_period_date_range.py b/posthog/hogql_queries/utils/query_previous_period_date_range.pyindex b054c03bda32..87a585cd5299 100644--- a/posthog/hogql_queries/utils/query_previous_period_date_range.py+++ b/posthog/hogql_queries/utils/query_previous_period_date_range.py@@ -76,7 +76,7 @@ class QueryPreviousPeriodDateRange(QueryDateRange):previous_period_date_from, previous_period_date_to = get_compare_period_dates(current_period_date_from,- current_period_date_to,+ self.nominal_comparison_date_to(current_period_date_to),self.date_from_delta_mappings(),self.date_to_delta_mappings(),self.interval_name,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 75856b5c003b..944b4f1693f2 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@@ -62,6 +62,28 @@ class TestQueryPreviousPeriodDateRange(APIBaseTest):self.assertEqual(query_date_range.date_to(), parser.isoparse(earliest_timestamp) - timedelta(microseconds=1))self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_date_from))+ @parameterized.expand(+ [+ # A day-anchored range at hour granularity used to size the previous period from the+ # elapsed part of today (ending 12:59), truncating it. It now spans the full previous+ # day, matching how day/week/month intervals already behave.+ ("today_hour", "dStart", IntervalType.HOUR, "2021-08-24T00:00:00Z", "2021-08-24T23:59:59.999999Z"),+ ("today_minute", "dStart", IntervalType.MINUTE, "2021-08-24T00:00:00.000001Z", "2021-08-25T00:00:00Z"),+ ("last_7d_hour", "-7d", IntervalType.HOUR, "2021-08-10T00:00:00Z", "2021-08-17T23:59:59.999999Z"),+ # A rolling sub-day window is unchanged: its previous period is just the window before it.+ ("last_24h_hour", "-24h", IntervalType.HOUR, "2021-08-23T12:00:00Z", "2021-08-24T12:59:59.999999Z"),+ ]+ )+ def test_previous_period_hourly_range_sizing(+ self, _name: str, date_from: str, interval: IntervalType, expected_from: str, expected_to: str+ ):+ now = parser.isoparse("2021-08-25T12:34:00.000Z")+ query_date_range = QueryPreviousPeriodDateRange(+ team=self.team, date_range=DateRange(date_from=date_from), interval=interval, now=now+ )+ self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_from))+ self.assertEqual(query_date_range.date_to(), parser.isoparse(expected_to))+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/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambrindex 56e4d75f5945..75d277e22f23 100644--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr@@ -34,7 +34,7 @@e.`$window_id` AS `$window_id`,if(equals(e.event, 'user signed up'), 1, 0) AS step_0,if(equals(e.event, 'user did things'), 1, 0) AS step_1,- ([e__person.properties___fish] AS value) AS prop_basic,+ ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,prop_basic AS propFROM events AS eLEFT OUTER JOIN@@ -44,16 +44,6 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- LEFT JOIN- (SELECT person.id AS id,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish- FROM person- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),- (SELECT person.id AS id, max(person.version) AS version- FROM person- WHERE equals(person.team_id, 99999)- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))GROUP BY aggregation_targetHAVING ifNull(greaterOrEquals(step_reached, 0), 0))@@ -121,17 +111,7 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- LEFT JOIN- (SELECT person.id AS id,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish- FROM person- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),- (SELECT person.id AS id, max(person.version) AS version- FROM person- WHERE equals(person.team_id, 99999)- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))GROUP BY aggregation_targetHAVING ifNull(greaterOrEquals(step_reached, 0), 0))GROUP BY breakdown@@ -188,8 +168,8 @@e.uuid AS uuid,e.`$session_id` AS `$session_id`,e.`$window_id` AS `$window_id`,- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1FROM events AS eLEFT OUTER JOIN(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,@@ -198,16 +178,6 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- LEFT JOIN- (SELECT person.id AS id,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish- FROM person- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),- (SELECT person.id AS id, max(person.version) AS version- FROM person- WHERE equals(person.team_id, 99999)- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))GROUP BY aggregation_targetHAVING ifNull(greaterOrEquals(step_reached, 0), 0))@@ -324,24 +294,7 @@(SELECT count() AS total,toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events AS e- LEFT OUTER JOIN- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- LEFT JOIN- (SELECT person.id AS id,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish- FROM person- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),- (SELECT person.id AS id, max(person.version) AS version- FROM person- WHERE equals(person.team_id, 99999)- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)@@ -373,24 +326,7 @@(SELECT count() AS total,toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_startFROM events AS e- LEFT OUTER JOIN- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)- LEFT JOIN- (SELECT person.id AS id,- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish- FROM person- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),- (SELECT person.id AS id, max(person.version) AS version- FROM person- WHERE equals(person.team_id, 99999)- GROUP BY person.id- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))GROUP BY day_start)GROUP BY day_startORDER BY day_start ASC)diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsxindex 89c7416663ed..d60db6521853 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx@@ -7,6 +7,7 @@ import { dimensions, dragSelection, rawDrag, setupJsdom, setupSyncRaf } from '@pimport { FEATURE_FLAGS } from 'lib/constants'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import type { IndexedTrendResult } from 'scenes/trends/types'import { urls } from 'scenes/urls'import { ExportType } from '~/exporter/types'@@ -26,6 +27,8 @@ import {import { buildAnnotation } from '~/test/insight-testing/test-data'import { AnnotationScope, ChartDisplayType, InsightShortId } from '~/types'+import { extendLabelsToLongestSeries } from './TrendsLineChart'+// The full InsightViz tree is heavy to mount under jsdom; on contended CI shards// the default 1s waitFor / findBy timeout is too tight and flakes randomly.configure({ asyncUtilTimeout: 5000 })@@ -942,4 +945,28 @@ describe('TrendsLineChart', () => {expect(getQuerySource().dateRange).toBeUndefined()})})++ describe('extendLabelsToLongestSeries', () => {+ const result = (data: number[]): IndexedTrendResult => ({ data }) as IndexedTrendResult++ it('extends the hourly domain forward to a longer previous series', () => {+ const currentDays = ['2020-01-02 00:00:00', '2020-01-02 01:00:00', '2020-01-02 02:00:00']+ const extended = extendLabelsToLongestSeries(currentDays, 'hour', [+ result([0, 0, 1]),+ result([3, 0, 0, 0, 0]),+ ])+ expect(extended).toEqual([+ '2020-01-02 00:00:00',+ '2020-01-02 01:00:00',+ '2020-01-02 02:00:00',+ '2020-01-02 03:00:00',+ '2020-01-02 04:00:00',+ ])+ })++ it('leaves the domain untouched when no series is longer', () => {+ const days = ['2020-01-02', '2020-01-03', '2020-01-04']+ expect(extendLabelsToLongestSeries(days, 'day', [result([1, 2, 3]), result([4, 5, 6])])).toBe(days)+ })+ })})diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex 3f651bcd39e5..13c2588a24a1 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -6,6 +6,7 @@ import { DEFAULT_Y_AXIS_ID, TimeSeriesLineChart } from '@posthog/quill-charts'import type { PointClickData, TooltipContext } from '@posthog/quill-charts'import { useChartTheme, useChartConfig, useDateRangeZoom } from 'lib/charts/hooks'+import { dayjs } from 'lib/dayjs'import { ciRanges } from 'lib/statistics'import { percentage } from 'lib/utils/numbers'import { isMultiSeriesFormula } from 'lib/utils/strings'@@ -24,7 +25,7 @@ import { groupsModel } from '~/models/groupsModel'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import { InsightVizNode } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'-import { ChartDisplayType } from '~/types'+import { ChartDisplayType, type IntervalType } from '~/types'import { chartStyleCurve } from '../../shared/chartStyleAdapter'import { hasTrendsChartData } from '../../shared/hasTrendsChartData'@@ -47,6 +48,31 @@ interface TrendsLineChartProps {const handleChartError = makeChartErrorHandler('trends-line-chart')+// A completed comparison ("previous") period can span more buckets than the still-in-progress+// current period — e.g. a full "yesterday" against "today" so far at hour granularity. The x-axis+// is keyed off the current period's days, so the extra previous-period points would fall outside+// the domain and get clipped. Extend the domain forward by the interval so the previous series+// spans the full width; the current series keeps its shorter, dashed tail.+export function extendLabelsToLongestSeries(+ labels: string[],+ interval: IntervalType | null | undefined,+ results: IndexedTrendResult[]+): string[] {+ const maxLength = results.reduce((max, r) => Math.max(max, r.data?.length ?? 0), 0)+ if (!labels.length || labels.length >= maxLength) {+ return labels+ }+ const hasTime = labels[0].includes(' ')+ const format = hasTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'+ const extended = [...labels]+ let cursor = dayjs(labels[labels.length - 1])+ while (extended.length < maxLength) {+ cursor = cursor.add(1, (interval ?? 'day') as dayjs.ManipulateType)+ extended.push(cursor.format(format))+ }+ return extended+}+export function TrendsLineChart({context,inSharedMode = false,@@ -110,7 +136,12 @@ export function TrendsLineChart({// tooltip formatters already render display text from them. Stickiness x values are// interval counts rather than dates, so it keeps its (already unique) labels.const days = currentPeriodResult?.days- const labels = (!isStickiness && days?.length ? days : currentPeriodResult?.labels) ?? []+ const useDayLabels = !isStickiness && !!days?.length+ const labels = useDayLabels+ ? extendLabelsToLongestSeries(days as string[], interval, indexedResults ?? [])+ : (currentPeriodResult?.labels ?? [])+ // Keep the tick formatter's day context in step with the (possibly extended) domain.+ const allDays = useDayLabels ? labels : (currentPeriodResult?.days ?? [])const hasData = hasTrendsChartData(indexedResults)@@ -281,7 +312,7 @@ export function TrendsLineChart({yAxisScaleType,interval,timezone,- allDays: currentPeriodResult?.days ?? [],+ allDays,xAxisLabel: trendsFilter?.xAxisLabel,yAxisLabel: trendsFilter?.yAxisLabel,yAxisStartAtZero: trendsFilter?.yAxisStartAtZero,@@ -312,7 +343,7 @@ export function TrendsLineChart({yAxisScaleType,interval,timezone,- currentPeriodResult?.days,+ allDays,goalLines,incompletenessOffsetFromEnd,getTrendsHidden,