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.

feat(error-tracking): rebuild the insights tab with release breakdowns (#91546)

Aleksander Błaszkiewicz3b045d09a444
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4ac293ff75ec..1b7dc5021670 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6692,6 +6692,42 @@ snapshots:
hash: v1.k794b7964.c34b2dacf3e9f04b7bc29aa4d636c9caa0e704dbfce5d0a3c1fe55ad8a0cbb94.W22WNZoQ5TiTsFojdfLU6XqFf1VyadhJGynmq1sKv9c
scenes-app-error-project-unavailable--no-selectable-projects--light:
hash: v1.k794b7964.25cba9f347696eb78fc20a05e5f37e514e17b483c0e7f2cbc2a0ff581eef2b72.Z1uJTP8R_ATm8aciECP4ScSzcSTFpYd7VQI6kVswSMg
+ scenes-app-error-tracking-insights-panels--exceptions-by-app--dark:
+ hash: v1.k794b7964.fb5c13d8f5ad378540f766e086a5cc6f22e172bf3b56acad1d12a78ccc5ec01d.4pARkbniyq4nz6H1OJ4vnnmQ45YLUyFL3dG7pcmV5x0
+ scenes-app-error-tracking-insights-panels--exceptions-by-app--light:
+ hash: v1.k794b7964.eebac61d7595f19fb081e5836a3391cda9788157dd1b5db811f038ef693c71e4.QV1eXeeJpNW2ryeYtA0cTCaSpZ7JsKQ1thFwEG_iX88
+ scenes-app-error-tracking-insights-panels--exceptions-by-release--dark:
+ hash: v1.k794b7964.1a6cf6187df8c4f0410359e2be02ecff4dc3286bbdf004d2f9d2a65d91b15160.kgbEHlY26qj4jTFr03fgGm0j_QjpKzV1vczDiM9xKFk
+ scenes-app-error-tracking-insights-panels--exceptions-by-release--light:
+ hash: v1.k794b7964.b9d2e6d25eece5e72506ac09d50968aaa1121b64481ccba7cbec9e03651ff185.ejD7CmOLjy6mE_Q3yPyJFZWrLWI9UrUKrwo05Np8QIM
+ scenes-app-error-tracking-insights-panels--exceptions-by-release-empty--dark:
+ hash: v1.k794b7964.539eb487fb34f358aa2049b0d7fc25cc2c4884d44e8fe95c5aa0f0b5bf78835e.A8bjQHMqc9s9eYn7kB-B3G4V2tjS8Ol6b-KdR1JV42k
+ scenes-app-error-tracking-insights-panels--exceptions-by-release-empty--light:
+ hash: v1.k794b7964.7c72ce2b6fe7cb7e5da3059b12a80b8d0693ca4cdb3a1509a142f9aa3d1b43b4.UnNy2dAD5rRz2DPBaSAnMHtqyuDjuUBCwQBc1RO54-U
+ scenes-app-error-tracking-insights-panels--exceptions-by-release-in-progress-bucket--dark:
+ hash: v1.k794b7964.9a5da11ad4e84c578ee860ec6cc9a7aa6b48648e198f28d9fb1e8ffcf1191cd6.r9lOAvij3gqLD8srJZxPjTD74PnV_dEV7gtzr1F_ppk
+ scenes-app-error-tracking-insights-panels--exceptions-by-release-in-progress-bucket--light:
+ hash: v1.k794b7964.b6bcea8b4d068993547b0dc93d7355317c681bdef9a049b78f5943e0e7199021.y34H0Vt5ADwEys3HfBXxnLgm9jRiq8a1SlFOCnatgu8
+ scenes-app-error-tracking-insights-panels--key-metrics--dark:
+ hash: v1.k794b7964.de2de43207fe62b131579cccbd0d82a1848144bac6a0a05b06e408724618152f.UbXSy7l4055Zp4p2dzEQ6NYvegl2R2BGJGAv_uKvzYk
+ scenes-app-error-tracking-insights-panels--key-metrics--light:
+ hash: v1.k794b7964.3fa77fb4b86c0de3eaa3d27a5267958377cdf6a3d0fde7bf2401cd25c45ee98f.EzqhidpeyN8cluPa0a1dzu5zTb2l1HqGzHac9_KagS0
+ scenes-app-error-tracking-insights-panels--key-metrics-in-progress-bucket--dark:
+ hash: v1.k794b7964.9f13cc6e6af4525849b5689fa0ddb0787e0bf27f3ba29761cf0da2b80ce3fd1a.Q5ycz3uCUh_xtWJhHl47bkOqQTzlWEF_AsNaifokMnI
+ scenes-app-error-tracking-insights-panels--key-metrics-in-progress-bucket--light:
+ hash: v1.k794b7964.ac5b091bb0f44a5dbc546128e01b58bd047edd3a0d1adb9f7832aea6dd6fe1a4.gbM8Wd6JQnhN6ACrP4sd_jZ3yIH6oZf59OFnPDQJQr8
+ scenes-app-error-tracking-insights-panels--key-metrics-loading--dark:
+ hash: v1.k794b7964.db30cdfb288aff6f15bc2eaf9333fd599a540bb0397525ac295ac6ed4d4a892b.51e4e34lRTCat9K9kbGdWvaO6QNDcU8S0zDNBjjzcLw
+ scenes-app-error-tracking-insights-panels--key-metrics-loading--light:
+ hash: v1.k794b7964.f9776b97b74093b3ffa7b8434821b929d7cee4af748725c28db2b1b032698d89.r21qK-Q6yV6rGe48p7reW8lYtzD0uYnyecIb89rB0MQ
+ scenes-app-error-tracking-insights-panels--key-metrics-narrow-scene--dark:
+ hash: v1.k794b7964.66709d56a840c27a0512403ad2d5552dfdcc32b404aa1e4677901ea356e3d910.f9H1jCqhcMvH9BVctkMVYy5PwkoUE3htt8plq0puKow
+ scenes-app-error-tracking-insights-panels--key-metrics-narrow-scene--light:
+ hash: v1.k794b7964.0d3fc071e8be5b6d23cb78ba681159b03b7974eb264134001ec5818ef1e9ee2b.u3DSMAooGY0uRKI06__c5pIsNrkkLXBBE-7frOYWccI
+ scenes-app-error-tracking-insights-panels--release-list--dark:
+ hash: v1.k794b7964.9499e2d132106a167a5b80083e7fde8d87dc505c10b88df6f7da33caf58b1924._7etlGW7P7rPphXSm92I9LNAZvzApU4zTuA3bDkpNbM
+ scenes-app-error-tracking-insights-panels--release-list--light:
+ hash: v1.k794b7964.f348be5ccd7694090ebd0e41d249917849bbd92cfd08545726f3372ab6d5388c.km2n6GFkB2Qo5BFRYLm8Y1lzK0TPeDG2VxuUxjDx-wQ
scenes-app-errortracking--group-page--dark:
hash: v1.k794b7964.c6e4938f5fea35b65ef57198ee2b0935151e55b3bfdc90f0d84fa4c416cf24a6.EGidst1m2mmQK0RVXKF46D2Yg-iPEGfk3k6VhE70drk
scenes-app-errortracking--group-page--light:
@@ -6749,9 +6785,9 @@ snapshots:
scenes-app-errortracking--group-page-with-self-driving--light:
hash: v1.k794b7964.4c24d565a6a126a64761040eb44a64d5a689fc04a8b566ccc5410147c19451fc.wuQskHSi8SlMXfFZuza565EKQMIw1RhLM-1UCclFPJ8
scenes-app-errortracking--insights-page--dark:
- hash: v1.k794b7964.53b21c283d6e02513197c47385305bcde043553c03a05f410c4fca51b8ac3c76.ZqqLe0fDujqr3-AQieKGpq9howa1_XaoLdPAoZC9ceI
+ hash: v1.k794b7964.547ba7d50edff3d4fd57c33937b1536edb9837c5c34fd57543b29a5fb257e848.V99ai7csLzzA-J4mPePBh5GIyIie_ulJCWMMU7bfioE
scenes-app-errortracking--insights-page--light:
- hash: v1.k794b7964.0da15fab41604af57c36492d1eeb1cfbe0524557126ab8e61b1f2bace0ddbd10.zQQ_qIbZM_7JnmZHvOIudQQ5rmFGKeuyNiRxvBC4WJk
+ hash: v1.k794b7964.3792a45742b9bdfd5027555b815de1de585ffe1aad22390d967011897d8bf41a.KNidY9SojrCF8l_wl5I05rDOfvJDO88vl6maXfxf5Tg
scenes-app-errortracking--list-page--dark:
hash: v1.k794b7964.2fcf2311aa6f601214b532ccb22e83ef378b87ed1fd6705085b8276ca245ba6f.zLha5NipvTWdyRZqgMiowFL3N5MicRiuwrfuAa22y7c
scenes-app-errortracking--list-page--light:
diff --git a/products/mcp_analytics/frontend/timeBuckets.test.ts b/frontend/src/lib/utils/timeBuckets.test.ts
similarity index 81%
rename from products/mcp_analytics/frontend/timeBuckets.test.ts
rename to frontend/src/lib/utils/timeBuckets.test.ts
index 6cd4fb22f579..bbcf93603033 100644
--- a/products/mcp_analytics/frontend/timeBuckets.test.ts
+++ b/frontend/src/lib/utils/timeBuckets.test.ts
@@ -4,6 +4,7 @@ import { IntervalType } from '~/types'
import {
buildBucketKeys,
+ buildComparisonWindow,
formatBucketLabel,
intervalOptionsForWindow,
lastBucketIsInProgress,
@@ -203,4 +204,43 @@ describe('timeBuckets', () => {
])
})
})
+ describe('buildComparisonWindow', () => {
+ it.each([
+ ['2024-01-08', '2024-01-15', 'day', '2024-01-08 00:00:00', '2023-12-31'],
+ ['2024-01-01', '2024-01-31', 'day', '2024-01-01 00:00:00', '2023-12-01'],
+ ])(
+ 'extends [%s, %s] back to an equal-length prior window with cutoff at the selected start',
+ (dateFrom, dateTo, interval, expectedCutoff, expectedPriorStart) => {
+ const window = buildComparisonWindow(dateFrom, dateTo, 'UTC', interval as 'day')
+ expect(window.currentStartBucket).toBe(expectedCutoff)
+ expect(dayjs(window.dateFrom).format('YYYY-MM-DD')).toBe(expectedPriorStart)
+ }
+ )
+
+ it('rolls an hour-level range from now and steps the prior window back by its exact length', () => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:37:00Z'))
+ try {
+ // "-1h" resolves to the trailing hour; prior window is the hour before that, not the
+ // hour before the bucket it starts in.
+ const window = buildComparisonWindow('-1h', null, 'UTC', 'hour')
+ expect(window.currentStart).toBe('2026-06-18 11:37:00')
+ expect(window.currentStartBucket).toBe('2026-06-18 11:00:00')
+ expect(dayjs(window.dateFrom).toISOString()).toBe('2026-06-18T10:37:00.000Z')
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('resolves the relative -7d default against now', () => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))
+ try {
+ const window = buildComparisonWindow('-7d', null, 'UTC', 'day')
+ expect(window.currentStartBucket).toBe('2026-06-11 00:00:00')
+ // prior window is as long as the selected one: seven days plus today's elapsed 12h
+ expect(dayjs(window.dateFrom).format('YYYY-MM-DD')).toBe('2026-06-03')
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+ })
})
diff --git a/products/mcp_analytics/frontend/timeBuckets.ts b/frontend/src/lib/utils/timeBuckets.ts
similarity index 80%
rename from products/mcp_analytics/frontend/timeBuckets.ts
rename to frontend/src/lib/utils/timeBuckets.ts
index 8ad78fddc76d..fb2a837f7e4f 100644
--- a/products/mcp_analytics/frontend/timeBuckets.ts
+++ b/frontend/src/lib/utils/timeBuckets.ts
@@ -74,8 +74,8 @@ export const SELECTABLE_INTERVALS: IntervalType[] = ['hour', 'day', 'week', 'mon
const INTERVAL_LABELS: Record<string, string> = { hour: 'Hour', day: 'Day', week: 'Week', month: 'Month' }
-// A line this dense is already a smear, and MCPToolQualityDailyStatsQuery's row limit starts dropping
-// the newest buckets not far above it, so intervals past this many points are offered disabled.
+// A line this dense is already a smear, and query runners that cap their row count start dropping the
+// newest buckets not far above it, so intervals past this many points are offered disabled.
const MAX_BUCKETS = 1000
export interface IntervalOption {
@@ -178,3 +178,37 @@ export function formatBucketLabel(bucket: string, interval: IntervalType): strin
? d.format('MMM D, HH:mm')
: d.format('MMM D')
}
+
+export interface ComparisonWindow {
+ /** Start of the doubled window: one selected period earlier than the selected period's start. */
+ dateFrom: string
+ /** The caller's own `dateTo`, unresolved. A date-only bound resolves inclusively server-side and
+ * a datetime resolves exclusively, so handing back a resolved instant would make a query built
+ * on this window cover a different last day than one built on the raw range. */
+ dateTo: string | null
+ /** The selected period's exact start, as a project-timezone wall clock, to split raw timestamps on. */
+ currentStart: string
+ /** Bucket key the doubled window splits on. Buckets at or after it are the selected period. */
+ currentStartBucket: string
+}
+
+// Extend the resolved window back by the selected period's exact length, so one query returns both the
+// selected period and the period before it for a period-over-period comparison. `currentStart` and
+// `currentStartBucket` are formatted to match ClickHouse dateTrunc's DateTime output, so a caller can
+// split the returned rows on a plain string compare.
+export function buildComparisonWindow(
+ dateFrom: string | null,
+ dateTo: string | null,
+ timezone: string,
+ interval: IntervalType
+): ComparisonWindow {
+ const { start, end } = resolveWindow(dateFrom, dateTo, timezone)
+ // A date-only end bound covers its whole day, so the period runs to the end of that day.
+ const periodEnd = dateTo && /^\d{4}-\d{2}-\d{2}$/.test(dateTo) ? end.endOf('day') : end
+ return {
+ dateFrom: start.subtract(periodEnd.diff(start)).toISOString(),
+ dateTo,
+ currentStart: start.format(BUCKET_FORMAT),
+ currentStartBucket: startOfBucket(start, interval).format(BUCKET_FORMAT),
+ }
+}
diff --git a/frontend/src/queries/nodes/InsightViz/InsightViz.scss b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
index 52182a7ff431..f5b1fd1b8167 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightViz.scss
+++ b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
@@ -339,6 +339,15 @@
height: 100%;
}
+ // An embedded query renders `.InsightCard__viz` instead of `.InsightViz`, and that wrapper carries
+ // no sizing of its own. Give it the same full-height flex column, or the chart collapses to its
+ // content height and leaves the bottom of the card empty.
+ .InsightCard__viz {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ }
+
.InsightVizDisplay {
display: flex;
flex-direction: column;
diff --git a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
index c63b4abef072..06fa2eefbc0a 100644
--- a/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
+++ b/frontend/src/scenes/hog-functions/invocations/hogInvocationsLogic.tsx
@@ -492,7 +492,7 @@ const snapToBucket = (t: dayjs.Dayjs, { stepAmount, stepUnit }: SparklineTier):
* Bucket key format, matching what ClickHouse renders a bucketed DateTime as. Buckets join on the
* project's wall clock rather than on an instant: `toStartOfDay` returns local midnight, and the
* offset it is stamped with is a rendering detail, not a second piece of data. Mirrors
- * `products/mcp_analytics/frontend/timeBuckets.ts`, which solves the same problem for its charts.
+ * `lib/utils/timeBuckets.ts`, which solves the same problem for its charts.
*/
const BUCKET_FORMAT = 'YYYY-MM-DD HH:mm:ss'
/** Enough for the widest tier (a minutely day is 1440); caps an absolute range picked far apart. */
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fdb941ba0cd7..f2e517667e5d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3264,6 +3264,9 @@ importers:
'@posthog/quill-charts':
specifier: workspace:*
version: link:../../packages/quill/packages/charts
+ '@posthog/quill-components':
+ specifier: workspace:*
+ version: link:../../packages/quill/packages/components
'@storybook/react':
specifier: 'catalog:'
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_breakdowns_query_runner.py b/products/error_tracking/backend/hogql_queries/error_tracking_breakdowns_query_runner.py
index 42ec79a19684..1171f96c5e23 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_breakdowns_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_breakdowns_query_runner.py
@@ -32,15 +32,19 @@ class ErrorTrackingBreakdownsQueryRunner(
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.query.issueId = validate_uuid_param(self.query.issueId, "issueId")
- self.date_from = self.parse_relative_date_from(self.query.dateRange.date_from if self.query.dateRange else None)
+ self.date_from = self.parse_relative_date_from(
+ self.query.dateRange.date_from if self.query.dateRange else None, self.team.timezone_info
+ )
self.date_to = self.parse_relative_date_to(self.query.dateRange.date_to if self.query.dateRange else None)
@classmethod
- def parse_relative_date_from(cls, date: str | None) -> datetime.datetime:
+ def parse_relative_date_from(cls, date: str | None, timezone_info: ZoneInfo) -> datetime.datetime:
if date == "all" or date is None:
return datetime.datetime.now(tz=ZoneInfo("UTC")) - datetime.timedelta(days=7)
- return relative_date_parse(date, now=datetime.datetime.now(tz=ZoneInfo("UTC")), timezone_info=ZoneInfo("UTC"))
+ return relative_date_parse(
+ date, now=datetime.datetime.now(tz=ZoneInfo("UTC")), timezone_info=timezone_info, always_truncate=True
+ )
@classmethod
def parse_relative_date_to(cls, date: str | None) -> datetime.datetime:
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
index cd283f3274d3..43e1dc7cc130 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
@@ -53,7 +53,7 @@ class ErrorTrackingQueryRunner(ErrorTrackingQueryRunnerAccessMixin, AnalyticsQue
)
self.date_to = ErrorTrackingQueryRunner.parse_relative_date_to(self.query.dateRange.date_to)
self.date_from = ErrorTrackingQueryRunner.parse_relative_date_from(
- self.query.dateRange.date_from, default_end=self.date_to
+ self.query.dateRange.date_from, self.team.timezone_info, default_end=self.date_to
)
if self.query.withAggregations is None:
@@ -87,7 +87,7 @@ class ErrorTrackingQueryRunner(ErrorTrackingQueryRunnerAccessMixin, AnalyticsQue
@classmethod
def parse_relative_date_from(
- cls, date: str | None, default_end: datetime.datetime | None = None
+ cls, date: str | None, timezone_info: ZoneInfo, default_end: datetime.datetime | None = None
) -> datetime.datetime:
if date == "all":
return datetime.datetime.now(tz=ZoneInfo("UTC")) - datetime.timedelta(days=365 * 4)
@@ -95,7 +95,9 @@ class ErrorTrackingQueryRunner(ErrorTrackingQueryRunnerAccessMixin, AnalyticsQue
# A missing date_from must not silently mean "all time" — that's a 4-year events
# scan. Anchor the default window to the range end so date_to-only queries stay valid.
return (default_end or datetime.datetime.now(tz=ZoneInfo("UTC"))) - datetime.timedelta(days=7)
- return relative_date_parse(date, now=datetime.datetime.now(tz=ZoneInfo("UTC")), timezone_info=ZoneInfo("UTC"))
+ return relative_date_parse(
+ date, now=datetime.datetime.now(tz=ZoneInfo("UTC")), timezone_info=timezone_info, always_truncate=True
+ )
@classmethod
def parse_relative_date_to(cls, date: str | None) -> datetime.datetime:
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_releases_query_runner.py b/products/error_tracking/backend/hogql_queries/error_tracking_releases_query_runner.py
index ad34f04cd80f..391bcec5d513 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_releases_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_releases_query_runner.py
@@ -72,7 +72,9 @@ class ErrorTrackingReleasesQueryRunner(
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.query.issueId = validate_uuid_param(self.query.issueId, "issueId")
- self.date_from = self.parse_relative_date_from(self.query.dateRange.date_from if self.query.dateRange else None)
+ self.date_from = self.parse_relative_date_from(
+ self.query.dateRange.date_from if self.query.dateRange else None, self.team.timezone_info
+ )
self.date_to = self.parse_relative_date_to(self.query.dateRange.date_to if self.query.dateRange else None)
resolution = min(MAX_RESOLUTION, max(1, self.query.resolution or DEFAULT_RESOLUTION))
total_seconds = max(1, int((self.date_to - self.date_from).total_seconds()))
@@ -83,10 +85,12 @@ class ErrorTrackingReleasesQueryRunner(
self.bucket_starts = [aligned_from]
@classmethod
- def parse_relative_date_from(cls, date: str | None) -> datetime.datetime:
+ def parse_relative_date_from(cls, date: str | None, timezone_info: ZoneInfo) -> datetime.datetime:
if date == "all" or date is None:
return datetime.datetime.now(tz=ZoneInfo("UTC")) - datetime.timedelta(days=7)
- return relative_date_parse(date, now=datetime.datetime.now(tz=ZoneInfo("UTC")), timezone_info=ZoneInfo("UTC"))
+ return relative_date_parse(
+ date, now=datetime.datetime.now(tz=ZoneInfo("UTC")), timezone_info=timezone_info, always_truncate=True
+ )
@classmethod
def parse_relative_date_to(cls, date: str | None) -> datetime.datetime:
diff --git a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_breakdowns_query_runner.ambr b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_breakdowns_query_runner.ambr
index 330358846ec7..dc3695cc9f09 100644
--- a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_breakdowns_query_runner.ambr
+++ b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_breakdowns_query_runner.ambr
@@ -30,7 +30,7 @@
WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)
GROUP BY fp_hash
HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$exception_fingerprint'), ''), 'null'), '^"|"$', '')), events__fingerprint_issue_state.fp_hash)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 12:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(events__fingerprint_issue_state.issue_id, '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(events__fingerprint_issue_state.issue_id, '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))
GROUP BY breakdown_property,
breakdown_value))
WHERE lessOrEquals(row_number, 3)
@@ -81,7 +81,7 @@
WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)
GROUP BY fp_hash
HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$exception_fingerprint'), ''), 'null'), '^"|"$', '')), events__fingerprint_issue_state.fp_hash)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 12:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(events__fingerprint_issue_state.issue_id, '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(events__fingerprint_issue_state.issue_id, '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))
GROUP BY breakdown_property,
breakdown_value))
WHERE lessOrEquals(row_number, 3)
@@ -132,7 +132,7 @@
WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)
GROUP BY fp_hash
HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$exception_fingerprint'), ''), 'null'), '^"|"$', '')), events__fingerprint_issue_state.fp_hash)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 12:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(events__fingerprint_issue_state.issue_id, '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(events__fingerprint_issue_state.issue_id, '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))
GROUP BY breakdown_property,
breakdown_value))
WHERE lessOrEquals(row_number, 3)
@@ -183,7 +183,7 @@
WHERE equals(error_tracking_fingerprint_issue_state.team_id, 99999)
GROUP BY fp_hash
HAVING equals(argMax(error_tracking_fingerprint_issue_state.is_deleted, error_tracking_fingerprint_issue_state.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__fingerprint_issue_state ON equals(cityHash64(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$exception_fingerprint'), ''), 'null'), '^"|"$', '')), events__fingerprint_issue_state.fp_hash)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 12:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(events__fingerprint_issue_state.issue_id, '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64('2024-01-03 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.event, '$exception'), ifNull(equals(events__fingerprint_issue_state.issue_id, '01936e7f-d7ff-7314-b2d4-7627981e34f0'), 0))))
GROUP BY breakdown_property,
breakdown_value))
WHERE lessOrEquals(row_number, 3)
diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
index a45db22057e2..e879d7574bba 100644
--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
@@ -353,10 +353,15 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
@freeze_time("2022-01-10T12:11:00")
def test_date_range_resolution(self):
- date_from = ErrorTrackingQueryRunner.parse_relative_date_from("-1d")
+ date_from = ErrorTrackingQueryRunner.parse_relative_date_from("-1d", self.team.timezone_info)
date_to = ErrorTrackingQueryRunner.parse_relative_date_to("+1d")
- self.assertEqual(date_from, datetime(2022, 1, 9, 12, 11, 0, tzinfo=ZoneInfo(key="UTC")))
+ self.assertEqual(date_from, datetime(2022, 1, 9, 0, 0, 0, tzinfo=ZoneInfo(key="UTC")))
self.assertEqual(date_to, datetime(2022, 1, 11, 12, 11, 0, tzinfo=ZoneInfo(key="UTC")))
+ # Day ranges snap to midnight in the project timezone, not UTC.
+ self.assertEqual(
+ ErrorTrackingQueryRunner.parse_relative_date_from("-1d", ZoneInfo("America/Los_Angeles")),
+ datetime(2022, 1, 9, 0, 0, 0, tzinfo=ZoneInfo("America/Los_Angeles")),
+ )
def test_event_fetching_defaults_off(self):
runner = ErrorTrackingQueryRunner(
@@ -421,7 +426,7 @@ class TestErrorTrackingQueryRunner(ClickhouseTestMixin, NonAtomicBaseTestKeepIde
@freeze_time("2022-01-10T12:11:00")
def test_missing_date_from_defaults_to_seven_days(self):
# A missing date_from must default to a bounded 7-day window, not all-time.
- date_from = ErrorTrackingQueryRunner.parse_relative_date_from(None)
+ date_from = ErrorTrackingQueryRunner.parse_relative_date_from(None, self.team.timezone_info)
self.assertEqual(date_from, datetime(2022, 1, 3, 12, 11, 0, tzinfo=ZoneInfo(key="UTC")))
@freeze_time("2022-01-10T12:11:00")
diff --git a/products/error_tracking/frontend/ErrorTracking.stories.tsx b/products/error_tracking/frontend/ErrorTracking.stories.tsx
index c61f2d2ffd86..2d485aaf85ab 100644
--- a/products/error_tracking/frontend/ErrorTracking.stories.tsx
+++ b/products/error_tracking/frontend/ErrorTracking.stories.tsx
@@ -506,6 +506,75 @@ export default meta
type Story = StoryObj<{}>
export const ListPage: Story = {}
+// The eight day buckets the insights tab spans under the story's mocked date and default range.
+const STORY_INSIGHTS_BUCKETS = [
+ '2024-07-02 00:00:00',
+ '2024-07-03 00:00:00',
+ '2024-07-04 00:00:00',
+ '2024-07-05 00:00:00',
+ '2024-07-06 00:00:00',
+ '2024-07-07 00:00:00',
+ '2024-07-08 00:00:00',
+ '2024-07-09 00:00:00',
+]
+
+// exceptions, affected users, sessions, sessions with a crash, releases — per bucket.
+const STORY_INSIGHTS_SERIES: number[][] = [
+ [26, 14, 168, 9, 2],
+ [22, 12, 174, 8, 2],
+ [19, 11, 181, 7, 2],
+ [24, 13, 176, 9, 3],
+ [17, 9, 188, 6, 3],
+ [15, 8, 192, 5, 3],
+ [18, 10, 179, 6, 3],
+ [16, 9, 182, 6, 3],
+]
+
+const STORY_INSIGHTS_RELEASES: [string, string, string, [string, number][]][] = [
+ [
+ 'web',
+ '2.4.0',
+ '',
+ [
+ ['2024-07-05 00:00:00', 9],
+ ['2024-07-06 00:00:00', 11],
+ ['2024-07-07 00:00:00', 13],
+ ['2024-07-08 00:00:00', 14],
+ ['2024-07-09 00:00:00', 12],
+ ],
+ ],
+ [
+ 'web',
+ '2.3.1',
+ '',
+ [
+ ['2024-07-02 00:00:00', 18],
+ ['2024-07-03 00:00:00', 15],
+ ['2024-07-04 00:00:00', 12],
+ ['2024-07-05 00:00:00', 10],
+ ],
+ ],
+ [
+ 'ios',
+ '4.1',
+ '881',
+ [
+ ['2024-07-03 00:00:00', 5],
+ ['2024-07-04 00:00:00', 5],
+ ['2024-07-06 00:00:00', 4],
+ ],
+ ],
+ [
+ '',
+ '',
+ '',
+ [
+ ['2024-07-02 00:00:00', 8],
+ ['2024-07-07 00:00:00', 5],
+ ],
+ ],
+]
+
export const InsightsPage: Story = {
parameters: { pageUrl: urls.errorTracking({ activeTab: 'insights' }) },
decorators: [
@@ -515,12 +584,30 @@ export const InsightsPage: Story = {
const body = (await request.json()) as {
query?: {
kind?: string
+ query?: string
series?: { custom_name?: string }[]
trendsFilter?: { formulaNodes?: { custom_name?: string }[] }
}
}
if (body.query?.kind === NodeKind.HogQLQuery) {
- return [200, { results: [[157, 76, 1240, 42]] }]
+ const hogql = body.query.query ?? ''
+ // The three HogQL queries behind the tab return different shapes, so the mock
+ // keys off a phrase unique to each rather than answering them all alike.
+ if (hogql.includes('previous_exceptions')) {
+ return [200, { results: [[157, 186, 76, 71, 1240, 1190, 42, 51, 3, 2]] }]
+ }
+ if (hogql.includes('groupArray')) {
+ return [200, { results: STORY_INSIGHTS_RELEASES }]
+ }
+ return [
+ 200,
+ {
+ results: STORY_INSIGHTS_BUCKETS.map((bucket, index) => [
+ bucket,
+ ...STORY_INSIGHTS_SERIES[index],
+ ]),
+ },
+ ]
}
const label =
body.query?.trendsFilter?.formulaNodes?.[0]?.custom_name ??
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ChartCard.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ChartCard.tsx
index e174a82b481e..5f1776f19f9d 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ChartCard.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ChartCard.tsx
@@ -7,6 +7,7 @@ import { Query } from '~/queries/Query/Query'
import { InsightVizNode, TrendsQuery } from '~/queries/schema/schema-general'
import { InsightLogicProps } from '~/types'
+import { InsightsCard } from './InsightsCard'
import { insightNewUrl } from './queries'
export function ChartCard({
@@ -27,12 +28,11 @@ export function ChartCard({
}
return (
- <div className="h-100 flex flex-col rounded-md border bg-surface-primary">
- <div className="flex shrink-0 items-center justify-between p-4 pb-2">
- <div>
- <h3 className="font-semibold text-sm m-0">{title}</h3>
- <p className="text-xs text-secondary m-0">{description}</p>
- </div>
+ <InsightsCard
+ title={title}
+ description={description}
+ className="h-100"
+ action={
<Tooltip>
<TooltipTrigger
render={
@@ -49,8 +49,9 @@ export function ChartCard({
</TooltipTrigger>
<TooltipContent>Open as insight</TooltipContent>
</Tooltip>
- </div>
- <div className="ErrorTracking__insights min-h-0 flex-1 px-4 pt-2 pb-4">
+ }
+ >
+ <div className="ErrorTracking__insights min-h-0 flex-1">
<Query
query={query}
readOnly={true}
@@ -58,6 +59,6 @@ export function ChartCard({
inSharedMode={true}
/>
</div>
- </div>
+ </InsightsCard>
)
}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ErrorTrackingInsights.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ErrorTrackingInsights.tsx
index 2151674e96c4..acf8ce1fc2d3 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ErrorTrackingInsights.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ErrorTrackingInsights.tsx
@@ -1,50 +1,89 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner } from '@posthog/lemon-ui'
import { SceneStickyBar } from '~/layout/scenes/components/SceneStickyBar'
import { ChartCard } from './ChartCard'
import { errorTrackingInsightsLogic } from './errorTrackingInsightsLogic'
import { InsightsFilters } from './InsightsFilters'
-import { SummaryStats } from './SummaryStats'
+import { MetricTiles } from './MetricTiles'
+import { ReleaseBreakdownCards } from './ReleaseBreakdownCards'
+
+function InsightsSection({ title, children }: { title: string; children: React.ReactNode }): JSX.Element {
+ return (
+ <section>
+ <h2 className="mb-4 text-xl font-semibold text-primary">{title}</h2>
+ {children}
+ </section>
+ )
+}
export function ErrorTrackingInsights(): JSX.Element {
- const { exceptionVolumeQuery, issuesCreatedQuery, affectedUsersQuery, crashFreeSessionsQuery } =
- useValues(errorTrackingInsightsLogic)
+ const {
+ exceptionVolumeQuery,
+ issuesCreatedQuery,
+ affectedUsersQuery,
+ crashFreeSessionsQuery,
+ metrics,
+ metricsLoading,
+ incompleteTail,
+ loadFailed,
+ } = useValues(errorTrackingInsightsLogic)
+ const { loadInsights } = useActions(errorTrackingInsightsLogic)
return (
<div>
<SceneStickyBar className="-mt-4" showBorderBottom={false}>
<InsightsFilters />
</SceneStickyBar>
- <div className="space-y-4">
- <SummaryStats />
-
- <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
- <ChartCard
- title="Exception volume"
- description="Exceptions per day"
- query={exceptionVolumeQuery}
- chartKey="exception_volume"
- />
- <ChartCard
- title="Issues created"
- description="New issues per day"
- query={issuesCreatedQuery}
- chartKey="issues_created"
- />
- <ChartCard
- title="Affected users"
- description="Unique users experiencing exceptions"
- query={affectedUsersQuery}
- chartKey="affected_users"
- />
- <ChartCard
- title="Crash-free sessions"
- description="Percentage of sessions without any exceptions"
- query={crashFreeSessionsQuery}
- chartKey="crash_free_sessions"
- />
- </div>
+ <div className="flex flex-col gap-4">
+ {loadFailed && (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: () => loadInsights() }}>
+ Couldn't load these insights. The numbers below may be out of date.
+ </LemonBanner>
+ )}
+ <InsightsSection title="Key metrics">
+ <MetricTiles metrics={metrics} loading={metricsLoading} incompleteTail={incompleteTail} />
+ </InsightsSection>
+
+ <InsightsSection title="Trends">
+ {/* Two charts side by side need real width, and the nav sidebar plus an open side
+ panel take most of a laptop window. Break on the tab's own width, not the
+ viewport's, so the pair stacks whenever the space actually ran out. */}
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-4 @4xl:grid-cols-2">
+ <ChartCard
+ title="Exception volume"
+ description="Exceptions over time"
+ query={exceptionVolumeQuery}
+ chartKey="exception_volume"
+ />
+ <ChartCard
+ title="Issues created"
+ description="Issues seen for the first time"
+ query={issuesCreatedQuery}
+ chartKey="issues_created"
+ />
+ <ChartCard
+ title="Affected users"
+ description="Unique users experiencing exceptions"
+ query={affectedUsersQuery}
+ chartKey="affected_users"
+ />
+ <ChartCard
+ title="Crash-free sessions"
+ description="Percentage of sessions without any exceptions"
+ query={crashFreeSessionsQuery}
+ chartKey="crash_free_sessions"
+ />
+ </div>
+ </div>
+ </InsightsSection>
+
+ <InsightsSection title="Releases">
+ <ReleaseBreakdownCards />
+ </InsightsSection>
</div>
</div>
)
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBandChart.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBandChart.tsx
new file mode 100644
index 000000000000..f660b86f94e9
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBandChart.tsx
@@ -0,0 +1,106 @@
+import { useMemo } from 'react'
+
+import { DefaultTooltip, TimeSeriesBarChart, type TimeSeriesBarChartConfig } from '@posthog/quill-charts'
+import type { ChartTheme, PointClickData, Series } from '@posthog/quill-charts'
+
+import { useChartConfig } from 'lib/charts/hooks'
+import { Skeleton } from 'lib/ui/quill'
+import { formatBucketLabel } from 'lib/utils/timeBuckets'
+
+import { IntervalType } from '~/types'
+
+import { BandFilter, ExceptionBand } from './releaseBreakdown'
+
+const CHART_HEIGHT = 'h-[260px]'
+
+export function ExceptionBandChart({
+ bands,
+ labels,
+ loading,
+ theme,
+ timezone,
+ interval,
+ incompleteTail,
+ onSelectBand,
+}: {
+ bands: ExceptionBand[]
+ /** Bucket keys the bands' counts are aligned to. */
+ labels: string[]
+ loading: boolean
+ theme: ChartTheme
+ timezone: string
+ interval: IntervalType
+ // When true, the final bucket is the interval still in progress. Required rather than optional:
+ // an omitted prop silently draws a partial period as a settled drop in volume.
+ incompleteTail: boolean
+ onSelectBand: (filters: BandFilter[]) => void
+}): JSX.Element {
+ const series = useMemo<Series<ExceptionBand>[]>(
+ () =>
+ bands.map((band) => ({
+ key: band.key,
+ label: band.label,
+ color: band.color,
+ data: band.counts,
+ meta: band,
+ // A bar cannot carry the dashed treatment the tiles' sparklines use, so hatch the
+ // in-progress bucket instead. Without it a period a few hours old reads as a drop.
+ bars: incompleteTail
+ ? band.counts.map((_, index) => ({ hatch: index === band.counts.length - 1 }))
+ : undefined,
+ })),
+ [bands, incompleteTail]
+ )
+ const config = useChartConfig<TimeSeriesBarChartConfig>(
+ () => ({
+ barLayout: 'stacked',
+ barCornerRadius: 4,
+ showAxisLines: true,
+ showTickMarks: true,
+ showCrosshair: true,
+ showGrid: true,
+ xAxis: { interval, timezone },
+ tooltip: { placement: 'cursor' },
+ }),
+ [timezone, interval]
+ )
+
+ const onPointClick = ({ series: clicked }: PointClickData<ExceptionBand>): void => {
+ if (clicked.meta?.filters) {
+ onSelectBand(clicked.meta.filters)
+ }
+ }
+
+ if (loading) {
+ return <Skeleton className={`w-full ${CHART_HEIGHT}`} />
+ }
+ if (bands.length === 0) {
+ return (
+ <div className="py-6 text-center text-xs text-secondary">
+ No exceptions in this period, so there is nothing to break down.
+ </div>
+ )
+ }
+ return (
+ <div className={`flex flex-col ${CHART_HEIGHT}`}>
+ <TimeSeriesBarChart
+ series={series}
+ labels={labels}
+ config={config}
+ theme={theme}
+ onPointClick={onPointClick}
+ dataAttr="error-tracking-insights-breakdown"
+ tooltip={(context) => (
+ <DefaultTooltip
+ {...context}
+ hideZeroRows
+ sortedByValue
+ showTotal
+ labelFormatter={(label) => formatBucketLabel(label, interval)}
+ valueFormatter={(value) => `${value} ${value === 1 ? 'exception' : 'exceptions'}`}
+ />
+ )}
+ />
+ </div>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBandTable.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBandTable.tsx
new file mode 100644
index 000000000000..bab26ecb25ba
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBandTable.tsx
@@ -0,0 +1,134 @@
+import {
+ Button,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableEmpty,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Text,
+} from 'lib/ui/quill'
+import { humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import { BandFilter, ExceptionBand } from './releaseBreakdown'
+
+const COLUMN_COUNT = 3
+
+function formatShare(share: number): string {
+ if (share > 0 && share < 0.5) {
+ return '<1%'
+ }
+ return `${Math.round(share)}%`
+}
+
+function BandLabel({
+ band,
+ onSelectBand,
+}: {
+ band: ExceptionBand
+ onSelectBand: (filters: BandFilter[]) => void
+}): JSX.Element {
+ const swatch = (
+ // eslint-disable-next-line react/forbid-dom-props
+ <span aria-hidden className="size-2 shrink-0 rounded-full" style={{ backgroundColor: band.color }} />
+ )
+ if (!band.filters) {
+ return (
+ <div className="flex min-w-0 items-center gap-1.5">
+ {swatch}
+ <Text size="xs" variant="muted" className="truncate">
+ {band.label}
+ </Text>
+ </div>
+ )
+ }
+ return (
+ <Button
+ variant="default"
+ size="sm"
+ className="h-6 w-full min-w-0 justify-start gap-1.5 px-1.5 text-xs"
+ data-attr="error-tracking-insights-band-filter"
+ tooltip="Filter this tab down to it"
+ onClick={() => onSelectBand(band.filters as BandFilter[])}
+ >
+ {swatch}
+ <span className="truncate">{band.label}</span>
+ </Button>
+ )
+}
+
+function BandRows({
+ bands,
+ loading,
+ onSelectBand,
+}: {
+ bands: ExceptionBand[]
+ loading: boolean
+ onSelectBand: (filters: BandFilter[]) => void
+}): JSX.Element {
+ if (loading) {
+ return (
+ <TableBody>
+ <TableRow>
+ <TableCell colSpan={COLUMN_COUNT}>
+ <div className="space-y-2 py-1">
+ {Array.from({ length: 4 }).map((_, index) => (
+ <Skeleton key={index} className="h-3.5 w-full" />
+ ))}
+ </div>
+ </TableCell>
+ </TableRow>
+ </TableBody>
+ )
+ }
+ if (bands.length === 0) {
+ return <TableEmpty className="py-6 text-secondary">No exceptions in this period.</TableEmpty>
+ }
+ return (
+ <TableBody>
+ {bands.map((band) => (
+ <TableRow key={band.key}>
+ <TableCell expand>
+ <BandLabel band={band} onSelectBand={onSelectBand} />
+ </TableCell>
+ <TableCell align="right" className="tabular-nums">
+ {humanFriendlyLargeNumber(band.total)}
+ </TableCell>
+ <TableCell align="right" className="tabular-nums text-secondary">
+ {formatShare(band.share)}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ )
+}
+
+export function ExceptionBandTable({
+ bands,
+ loading,
+ columnLabel,
+ onSelectBand,
+}: {
+ bands: ExceptionBand[]
+ loading: boolean
+ /** Header of the first column, naming what the rows are split by. */
+ columnLabel: string
+ onSelectBand: (filters: BandFilter[]) => void
+}): JSX.Element {
+ return (
+ <div className="overflow-x-auto">
+ <Table fullWidth>
+ <TableHeader>
+ <TableRow>
+ <TableHead expand>{columnLabel}</TableHead>
+ <TableHead align="right">Exceptions</TableHead>
+ <TableHead align="right">Share</TableHead>
+ </TableRow>
+ </TableHeader>
+ <BandRows bands={bands} loading={loading} onSelectBand={onSelectBand} />
+ </Table>
+ </div>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBreakdownCard.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBreakdownCard.tsx
new file mode 100644
index 000000000000..a0b9d713978b
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ExceptionBreakdownCard.tsx
@@ -0,0 +1,75 @@
+import { type ChartTheme } from '@posthog/quill-charts'
+
+import { Text } from 'lib/ui/quill'
+
+import { IntervalType } from '~/types'
+
+import { formatReleaseCount } from 'products/error_tracking/frontend/components/IssueReleases/issueReleases'
+
+import { ExceptionBandChart } from './ExceptionBandChart'
+import { ExceptionBandTable } from './ExceptionBandTable'
+import { InsightsCard } from './InsightsCard'
+import { BandFilter, ExceptionBreakdown } from './releaseBreakdown'
+
+/** One panel of the releases section: exception volume over time, split by one property, plus the
+ * same split as a table. The chart and the table read the same bands, so the colors and the order
+ * they show cannot drift apart. */
+export function ExceptionBreakdownCard({
+ title,
+ breakdown,
+ countNoun,
+ columnLabel,
+ labels,
+ loading,
+ theme,
+ timezone,
+ interval,
+ incompleteTail,
+ onSelectBand,
+}: {
+ title: string
+ breakdown: ExceptionBreakdown
+ /** Singular noun for the header count, e.g. "release" reads as "3 releases". */
+ countNoun: string
+ columnLabel: string
+ /** Bucket keys the bands' counts are aligned to. */
+ labels: string[]
+ loading: boolean
+ theme: ChartTheme
+ timezone: string
+ interval: IntervalType
+ incompleteTail: boolean
+ onSelectBand: (filters: BandFilter[]) => void
+}): JSX.Element {
+ return (
+ <InsightsCard
+ title={title}
+ description="Select a value to filter the whole tab down to it"
+ action={
+ loading ? null : (
+ <Text size="xs" variant="muted">
+ {formatReleaseCount(breakdown.groupCount, countNoun, breakdown.groupCountTruncated)}
+ </Text>
+ )
+ }
+ contentClassName="gap-4"
+ >
+ <ExceptionBandChart
+ bands={breakdown.bands}
+ labels={labels}
+ loading={loading}
+ theme={theme}
+ timezone={timezone}
+ interval={interval}
+ incompleteTail={incompleteTail}
+ onSelectBand={onSelectBand}
+ />
+ <ExceptionBandTable
+ bands={breakdown.bands}
+ loading={loading}
+ columnLabel={columnLabel}
+ onSelectBand={onSelectBand}
+ />
+ </InsightsCard>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/InsightsCard.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/InsightsCard.tsx
new file mode 100644
index 000000000000..ba64df324899
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/InsightsCard.tsx
@@ -0,0 +1,42 @@
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from 'lib/ui/quill'
+import { cn } from 'lib/utils/css-classes'
+
+/** The card every panel on the insights tab sits in, so the tab reads as one grid of panels. */
+export function InsightsCard({
+ title,
+ description,
+ action,
+ children,
+ className,
+ contentClassName,
+}: {
+ title: string
+ description?: string
+ /** Rendered in the header's top-right corner, for a single control such as a link out. */
+ action?: React.ReactNode
+ children: React.ReactNode
+ className?: string
+ contentClassName?: string
+}): JSX.Element {
+ return (
+ <Card size="sm" className={cn('min-w-0', className)}>
+ {/* The header's own layout is a grid built around quill's card-action slot, which this app's
+ quill build does not export. Switching it to flex puts the action beside the title
+ without reaching for the slot's markup. */}
+ <CardHeader className="flex flex-row items-start justify-between gap-2">
+ <div className="flex min-w-0 flex-col gap-1">
+ {/* quill renders CardTitle as a plain div, so the panel titles carry no heading
+ semantics on their own. The role restores them without forking the primitive
+ or restating its typography on an inner element. */}
+ <CardTitle role="heading" aria-level={3}>
+ {title}
+ </CardTitle>
+ {description ? <CardDescription>{description}</CardDescription> : null}
+ </div>
+ {action ? <div className="shrink-0">{action}</div> : null}
+ </CardHeader>
+ {/* min-h-0 lets a height-constrained card's content shrink instead of overflowing the card's clip. */}
+ <CardContent className={cn('flex min-h-0 flex-1 flex-col', contentClassName)}>{children}</CardContent>
+ </Card>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/InsightsPanels.stories.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/InsightsPanels.stories.tsx
new file mode 100644
index 000000000000..e0fb3ba6b054
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/InsightsPanels.stories.tsx
@@ -0,0 +1,220 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { type ChartTheme } from '@posthog/quill-charts'
+
+import { buildTheme } from 'lib/charts/utils/theme'
+
+import { ExceptionBandChart } from './ExceptionBandChart'
+import { ExceptionBandTable } from './ExceptionBandTable'
+import { InsightMetric, InsightsMetrics } from './insightsMetrics'
+import { MetricTiles } from './MetricTiles'
+import { buildAppBreakdown, buildReleaseBreakdown, parseReleaseRows } from './releaseBreakdown'
+
+const BUCKETS = [
+ '2026-06-01 00:00:00',
+ '2026-06-02 00:00:00',
+ '2026-06-03 00:00:00',
+ '2026-06-04 00:00:00',
+ '2026-06-05 00:00:00',
+ '2026-06-06 00:00:00',
+ '2026-06-07 00:00:00',
+]
+const LABELS = ['Jun 1', 'Jun 2', 'Jun 3', 'Jun 4', 'Jun 5', 'Jun 6', 'Jun 7']
+
+function metric(
+ value: number,
+ previousValue: number,
+ sparkline: number[],
+ goodDirection: 'up' | 'down'
+): InsightMetric {
+ return {
+ value,
+ previousValue,
+ deltaPct: previousValue ? ((value - previousValue) / previousValue) * 100 : null,
+ sparkline,
+ sparklineLabels: LABELS,
+ goodDirection,
+ }
+}
+
+const METRICS: InsightsMetrics = {
+ exceptions: metric(18420, 21030, [2900, 2740, 2610, 2580, 2490, 2380, 2720], 'down'),
+ affectedUsers: metric(1840, 1655, [280, 265, 250, 244, 238, 231, 332], 'down'),
+ sessions: metric(96200, 88400, [13100, 13500, 13800, 13600, 14100, 14000, 14100], 'up'),
+ crashSessions: metric(4210, 5120, [640, 620, 600, 590, 580, 570, 610], 'down'),
+ crashFreeRate: metric(95.6, 94.2, [95.1, 95.4, 95.7, 95.7, 95.9, 95.9, 95.7], 'up'),
+ releases: metric(4, 2, [2, 2, 3, 3, 4, 4, 4], 'up'),
+}
+
+// A window that ends mid-period: the last bucket's counts sit far below its neighbours because the
+// interval has not finished. Both stories exist to show that reads as in-progress, not as a drop.
+const PARTIAL_TAIL: InsightsMetrics = {
+ ...METRICS,
+ exceptions: metric(15980, 21030, [2900, 2740, 2610, 2580, 2490, 2380, 280], 'down'),
+}
+
+const RELEASE_ROWS = parseReleaseRows(
+ [
+ [
+ 'web',
+ '2.4.0',
+ '',
+ [
+ ['2026-06-05 00:00:00', 420],
+ ['2026-06-06 00:00:00', 980],
+ ['2026-06-07 00:00:00', 1240],
+ ],
+ ],
+ [
+ 'web',
+ '2.3.1',
+ '',
+ [
+ ['2026-06-01 00:00:00', 1900],
+ ['2026-06-02 00:00:00', 1780],
+ ['2026-06-03 00:00:00', 1710],
+ ['2026-06-04 00:00:00', 1650],
+ ['2026-06-05 00:00:00', 900],
+ ],
+ ],
+ [
+ 'ios',
+ '4.1',
+ '881',
+ [
+ ['2026-06-02 00:00:00', 320],
+ ['2026-06-03 00:00:00', 300],
+ ['2026-06-04 00:00:00', 280],
+ ],
+ ],
+ ['web', '2.3.0', '', [['2026-06-01 00:00:00', 210]]],
+ [
+ '',
+ '',
+ '',
+ [
+ ['2026-06-01 00:00:00', 90],
+ ['2026-06-06 00:00:00', 120],
+ ],
+ ],
+ ],
+ BUCKETS
+)
+
+const BREAKDOWN = buildReleaseBreakdown(RELEASE_ROWS, BUCKETS, buildTheme().colors)
+const APP_BREAKDOWN = buildAppBreakdown(RELEASE_ROWS, BUCKETS, buildTheme().colors)
+
+const meta: Meta = {
+ title: 'Scenes-App/Error Tracking/Insights Panels',
+ parameters: { layout: 'padded' },
+}
+export default meta
+
+type Story = StoryObj
+
+function withTheme(render: (theme: ChartTheme) => JSX.Element): () => JSX.Element {
+ // Charts size themselves from their container via ResizeObserver, so the wrapper needs a definite
+ // width. Without one the card collapses in the shrink-to-fit snapshot runtime.
+ return () => <div className="w-[860px]">{render(buildTheme())}</div>
+}
+
+export const KeyMetrics: Story = {
+ render: () => (
+ <div className="w-[960px]">
+ <MetricTiles metrics={METRICS} loading={false} incompleteTail={false} />
+ </div>
+ ),
+}
+
+export const KeyMetricsInProgressBucket: Story = {
+ render: () => (
+ <div className="w-[960px]">
+ <MetricTiles metrics={PARTIAL_TAIL} loading={false} incompleteTail />
+ </div>
+ ),
+}
+
+export const KeyMetricsNarrowScene: Story = {
+ render: () => (
+ <div className="w-[520px]">
+ <MetricTiles metrics={METRICS} loading={false} incompleteTail={false} />
+ </div>
+ ),
+}
+
+export const KeyMetricsLoading: Story = {
+ // The point of this story is the skeletons, and the test runner treats a LemonSkeleton as a loader
+ // it must see disappear before snapshotting. Tell it not to wait, or it times out on every run.
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+ render: () => (
+ <div className="w-[960px]">
+ <MetricTiles metrics={METRICS} loading incompleteTail={false} />
+ </div>
+ ),
+}
+
+export const ExceptionsByRelease: Story = {
+ render: withTheme((theme) => (
+ <ExceptionBandChart
+ bands={BREAKDOWN.bands}
+ labels={BUCKETS}
+ loading={false}
+ theme={theme}
+ timezone="UTC"
+ interval="day"
+ incompleteTail={false}
+ onSelectBand={() => {}}
+ />
+ )),
+}
+
+export const ExceptionsByApp: Story = {
+ render: withTheme((theme) => (
+ <ExceptionBandChart
+ bands={APP_BREAKDOWN.bands}
+ labels={BUCKETS}
+ loading={false}
+ theme={theme}
+ timezone="UTC"
+ interval="day"
+ incompleteTail={false}
+ onSelectBand={() => {}}
+ />
+ )),
+}
+
+export const ExceptionsByReleaseEmpty: Story = {
+ render: withTheme((theme) => (
+ <ExceptionBandChart
+ bands={[]}
+ labels={BUCKETS}
+ loading={false}
+ theme={theme}
+ timezone="UTC"
+ interval="day"
+ incompleteTail={false}
+ onSelectBand={() => {}}
+ />
+ )),
+}
+
+export const ReleaseList: Story = {
+ render: withTheme(() => (
+ <ExceptionBandTable bands={BREAKDOWN.bands} loading={false} columnLabel="Release" onSelectBand={() => {}} />
+ )),
+}
+
+export const ExceptionsByReleaseInProgressBucket: Story = {
+ render: withTheme((theme) => (
+ <ExceptionBandChart
+ bands={BREAKDOWN.bands}
+ labels={BUCKETS}
+ loading={false}
+ theme={theme}
+ timezone="UTC"
+ interval="day"
+ incompleteTail
+ onSelectBand={() => {}}
+ />
+ )),
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/MetricTiles.scss b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/MetricTiles.scss
new file mode 100644
index 000000000000..1eb97a24d563
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/MetricTiles.scss
@@ -0,0 +1,7 @@
+// Cuts the loading tile's shimmer block into the silhouette of a rising area chart, so the
+// placeholder reads as "a chart is coming" rather than as a grey slab. Tailwind cannot express a
+// polygon clip path, and the point list is long enough that an arbitrary-value class would be
+// unreadable.
+.MetricTiles__chart-skeleton {
+ clip-path: polygon(0% 100%, 0% 74%, 14% 62%, 28% 68%, 42% 46%, 57% 54%, 71% 32%, 85% 40%, 100% 20%, 100% 100%);
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/MetricTiles.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/MetricTiles.tsx
new file mode 100644
index 000000000000..f6316dd805aa
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/MetricTiles.tsx
@@ -0,0 +1,201 @@
+import './MetricTiles.scss'
+
+import { LemonSkeleton } from '@posthog/lemon-ui'
+import { type ChartTheme } from '@posthog/quill-charts'
+import {
+ Metric,
+ MetricDelta,
+ MetricHeader,
+ MetricSparkline,
+ MetricSubtitle,
+ MetricTitle,
+ MetricValue,
+} from '@posthog/quill-components/metric'
+
+import { useChartTheme } from 'lib/charts/hooks'
+import { Card } from 'lib/ui/quill'
+import { formatPercentage, humanFriendlyLargeNumber } from 'lib/utils/numbers'
+
+import { InsightMetric, InsightsMetrics } from './insightsMetrics'
+
+const SPARKLINE_HEIGHT = 50
+// The same height as a class, for the placeholder standing in for the chart. Tailwind reads class
+// names out of the source, so it cannot be built from the constant: keep the two equal, or the tile
+// changes height the moment the data lands.
+const SPARKLINE_HEIGHT_CLASS = 'h-[50px]'
+
+// The tile's own layout, shared by the loaded and the loading state so the grid keeps one height
+// across the load. Metric owns these classes when it renders; the skeleton repeats them because it
+// stands in for the same boxes.
+const TILE_BODY_CLASS = 'flex h-full flex-col px-3 text-primary'
+const TILE_HEADER_CLASS = 'flex items-start justify-between gap-2'
+const TILE_TITLE_CLASS = 'text-sm font-medium'
+const TILE_SUBTITLE_CLASS = 'mt-1 text-sm opacity-60'
+const NO_VALUE = '-'
+
+/** A rate a hair under 100 must not render as a clean "100%" — that reads as "no crashes at all". */
+function formatRate(value: number): string {
+ return formatPercentage(Math.floor(value * 10) / 10, { precise: true, compact: true })
+}
+
+interface TileSpec {
+ label: string
+ metric: InsightMetric
+ format: (value: number) => string
+ color: string
+ /** Caption under the headline. On hover it yields to the hovered point's bucket label. */
+ subtitle: string
+}
+
+function MetricTile({
+ tile,
+ theme,
+ incompleteTail,
+}: {
+ tile: TileSpec
+ theme: ChartTheme
+ incompleteTail: boolean
+}): JSX.Element {
+ // The final bucket is the interval still in progress, so dash it. Without that a period only a few
+ // hours old reads as a collapse in exceptions rather than a period that has not finished.
+ const dashedFromIndex =
+ incompleteTail && tile.metric.sparkline.length >= 2 ? tile.metric.sparkline.length - 1 : undefined
+ const { value, previousValue, deltaPct } = tile.metric
+ // A zero delta is not a rise, so it gets no pill rather than the change badge's upward chevron.
+ const change = value !== null && deltaPct !== null && deltaPct !== 0 ? { value: deltaPct } : null
+
+ return (
+ <Card size="sm" flush className="flex-1">
+ <Metric
+ className={TILE_BODY_CLASS}
+ value={value ?? 0}
+ data={tile.metric.sparkline}
+ labels={tile.metric.sparklineLabels}
+ theme={theme}
+ color={tile.color}
+ goodDirection={tile.metric.goodDirection}
+ formatValue={value === null ? () => NO_VALUE : tile.format}
+ change={change}
+ changeTooltip={
+ change !== null && previousValue !== null
+ ? `vs. ${tile.format(previousValue)} in the previous period`
+ : undefined
+ }
+ hoverChangeFromPreviousPoint
+ restingSubtitle={tile.subtitle}
+ sparklineHeight={SPARKLINE_HEIGHT}
+ sparklineDashedFromIndex={dashedFromIndex}
+ >
+ <MetricHeader className={TILE_HEADER_CLASS}>
+ <MetricTitle className={TILE_TITLE_CLASS}>{tile.label}</MetricTitle>
+ <MetricDelta />
+ </MetricHeader>
+ <MetricValue className="mt-2 h-10" />
+ <MetricSubtitle className={TILE_SUBTITLE_CLASS} />
+ <MetricSparkline className="mt-3 -mx-3" />
+ </Metric>
+ </Card>
+ )
+}
+
+// The label is a fixed property of the tile rather than a query result, so it renders for real while
+// the numbers and the chart load.
+function LoadingTile({ tile }: { tile: TileSpec }): JSX.Element {
+ return (
+ <Card size="sm" flush className="flex-1">
+ <div className={TILE_BODY_CLASS}>
+ <div className={TILE_HEADER_CLASS}>
+ <div className={TILE_TITLE_CLASS}>{tile.label}</div>
+ {/* The change pill is 1rem tall against a 1.25rem title, so this can never be
+ what sets the header's height. */}
+ <LemonSkeleton className="h-4 w-12 rounded-full" />
+ </div>
+ <LemonSkeleton className="mt-2 h-10 w-24" />
+ {/* Hidden rather than dropped: the real caption still holds the box it will occupy,
+ so the tile keeps one height across the load without a second element having to
+ match its line height. */}
+ <div className={`${TILE_SUBTITLE_CLASS} invisible`}>{tile.subtitle}</div>
+ {/* `top-[6px]` mirrors MetricSparkline, which rests the line on the card's bottom edge. */}
+ <LemonSkeleton
+ className={`MetricTiles__chart-skeleton relative top-[6px] mt-3 -mx-3 rounded-none ${SPARKLINE_HEIGHT_CLASS}`}
+ />
+ </div>
+ </Card>
+ )
+}
+
+export function MetricTiles({
+ metrics,
+ loading,
+ incompleteTail,
+}: {
+ metrics: InsightsMetrics
+ loading: boolean
+ // When true, the last bucket is the interval still in progress. Required rather than optional: an
+ // omitted prop silently renders a partial period as settled data.
+ incompleteTail: boolean
+}): JSX.Element {
+ const theme = useChartTheme()
+
+ const tiles: TileSpec[] = [
+ {
+ label: 'Exceptions',
+ metric: metrics.exceptions,
+ format: humanFriendlyLargeNumber,
+ color: theme.colors[4],
+ subtitle: 'Total',
+ },
+ {
+ label: 'Affected users',
+ metric: metrics.affectedUsers,
+ format: humanFriendlyLargeNumber,
+ color: theme.colors[2],
+ subtitle: 'Total',
+ },
+ {
+ label: 'Sessions',
+ metric: metrics.sessions,
+ format: humanFriendlyLargeNumber,
+ color: theme.colors[0],
+ subtitle: 'Total',
+ },
+ {
+ label: 'Sessions with a crash',
+ metric: metrics.crashSessions,
+ format: humanFriendlyLargeNumber,
+ color: theme.colors[4],
+ subtitle: 'Total',
+ },
+ {
+ label: 'Crash-free sessions',
+ metric: metrics.crashFreeRate,
+ format: formatRate,
+ color: theme.colors[0],
+ subtitle: 'This period',
+ },
+ {
+ label: 'Releases',
+ metric: metrics.releases,
+ format: humanFriendlyLargeNumber,
+ color: theme.colors[6],
+ subtitle: 'Seen in this period',
+ },
+ ]
+
+ // Wrap the six tiles only into rows that divide evenly (6 → 3+3 → 2+2+2), never a lone trailing
+ // card. Container queries key off the card area's own width, so an open side panel cannot push it
+ // to an awkward 5+1 the way viewport breakpoints would.
+ return (
+ <div className="@container">
+ <div className="grid grid-cols-2 gap-3 @xl:grid-cols-3 @6xl:grid-cols-6">
+ {tiles.map((tile) =>
+ loading ? (
+ <LoadingTile key={tile.label} tile={tile} />
+ ) : (
+ <MetricTile key={tile.label} tile={tile} theme={theme} incompleteTail={incompleteTail} />
+ )
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ReleaseBreakdownCards.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ReleaseBreakdownCards.tsx
new file mode 100644
index 000000000000..101ca6d04dc6
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/ReleaseBreakdownCards.tsx
@@ -0,0 +1,62 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { useChartTheme } from 'lib/charts/hooks'
+
+import { errorTrackingInsightsLogic } from './errorTrackingInsightsLogic'
+import { ExceptionBreakdownCard } from './ExceptionBreakdownCard'
+import { buildAppBreakdown, buildReleaseBreakdown } from './releaseBreakdown'
+
+export function ReleaseBreakdownCards(): JSX.Element {
+ const { releaseRows, releaseRowsLoading, appRows, appRowsLoading, bucketKeys, interval, timezone, incompleteTail } =
+ useValues(errorTrackingInsightsLogic)
+ const { filterByBand } = useActions(errorTrackingInsightsLogic)
+ const theme = useChartTheme()
+
+ const releases = useMemo(
+ () => buildReleaseBreakdown(releaseRows, bucketKeys, theme.colors),
+ [releaseRows, bucketKeys, theme.colors]
+ )
+ // Folded from its own query rather than from the release rows: those are capped, so past the cap
+ // an app would lose the releases that were dropped and report a total short of its real one.
+ const apps = useMemo(
+ () => buildAppBreakdown(appRows, bucketKeys, theme.colors),
+ [appRows, bucketKeys, theme.colors]
+ )
+
+ // A chart and a table side by side need real width, and the nav sidebar plus an open side panel
+ // take most of a laptop window. Break on the section's own width so the pair stacks whenever the
+ // space actually ran out.
+ return (
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-4 @4xl:grid-cols-2">
+ <ExceptionBreakdownCard
+ title="Exceptions by release"
+ breakdown={releases}
+ countNoun="release"
+ columnLabel="Release"
+ labels={bucketKeys}
+ loading={releaseRowsLoading}
+ theme={theme}
+ timezone={timezone}
+ interval={interval}
+ incompleteTail={incompleteTail}
+ onSelectBand={filterByBand}
+ />
+ <ExceptionBreakdownCard
+ title="Exceptions by app"
+ breakdown={apps}
+ countNoun="app"
+ columnLabel="App"
+ labels={bucketKeys}
+ loading={appRowsLoading}
+ theme={theme}
+ timezone={timezone}
+ interval={interval}
+ incompleteTail={incompleteTail}
+ onSelectBand={filterByBand}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/SummaryStats.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/SummaryStats.tsx
deleted file mode 100644
index e7c8e23a051d..000000000000
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/SummaryStats.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { useValues } from 'kea'
-
-import { LemonSkeleton } from '@posthog/lemon-ui'
-
-import { compactNumber } from 'lib/utils/numbers'
-
-import { errorTrackingInsightsLogic } from './errorTrackingInsightsLogic'
-
-export function SummaryStats(): JSX.Element {
- const { summaryStats, summaryStatsLoading } = useValues(errorTrackingInsightsLogic)
-
- const cards = [
- { label: 'Total exceptions', value: summaryStats ? compactNumber(summaryStats.totalExceptions) : null },
- { label: 'Affected users', value: summaryStats ? compactNumber(summaryStats.affectedUsers) : null },
- { label: 'Total sessions', value: summaryStats ? compactNumber(summaryStats.totalSessions) : null },
- { label: 'Sessions with crash', value: summaryStats ? compactNumber(summaryStats.crashSessions) : null },
- { label: 'Crash-free sessions', value: summaryStats ? `${summaryStats.crashFreeRate}%` : null },
- ]
-
- return (
- <div className="grid grid-cols-2 gap-4 xl:grid-cols-5">
- {cards.map(({ label, value }) => (
- <div key={label} className="flex flex-col gap-1 rounded-md border bg-surface-primary p-4">
- <span className="text-xs text-secondary">{label}</span>
- {summaryStatsLoading ? (
- <LemonSkeleton className="h-8 w-20" />
- ) : (
- <span className="text-2xl font-bold">{value ?? '—'}</span>
- )}
- </div>
- ))}
- </div>
- )
-}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.test.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.test.ts
index 39e1340dba8e..4416accf18f1 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.test.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.test.ts
@@ -98,10 +98,61 @@ describe('errorTrackingInsightsLogic', () => {
)
expect(JSON.stringify(insights.values.issuesCreatedQuery)).not.toContain(PropertyFilterType.ErrorTrackingIssue)
- const lastSummaryStatsQuery = jest.mocked(api.query).mock.calls.at(-1)?.[0] as any
- expect(lastSummaryStatsQuery.filters.properties).toEqual(inner.values)
- expect(JSON.stringify(lastSummaryStatsQuery.filters.properties)).not.toContain(
- PropertyFilterType.ErrorTrackingIssue
- )
+ // Every HogQL query behind the tab has to see the same stripped properties as the charts, or a
+ // metric tile disagrees with the chart under it about which events matched.
+ const hogQLQueries = jest.mocked(api.query).mock.calls.map(([query]) => query as any)
+ expect(hogQLQueries.length).toBeGreaterThan(0)
+ for (const query of hogQLQueries) {
+ expect(query.filters.properties).toEqual(inner.values)
+ expect(JSON.stringify(query.filters.properties)).not.toContain(PropertyFilterType.ErrorTrackingIssue)
+ }
+ })
+
+ it('applies a band as filters, marking a value it has none of as not set', async () => {
+ await expectLogic(insights, () => {
+ insights.actions.filterByBand([
+ { key: '$app_namespace', value: 'web' },
+ { key: '$app_version', value: '1.2.0' },
+ { key: '$app_build', value: null },
+ ])
+ }).toFinishAllListeners()
+
+ const inner = insights.values.insightsFilterGroup.values[0] as UniversalFiltersGroup
+ expect(inner.values).toEqual([
+ { type: PropertyFilterType.Event, key: '$app_namespace', operator: PropertyOperator.Exact, value: ['web'] },
+ { type: PropertyFilterType.Event, key: '$app_version', operator: PropertyOperator.Exact, value: ['1.2.0'] },
+ { type: PropertyFilterType.Event, key: '$app_build', operator: PropertyOperator.IsNotSet },
+ ])
+ // Every chip the click added has to be counted, or the filter bar opens the value editor on
+ // all but the last of them.
+ expect(issueFilters.values.filterAddedFromPreview).toBe(3)
+ })
+
+ // A band is one value spread over several properties. Left in an "Any" group its chips match
+ // anything carrying any one of them, which is the opposite of filtering down to the band.
+ it('makes the filter group conjunctive so a band cannot be applied as an OR', async () => {
+ issueFilters.actions.setFilterGroup({
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.Or,
+ values: [
+ {
+ type: PropertyFilterType.Event,
+ key: '$browser',
+ operator: PropertyOperator.Exact,
+ value: ['Firefox'],
+ },
+ ],
+ },
+ ],
+ })
+
+ await expectLogic(insights, () => {
+ insights.actions.filterByBand([{ key: '$app_namespace', value: 'web' }])
+ }).toFinishAllListeners()
+
+ const inner = issueFilters.values.filterGroup.values[0] as UniversalFiltersGroup
+ expect(inner.type).toBe(FilterLogicalOperator.And)
})
})
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.ts
index 356bccca5065..eed28de66c11 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.ts
@@ -1,10 +1,12 @@
-import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import api from 'lib/api'
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
+import { buildBucketKeys, buildComparisonWindow, lastBucketIsInProgress } from 'lib/utils/timeBuckets'
+import { teamLogic } from 'scenes/teamLogic'
import {
DateRange,
@@ -17,28 +19,37 @@ import {
import {
AnyPropertyFilter,
FilterLogicalOperator,
+ IntervalType,
PropertyFilterType,
+ PropertyOperator,
UniversalFiltersGroup,
UniversalFiltersGroupValue,
} from '~/types'
import { issueFiltersLogic } from '../../../../components/IssueFilters/issueFiltersLogic'
import { ERROR_TRACKING_SCENE_LOGIC_KEY } from '../../errorTrackingSceneLogic'
+import {
+ ComparisonTotals,
+ EMPTY_COMPARISON_TOTALS,
+ InsightsMetrics,
+ SummaryBucket,
+ buildMetrics,
+ parseComparisonTotals,
+ parseSummaryBuckets,
+} from './insightsMetrics'
import {
buildAffectedUsersQuery,
+ buildAppBreakdownQuery,
+ buildComparisonTotalsQuery,
buildCrashFreeSessionsQuery,
buildExceptionVolumeQuery,
buildIssuesCreatedQuery,
+ buildReleaseBreakdownQuery,
+ buildSummarySeriesQuery,
+ getInterval,
InsightQueryFilters,
} from './queries'
-
-export interface InsightsSummaryStats {
- totalExceptions: number
- affectedUsers: number
- totalSessions: number
- crashSessions: number
- crashFreeRate: number
-}
+import { BandFilter, MAX_RELEASE_ROWS, ReleaseRow, parseReleaseRows } from './releaseBreakdown'
function stripIssueFiltersFromGroup(group: UniversalFiltersGroup): UniversalFiltersGroup {
const values = group.values.reduce<UniversalFiltersGroupValue[]>((strippedValues, filter) => {
@@ -65,20 +76,46 @@ export interface errorTrackingInsightsLogicValues {
filterGroup: UniversalFiltersGroup // issueFiltersLogic
filterTestAccounts: boolean // issueFiltersLogic
mergedFilterGroup: UniversalFiltersGroup // issueFiltersLogic
+ timezone: string // teamLogic
affectedUsersQuery: InsightVizNode<TrendsQuery>
+ appRows: ReleaseRow[]
+ appRowsLoading: boolean
+ bucketKeys: string[]
+ comparisonTotals: ComparisonTotals
+ comparisonTotalsLoading: boolean
crashFreeSessionsQuery: InsightVizNode<TrendsQuery>
effectiveDateRange: DateRange
effectiveProperties: AnyPropertyFilter[]
exceptionVolumeQuery: InsightVizNode<TrendsQuery>
+ incompleteTail: boolean
insightQueryFilters: InsightQueryFilters
insightsFilterGroup: UniversalFiltersGroup
+ interval: IntervalType
issuesCreatedQuery: InsightVizNode<TrendsQuery>
- summaryStats: InsightsSummaryStats | null
- summaryStatsLoading: boolean
+ loadFailed: boolean
+ metrics: InsightsMetrics
+ metricsLoading: boolean
+ releaseRows: ReleaseRow[]
+ releaseRowsLoading: boolean
+ summaryBuckets: SummaryBucket[]
+ summaryBucketsLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface errorTrackingInsightsLogicActions {
+ addPropertyFilter: (
+ key: string,
+ value: boolean | number | string | null,
+ operator?: PropertyOperator | undefined,
+ openConfig?: boolean | undefined,
+ replaceExisting?: boolean | undefined
+ ) => {
+ key: string
+ openConfig: boolean
+ operator: PropertyOperator
+ replaceExisting: boolean
+ value: boolean | number | string | null
+ } // issueFiltersLogic
setDateRange: (
dateRange: DateRange,
fromPreview?: boolean | undefined
@@ -96,32 +133,69 @@ export interface errorTrackingInsightsLogicActions {
setFilterTestAccounts: (filterTestAccounts: boolean) => {
filterTestAccounts: boolean
} // issueFiltersLogic
- loadSummaryStats: (_: any) => any
- loadSummaryStatsFailure: (
+ filterByBand: (filters: BandFilter[]) => {
+ filters: BandFilter[]
+ }
+ loadAppRows: (_: void) => void
+ loadAppRowsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAppRowsSuccess: (
+ appRows: ReleaseRow[],
+ payload?: void
+ ) => {
+ appRows: ReleaseRow[]
+ payload?: void
+ }
+ loadComparisonTotals: (_: void) => void
+ loadComparisonTotalsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadComparisonTotalsSuccess: (
+ comparisonTotals: ComparisonTotals,
+ payload?: void
+ ) => {
+ comparisonTotals: ComparisonTotals
+ payload?: void
+ }
+ loadInsights: () => void
+ loadReleaseRows: (_: void) => void
+ loadReleaseRowsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadReleaseRowsSuccess: (
+ releaseRows: ReleaseRow[],
+ payload?: void
+ ) => {
+ releaseRows: ReleaseRow[]
+ payload?: void
+ }
+ loadSummaryBuckets: (_: void) => void
+ loadSummaryBucketsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
- loadSummaryStatsSuccess: (
- summaryStats: {
- affectedUsers: number
- crashFreeRate: number
- crashSessions: number
- totalExceptions: number
- totalSessions: number
- } | null,
- payload?: any
+ loadSummaryBucketsSuccess: (
+ summaryBuckets: SummaryBucket[],
+ payload?: void
) => {
- summaryStats: {
- affectedUsers: number
- crashFreeRate: number
- crashSessions: number
- totalExceptions: number
- totalSessions: number
- } | null
- payload?: any
+ summaryBuckets: SummaryBucket[]
+ payload?: void
}
}
@@ -131,10 +205,20 @@ export interface errorTrackingInsightsLogicMeta {
insightsFilterGroup: (mergedFilterGroup: UniversalFiltersGroup) => UniversalFiltersGroup
effectiveProperties: (insightsFilterGroup: UniversalFiltersGroup) => AnyPropertyFilter[]
effectiveDateRange: (dateRange: DateRange) => DateRange
+ interval: (effectiveDateRange: DateRange) => IntervalType
+ bucketKeys: (effectiveDateRange: DateRange, timezone: string, interval: IntervalType) => string[]
+ incompleteTail: (bucketKeys: string[], timezone: string, interval: IntervalType) => boolean
insightQueryFilters: (
effectiveProperties: AnyPropertyFilter[],
filterTestAccounts: boolean
) => InsightQueryFilters
+ metrics: (
+ comparisonTotals: ComparisonTotals,
+ summaryBuckets: SummaryBucket[],
+ bucketKeys: string[],
+ interval: IntervalType
+ ) => InsightsMetrics
+ metricsLoading: (comparisonTotalsLoading: boolean, summaryBucketsLoading: boolean) => boolean
exceptionVolumeQuery: (
effectiveDateRange: DateRange,
insightQueryFilters: InsightQueryFilters
@@ -176,10 +260,119 @@ export const errorTrackingInsightsLogic = kea<errorTrackingInsightsLogicType>([
values: [
issueFiltersLogic({ logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY }),
['dateRange', 'filterTestAccounts', 'filterGroup', 'mergedFilterGroup'],
+ teamLogic,
+ ['timezone'],
],
actions: [
issueFiltersLogic({ logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY }),
- ['setDateRange', 'setFilterGroup', 'setFilterTestAccounts'],
+ ['setDateRange', 'setFilterGroup', 'setFilterTestAccounts', 'addPropertyFilter'],
+ ],
+ })),
+
+ actions({
+ loadInsights: () => {},
+ filterByBand: (filters: BandFilter[]) => ({ filters }),
+ }),
+
+ reducers({
+ loadFailed: [
+ false,
+ {
+ loadInsights: () => false,
+ loadComparisonTotalsFailure: () => true,
+ loadSummaryBucketsFailure: () => true,
+ loadReleaseRowsFailure: () => true,
+ loadAppRowsFailure: () => true,
+ },
+ ],
+ }),
+
+ loaders(({ values }) => ({
+ comparisonTotals: [
+ EMPTY_COMPARISON_TOTALS,
+ {
+ loadComparisonTotals: async (_: void, breakpoint): Promise<ComparisonTotals> => {
+ await breakpoint(10)
+ const window = buildComparisonWindow(
+ values.effectiveDateRange.date_from ?? null,
+ values.effectiveDateRange.date_to ?? null,
+ values.timezone,
+ values.interval
+ )
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: buildComparisonTotalsQuery(window.currentStart, values.timezone),
+ filters: {
+ dateRange: { date_from: window.dateFrom, date_to: window.dateTo },
+ filterTestAccounts: values.filterTestAccounts,
+ properties: values.effectiveProperties,
+ },
+ tags: { productKey: ProductKey.ERROR_TRACKING },
+ })) as HogQLQueryResponse
+ breakpoint()
+ return parseComparisonTotals((response?.results as unknown[][]) ?? [])
+ },
+ },
+ ],
+ summaryBuckets: [
+ [] as SummaryBucket[],
+ {
+ loadSummaryBuckets: async (_: void, breakpoint): Promise<SummaryBucket[]> => {
+ await breakpoint(10)
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: buildSummarySeriesQuery(values.interval),
+ filters: {
+ dateRange: values.effectiveDateRange,
+ filterTestAccounts: values.filterTestAccounts,
+ properties: values.effectiveProperties,
+ },
+ tags: { productKey: ProductKey.ERROR_TRACKING },
+ })) as HogQLQueryResponse
+ breakpoint()
+ return parseSummaryBuckets((response?.results as unknown[][]) ?? [])
+ },
+ },
+ ],
+ appRows: [
+ [] as ReleaseRow[],
+ {
+ loadAppRows: async (_: void, breakpoint): Promise<ReleaseRow[]> => {
+ await breakpoint(10)
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: buildAppBreakdownQuery(values.interval, MAX_RELEASE_ROWS),
+ filters: {
+ dateRange: values.effectiveDateRange,
+ filterTestAccounts: values.filterTestAccounts,
+ properties: values.effectiveProperties,
+ },
+ tags: { productKey: ProductKey.ERROR_TRACKING },
+ })) as HogQLQueryResponse
+ breakpoint()
+ return parseReleaseRows((response?.results as unknown[][]) ?? [], values.bucketKeys)
+ },
+ },
+ ],
+ releaseRows: [
+ [] as ReleaseRow[],
+ {
+ loadReleaseRows: async (_: void, breakpoint): Promise<ReleaseRow[]> => {
+ await breakpoint(10)
+ const response = (await api.query({
+ kind: NodeKind.HogQLQuery,
+ query: buildReleaseBreakdownQuery(values.interval, MAX_RELEASE_ROWS),
+ filters: {
+ dateRange: values.effectiveDateRange,
+ filterTestAccounts: values.filterTestAccounts,
+ properties: values.effectiveProperties,
+ },
+ tags: { productKey: ProductKey.ERROR_TRACKING },
+ })) as HogQLQueryResponse
+ breakpoint()
+ return parseReleaseRows((response?.results as unknown[][]) ?? [], values.bucketKeys)
+ },
+ },
],
})),
@@ -212,6 +405,22 @@ export const errorTrackingInsightsLogic = kea<errorTrackingInsightsLogicType>([
date_to: dateRange.date_to ?? null,
}),
],
+ // The charts and the metric tiles have to bucket the same way, or a tile's sparkline reads as
+ // a different shape than the chart directly below it.
+ interval: [
+ (s) => [s.effectiveDateRange],
+ (dateRange: DateRange): IntervalType => getInterval(dateRange.date_from, dateRange.date_to),
+ ],
+ bucketKeys: [
+ (s) => [s.effectiveDateRange, s.timezone, s.interval],
+ (dateRange: DateRange, timezone: string, interval: IntervalType): string[] =>
+ buildBucketKeys(dateRange.date_from ?? null, dateRange.date_to ?? null, timezone, interval),
+ ],
+ incompleteTail: [
+ (s) => [s.bucketKeys, s.timezone, s.interval],
+ (bucketKeys: string[], timezone: string, interval: IntervalType): boolean =>
+ lastBucketIsInProgress(bucketKeys, timezone, interval),
+ ],
insightQueryFilters: [
(s) => [s.effectiveProperties, s.filterTestAccounts],
(properties: AnyPropertyFilter[], filterTestAccounts: boolean): InsightQueryFilters => ({
@@ -219,6 +428,21 @@ export const errorTrackingInsightsLogic = kea<errorTrackingInsightsLogicType>([
filterTestAccounts,
}),
],
+ metrics: [
+ (s) => [s.comparisonTotals, s.summaryBuckets, s.bucketKeys, s.interval],
+ (
+ totals: ComparisonTotals,
+ buckets: SummaryBucket[],
+ bucketKeys: string[],
+ interval: IntervalType
+ ): InsightsMetrics => buildMetrics(totals, buckets, bucketKeys, interval),
+ ],
+ // The tiles read both queries, so they stay in their loading state until both have answered
+ // rather than showing a headline number above a sparkline that is still empty.
+ metricsLoading: [
+ (s) => [s.comparisonTotalsLoading, s.summaryBucketsLoading],
+ (totalsLoading: boolean, bucketsLoading: boolean): boolean => totalsLoading || bucketsLoading,
+ ],
exceptionVolumeQuery: [
(s) => [s.effectiveDateRange, s.insightQueryFilters],
(dateRange: DateRange, filters: InsightQueryFilters): InsightVizNode<TrendsQuery> =>
@@ -241,72 +465,58 @@ export const errorTrackingInsightsLogic = kea<errorTrackingInsightsLogicType>([
],
}),
- loaders(({ values }) => ({
- summaryStats: [
- null as InsightsSummaryStats | null,
- {
- loadSummaryStats: async (_, breakpoint) => {
- await breakpoint(10)
- const response = await api.query({
- kind: NodeKind.HogQLQuery,
- query: `
- SELECT
- countIf(event = '$exception') as total_exceptions,
- uniqIf(person_id, event = '$exception') as affected_users,
- uniqIf($session_id, notEmpty($session_id)) as total_sessions,
- uniqIf($session_id, event = '$exception' AND notEmpty($session_id)) as crash_sessions
- FROM events
- WHERE {filters}
- `,
- filters: {
- dateRange: values.effectiveDateRange,
- filterTestAccounts: values.filterTestAccounts,
- properties: values.effectiveProperties,
- },
- tags: { productKey: ProductKey.ERROR_TRACKING },
- })
- const row = (response as HogQLQueryResponse)?.results?.[0]
- if (!row) {
- return null
- }
- const [totalExceptions, affectedUsers, totalSessions, crashSessions] = row as [
- number,
- number,
- number,
- number,
- ]
- const crashFreeRate =
- totalSessions > 0 ? ((totalSessions - crashSessions) / totalSessions) * 100 : 100
-
- return {
- totalExceptions,
- affectedUsers,
- totalSessions,
- crashSessions,
- crashFreeRate: Math.round(crashFreeRate * 100) / 100,
- }
- },
- },
- ],
- })),
-
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
+ loadInsights: () => {
+ actions.loadComparisonTotals()
+ actions.loadSummaryBuckets()
+ actions.loadReleaseRows()
+ actions.loadAppRows()
+ },
setDateRange: () => {
- actions.loadSummaryStats(null)
+ actions.loadInsights()
},
setFilterTestAccounts: () => {
- actions.loadSummaryStats(null)
+ actions.loadInsights()
+ },
+ // A band with no value for a property filters on "is not set", so a click never leaves a stale
+ // chip from the band clicked before it.
+ filterByBand: ({ filters }) => {
+ for (const { key, value } of filters) {
+ actions.addPropertyFilter(
+ key,
+ value,
+ value === null ? PropertyOperator.IsNotSet : PropertyOperator.Exact,
+ false,
+ true
+ )
+ }
+ // A band is one value spread over several properties, so its chips only mean what the
+ // panel says while they combine with AND. Added to a group the user set to "Any" they
+ // would instead match anything carrying any one of them.
+ const group = values.filterGroup
+ const first = group.values[0]
+ const conjunctive =
+ isUniversalGroupFilterLike(first) && first.type !== FilterLogicalOperator.And
+ ? {
+ ...group,
+ values: [{ ...first, type: FilterLogicalOperator.And }, ...group.values.slice(1)],
+ }
+ : group
+ // Each add resets the preview-added count to one chip, so all but the last of these would
+ // open its value editor on the next render. Re-count every chip this click added, which
+ // lands the band as chips alone.
+ actions.setFilterGroup(conjunctive, filters.length)
},
})),
subscriptions(({ actions }) => ({
insightsFilterGroup: () => {
- actions.loadSummaryStats(null)
+ actions.loadInsights()
},
})),
afterMount(({ actions }) => {
posthog.capture('error_tracking_insights_viewed')
- actions.loadSummaryStats(null)
+ actions.loadInsights()
}),
])
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/insightsMetrics.test.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/insightsMetrics.test.ts
new file mode 100644
index 000000000000..99b05544ea69
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/insightsMetrics.test.ts
@@ -0,0 +1,77 @@
+import { buildMetrics, crashFreeRate, parseComparisonTotals, parseSummaryBuckets } from './insightsMetrics'
+
+describe('insightsMetrics', () => {
+ describe('parseComparisonTotals', () => {
+ // The query interleaves each measure with its previous-period twin. Reordering the SELECT
+ // without reordering this would silently show one metric's value against another's baseline.
+ it('reads the interleaved current and previous columns', () => {
+ const totals = parseComparisonTotals([[100, 50, 9, 4, 80, 70, 20, 10, 3, 2]])
+
+ expect(totals.current).toEqual({
+ exceptions: 100,
+ affectedUsers: 9,
+ sessions: 80,
+ crashSessions: 20,
+ releases: 3,
+ })
+ expect(totals.previous).toEqual({
+ exceptions: 50,
+ affectedUsers: 4,
+ sessions: 70,
+ crashSessions: 10,
+ releases: 2,
+ })
+ })
+
+ it('reads an empty response as a period with no activity', () => {
+ expect(parseComparisonTotals([]).current.exceptions).toBe(0)
+ })
+ })
+
+ describe('crashFreeRate', () => {
+ it.each([
+ [100, 20, 80],
+ [100, 0, 100],
+ ])('%s sessions with %s crashing is %s%% crash-free', (sessions, crashSessions, expected) => {
+ expect(crashFreeRate({ sessions, crashSessions })).toBe(expected)
+ })
+
+ // Reporting 100% for a period with no traffic claims a clean period on no evidence, and hands
+ // the comparison a baseline that makes every delta read as no change.
+ it('has no rate for a period with no sessions', () => {
+ expect(crashFreeRate({ sessions: 0, crashSessions: 0 })).toBeNull()
+ })
+ })
+
+ describe('buildMetrics', () => {
+ const bucketKeys = ['2026-06-01 00:00:00', '2026-06-02 00:00:00', '2026-06-03 00:00:00']
+ const totals = parseComparisonTotals([[30, 15, 6, 4, 100, 100, 12, 8, 2, 1]])
+
+ // A quiet bucket returns no row at all. Falling back to the returned rows would draw a
+ // sparkline shorter than the chart beside it, with the gap closed up rather than shown.
+ it('zero-fills the buckets the query returned no row for', () => {
+ const buckets = parseSummaryBuckets([['2026-06-03 00:00:00', 20, 5, 60, 8, 2]])
+
+ const metrics = buildMetrics(totals, buckets, bucketKeys, 'day')
+
+ expect(metrics.exceptions.sparkline).toEqual([0, 0, 20])
+ expect(metrics.exceptions.sparklineLabels).toEqual(['Jun 1', 'Jun 2', 'Jun 3'])
+ expect(metrics.crashFreeRate.sparkline).toEqual([100, 100, (52 / 60) * 100])
+ })
+
+ it('compares each headline against the previous period', () => {
+ const metrics = buildMetrics(totals, [], bucketKeys, 'day')
+
+ expect(metrics.exceptions).toMatchObject({ value: 30, previousValue: 15, deltaPct: 100 })
+ expect(metrics.releases).toMatchObject({ value: 2, previousValue: 1, deltaPct: 100 })
+ expect(metrics.crashFreeRate).toMatchObject({ value: 88, previousValue: 92 })
+ })
+
+ // Without a baseline the tile has to show no pill: a jump from nothing is not a percentage.
+ it('reports no change when the previous period was empty', () => {
+ const fromNothing = parseComparisonTotals([[30, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
+
+ expect(buildMetrics(fromNothing, [], bucketKeys, 'day').exceptions.deltaPct).toBeNull()
+ })
+ })
+})
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/insightsMetrics.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/insightsMetrics.ts
new file mode 100644
index 000000000000..db83d05caf8d
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/insightsMetrics.ts
@@ -0,0 +1,181 @@
+import { formatBucketLabel, normalizeBucket } from 'lib/utils/timeBuckets'
+
+import { IntervalType } from '~/types'
+
+export interface InsightMetric {
+ /** Null when the period holds nothing the metric can be computed from. */
+ value: number | null
+ previousValue: number | null
+ /** Null when the previous period had nothing to compare against, so the tile shows no change pill. */
+ deltaPct: number | null
+ sparkline: number[]
+ sparklineLabels: string[]
+ goodDirection: 'up' | 'down'
+}
+
+export interface InsightsMetrics {
+ exceptions: InsightMetric
+ affectedUsers: InsightMetric
+ sessions: InsightMetric
+ crashSessions: InsightMetric
+ crashFreeRate: InsightMetric
+ releases: InsightMetric
+}
+
+/** The five aggregates the summary query returns for one period. */
+export interface PeriodTotals {
+ exceptions: number
+ affectedUsers: number
+ sessions: number
+ crashSessions: number
+ releases: number
+}
+
+export interface ComparisonTotals {
+ current: PeriodTotals
+ previous: PeriodTotals
+}
+
+/** One bucket of the summary series, already normalized to a bucket key the zero-fill can join on. */
+export interface SummaryBucket extends PeriodTotals {
+ bucket: string
+}
+
+const EMPTY_TOTALS: PeriodTotals = {
+ exceptions: 0,
+ affectedUsers: 0,
+ sessions: 0,
+ crashSessions: 0,
+ releases: 0,
+}
+
+export const EMPTY_COMPARISON_TOTALS: ComparisonTotals = { current: EMPTY_TOTALS, previous: EMPTY_TOTALS }
+
+/**
+ * Percentage of sessions that reported no exception, or null when there were no sessions at all.
+ * A period with no traffic has no rate: reporting 100% there would claim a clean period on the
+ * strength of no evidence, and it would give the comparison a baseline to divide by.
+ */
+export function crashFreeRate({
+ sessions,
+ crashSessions,
+}: Pick<PeriodTotals, 'sessions' | 'crashSessions'>): number | null {
+ return sessions > 0 ? ((sessions - crashSessions) / sessions) * 100 : null
+}
+
+/** Per-bucket rate for the sparkline, where a bucket with no sessions draws flat rather than absent. */
+function bucketCrashFreeRate(totals: PeriodTotals): number {
+ return crashFreeRate(totals) ?? 100
+}
+
+function changePct(current: number | null, previous: number | null): number | null {
+ if (current === null || previous === null || previous === 0) {
+ return current === 0 && previous === 0 ? 0 : null
+ }
+ return ((current - previous) / previous) * 100
+}
+
+export function parseComparisonTotals(rawRows: unknown[][]): ComparisonTotals {
+ const row = rawRows[0]
+ if (!row) {
+ return { current: EMPTY_TOTALS, previous: EMPTY_TOTALS }
+ }
+ return {
+ current: {
+ exceptions: Number(row[0] ?? 0),
+ affectedUsers: Number(row[2] ?? 0),
+ sessions: Number(row[4] ?? 0),
+ crashSessions: Number(row[6] ?? 0),
+ releases: Number(row[8] ?? 0),
+ },
+ previous: {
+ exceptions: Number(row[1] ?? 0),
+ affectedUsers: Number(row[3] ?? 0),
+ sessions: Number(row[5] ?? 0),
+ crashSessions: Number(row[7] ?? 0),
+ releases: Number(row[9] ?? 0),
+ },
+ }
+}
+
+export function parseSummaryBuckets(rawRows: unknown[][]): SummaryBucket[] {
+ return rawRows.map((row) => ({
+ bucket: normalizeBucket(row[0]),
+ exceptions: Number(row[1] ?? 0),
+ affectedUsers: Number(row[2] ?? 0),
+ sessions: Number(row[3] ?? 0),
+ crashSessions: Number(row[4] ?? 0),
+ releases: Number(row[5] ?? 0),
+ }))
+}
+
+/**
+ * Headline numbers from the comparison query and sparklines from the per-bucket series.
+ *
+ * The two come from separate queries because the headline distinct counts (users, sessions, releases)
+ * cannot be recovered by summing per-bucket distinct counts: anything active in more than one bucket
+ * would be counted once per bucket.
+ */
+export function buildMetrics(
+ totals: ComparisonTotals,
+ buckets: SummaryBucket[],
+ bucketKeys: string[],
+ interval: IntervalType
+): InsightsMetrics {
+ const byBucket = new Map(buckets.map((bucket) => [bucket.bucket, bucket]))
+ const series = bucketKeys.map((key) => byBucket.get(key) ?? EMPTY_TOTALS)
+ const sparklineLabels = bucketKeys.map((key) => formatBucketLabel(key, interval))
+
+ const metric = (
+ value: number | null,
+ previousValue: number | null,
+ sparkline: number[],
+ goodDirection: 'up' | 'down'
+ ): InsightMetric => ({
+ value,
+ previousValue,
+ deltaPct: changePct(value, previousValue),
+ sparkline,
+ sparklineLabels,
+ goodDirection,
+ })
+
+ return {
+ exceptions: metric(
+ totals.current.exceptions,
+ totals.previous.exceptions,
+ series.map((bucket) => bucket.exceptions),
+ 'down'
+ ),
+ affectedUsers: metric(
+ totals.current.affectedUsers,
+ totals.previous.affectedUsers,
+ series.map((bucket) => bucket.affectedUsers),
+ 'down'
+ ),
+ sessions: metric(
+ totals.current.sessions,
+ totals.previous.sessions,
+ series.map((bucket) => bucket.sessions),
+ 'up'
+ ),
+ crashSessions: metric(
+ totals.current.crashSessions,
+ totals.previous.crashSessions,
+ series.map((bucket) => bucket.crashSessions),
+ 'down'
+ ),
+ crashFreeRate: metric(
+ crashFreeRate(totals.current),
+ crashFreeRate(totals.previous),
+ series.map(bucketCrashFreeRate),
+ 'up'
+ ),
+ releases: metric(
+ totals.current.releases,
+ totals.previous.releases,
+ series.map((bucket) => bucket.releases),
+ 'up'
+ ),
+ }
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/queries.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/queries.ts
index 1cb511ce4048..a319568e7722 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/queries.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/queries.ts
@@ -12,6 +12,10 @@ export interface InsightQueryFilters {
const MAX_HOURS_FOR_HOURLY_INTERVAL = 25
+// Buckets the summary series may return. Hourly windows stay under a day and daily windows come from
+// a date picker, so no reachable range approaches this.
+const MAX_SUMMARY_BUCKETS = 10000
+
export function getInterval(dateFrom: string | null | undefined, dateTo: string | null | undefined): IntervalType {
const from = dateStringToDayJs(dateFrom ?? null)
const to = dateStringToDayJs(dateTo ?? null) ?? dayjs()
@@ -21,6 +25,111 @@ export function getInterval(dateFrom: string | null | undefined, dateTo: string
return 'day'
}
+// Exceptions carry their release as $app_namespace / $app_version / $app_build, the same identity the
+// issue page's releases panel groups by. Coalescing a missing property to '' keeps it inside the
+// aggregates below: a null would propagate through the comparison and drop the row instead of
+// grouping it as "no release data".
+const RELEASE_NAMESPACE = "coalesce(toString(properties.$app_namespace), '')"
+const RELEASE_VERSION = "coalesce(toString(properties.$app_version), '')"
+const RELEASE_BUILD = "coalesce(toString(properties.$app_build), '')"
+const RELEASE_KEY = `tuple(${RELEASE_NAMESPACE}, ${RELEASE_VERSION}, ${RELEASE_BUILD})`
+const HAS_RELEASE = `${RELEASE_VERSION} != ''`
+
+// toString() is load-bearing: a bare dateTrunc returns a typed DateTime that the query API serializes
+// with the project's UTC offset attached, which the client reads back as an instant and converts,
+// shifting every bucket away from the wall-clock keys it joins against. Rendering it server-side
+// leaves a plain string with nothing left to reinterpret.
+function bucketExpr(interval: IntervalType): string {
+ return `toString(dateTrunc('${interval}', timestamp))`
+}
+
+/**
+ * Headline totals for the selected period and the equal-length period before it.
+ *
+ * Runs over the doubled window and splits on `currentStart`, so both halves come back from one
+ * scan. Distinct counts have to be measured over the whole period rather than summed from the series
+ * query: a person, session, or release active on more than one day would otherwise be counted once
+ * per day. Column order is the contract `parseComparisonTotals` reads.
+ */
+export function buildComparisonTotalsQuery(currentStart: string, timezone: string): string {
+ const current = `timestamp >= toDateTime('${currentStart}', '${timezone}')`
+ const previous = `timestamp < toDateTime('${currentStart}', '${timezone}')`
+ const exception = "event = '$exception'"
+ const session = 'notEmpty($session_id)'
+ return `
+ SELECT
+ countIf(${exception} AND ${current}) AS exceptions,
+ countIf(${exception} AND ${previous}) AS previous_exceptions,
+ uniqIf(person_id, ${exception} AND ${current}) AS affected_users,
+ uniqIf(person_id, ${exception} AND ${previous}) AS previous_affected_users,
+ uniqIf($session_id, ${session} AND ${current}) AS sessions,
+ uniqIf($session_id, ${session} AND ${previous}) AS previous_sessions,
+ uniqIf($session_id, ${exception} AND ${session} AND ${current}) AS crash_sessions,
+ uniqIf($session_id, ${exception} AND ${session} AND ${previous}) AS previous_crash_sessions,
+ uniqIf(${RELEASE_KEY}, ${exception} AND ${HAS_RELEASE} AND ${current}) AS releases,
+ uniqIf(${RELEASE_KEY}, ${exception} AND ${HAS_RELEASE} AND ${previous}) AS previous_releases
+ FROM events
+ WHERE {filters}
+ `
+}
+
+/**
+ * The same measures per bucket over the selected period, for the metric tiles' sparklines. Column
+ * order is the contract `parseSummaryBuckets` reads.
+ *
+ * The LIMIT is load-bearing. A HogQL query with no limit of its own is paginated at 100 rows, and
+ * these rows are ordered oldest first, so a window longer than 100 buckets would drop its most
+ * recent ones and the zero-fill would draw them as zeros. The cap is set above any window the date
+ * picker can produce rather than at a number a real range could reach.
+ */
+export function buildSummarySeriesQuery(interval: IntervalType): string {
+ return `
+ SELECT
+ ${bucketExpr(interval)} AS bucket,
+ countIf(event = '$exception') AS exceptions,
+ uniqIf(person_id, event = '$exception') AS affected_users,
+ uniqIf($session_id, notEmpty($session_id)) AS sessions,
+ uniqIf($session_id, event = '$exception' AND notEmpty($session_id)) AS crash_sessions,
+ uniqIf(${RELEASE_KEY}, event = '$exception' AND ${HAS_RELEASE}) AS releases
+ FROM events
+ WHERE {filters}
+ GROUP BY bucket
+ ORDER BY bucket
+ LIMIT ${MAX_SUMMARY_BUCKETS}
+ `
+}
+
+/**
+ * Exception volume per release, folded server-side into one row per release.
+ *
+ * Grouping by release and collecting the buckets into an array keeps a busy account to one row per
+ * release rather than one per release and bucket, which is what lets the row cap bound the response.
+ * Column order is the contract `parseReleaseRows` reads.
+ */
+export function buildReleaseBreakdownQuery(interval: IntervalType, maxRows: number): string {
+ return `
+ SELECT
+ namespace,
+ version,
+ build,
+ groupArray(tuple(bucket, occurrences)) AS series
+ FROM (
+ SELECT
+ ${bucketExpr(interval)} AS bucket,
+ ${RELEASE_NAMESPACE} AS namespace,
+ ${RELEASE_VERSION} AS version,
+ ${RELEASE_BUILD} AS build,
+ count() AS occurrences
+ FROM events
+ WHERE event = '$exception' AND {filters}
+ GROUP BY bucket, namespace, version, build
+ )
+ GROUP BY namespace, version, build
+ ORDER BY sum(occurrences) DESC
+ LIMIT ${maxRows}
+ `
+}
+
export function buildExceptionVolumeQuery(
dateRange: DateRange,
{ properties, filterTestAccounts }: InsightQueryFilters
@@ -46,6 +155,8 @@ export function buildExceptionVolumeQuery(
},
showHeader: false,
showTable: false,
+ // The card around the chart already draws the border, so the viz must not draw its own.
+ embedded: true,
}
}
@@ -78,6 +189,8 @@ export function buildIssuesCreatedQuery(
},
showHeader: false,
showTable: false,
+ // The card around the chart already draws the border, so the viz must not draw its own.
+ embedded: true,
}
}
@@ -107,6 +220,8 @@ export function buildAffectedUsersQuery(
},
showHeader: false,
showTable: false,
+ // The card around the chart already draws the border, so the viz must not draw its own.
+ embedded: true,
}
}
@@ -146,9 +261,42 @@ export function buildCrashFreeSessionsQuery(
},
showHeader: false,
showTable: false,
+ // The card around the chart already draws the border, so the viz must not draw its own.
+ embedded: true,
}
}
+/**
+ * Exception volume per app, grouped by namespace alone.
+ *
+ * This cannot be folded out of the release breakdown: that query caps its rows, so past the cap an
+ * app whose releases are all low-volume would vanish from the fold and the surviving apps' totals
+ * and shares would be short by the dropped rows, with nothing saying so. Grouping by namespace here
+ * keeps the app figures exact, and the row count is the number of apps rather than of releases.
+ * Column order is the contract `parseReleaseRows` reads, with the release columns left empty.
+ */
+export function buildAppBreakdownQuery(interval: IntervalType, maxRows: number): string {
+ return `
+ SELECT
+ namespace,
+ '' AS version,
+ '' AS build,
+ groupArray(tuple(bucket, occurrences)) AS series
+ FROM (
+ SELECT
+ ${bucketExpr(interval)} AS bucket,
+ ${RELEASE_NAMESPACE} AS namespace,
+ count() AS occurrences
+ FROM events
+ WHERE event = '$exception' AND {filters}
+ GROUP BY bucket, namespace
+ )
+ GROUP BY namespace
+ ORDER BY sum(occurrences) DESC
+ LIMIT ${maxRows}
+ `
+}
+
export function insightNewUrl(query: InsightVizNode<TrendsQuery>): string {
const editorQuery: InsightVizNode<TrendsQuery> = {
...query,
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/releaseBreakdown.test.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/releaseBreakdown.test.ts
new file mode 100644
index 000000000000..983a2e97789a
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/releaseBreakdown.test.ts
@@ -0,0 +1,145 @@
+import { buildAppBreakdown, buildReleaseBreakdown, MAX_VISIBLE_BANDS, parseReleaseRows } from './releaseBreakdown'
+
+const BUCKET_KEYS = ['2026-06-01 00:00:00', '2026-06-02 00:00:00', '2026-06-03 00:00:00']
+const PALETTE = ['#1', '#2', '#3', '#4', '#5', '#6', '#7']
+
+function releaseRow(version: string, series: [string, number][]): unknown[] {
+ return ['web', version, '', series]
+}
+
+describe('releaseBreakdown', () => {
+ describe('parseReleaseRows', () => {
+ // groupArray does not promise an order, so the pairs arrive shuffled. Reading them positionally
+ // would draw each release's volume against the wrong days.
+ it('projects out-of-order bucket pairs onto the bucket key order', () => {
+ const rows = parseReleaseRows(
+ [
+ releaseRow('1.2.0', [
+ ['2026-06-03 00:00:00', 7],
+ ['2026-06-01 00:00:00', 3],
+ ]),
+ ],
+ BUCKET_KEYS
+ )
+
+ expect(rows[0]).toMatchObject({
+ namespace: 'web',
+ version: '1.2.0',
+ build: null,
+ counts: [3, 0, 7],
+ total: 10,
+ })
+ })
+
+ it('drops buckets outside the selected window so the table and the chart agree', () => {
+ const rows = parseReleaseRows(
+ [
+ releaseRow('1.2.0', [
+ ['2026-05-20 00:00:00', 99],
+ ['2026-06-02 00:00:00', 4],
+ ]),
+ ],
+ BUCKET_KEYS
+ )
+
+ expect(rows[0].counts).toEqual([0, 4, 0])
+ expect(rows[0].total).toBe(4)
+ })
+ })
+
+ describe('buildReleaseBreakdown', () => {
+ it('folds everything past the visible cap into one band that cannot be filtered', () => {
+ const rows = parseReleaseRows(
+ Array.from({ length: MAX_VISIBLE_BANDS + 3 }, (_, index) =>
+ releaseRow(`1.0.${index}`, [['2026-06-01 00:00:00', 100 - index]])
+ ),
+ BUCKET_KEYS
+ )
+
+ const breakdown = buildReleaseBreakdown(rows, BUCKET_KEYS, PALETTE)
+
+ expect(breakdown.bands).toHaveLength(MAX_VISIBLE_BANDS + 1)
+ expect(breakdown.bands[MAX_VISIBLE_BANDS]).toMatchObject({
+ label: '3 other releases',
+ filters: null,
+ })
+ expect(breakdown.groupCount).toBe(MAX_VISIBLE_BANDS + 3)
+ })
+
+ // Exceptions with no $app_version are the reason someone opens this panel, so they get their
+ // own band rather than being folded in with the named releases, and it stays filterable.
+ it('separates exceptions that carry no release', () => {
+ const rows = parseReleaseRows(
+ [releaseRow('1.2.0', [['2026-06-01 00:00:00', 30]]), ['', '', '', [['2026-06-01 00:00:00', 10]]]],
+ BUCKET_KEYS
+ )
+
+ const breakdown = buildReleaseBreakdown(rows, BUCKET_KEYS, PALETTE)
+
+ expect(breakdown.bands[1]).toMatchObject({ label: 'No release data', total: 10, share: 25 })
+ expect(breakdown.bands[1].filters).toEqual([
+ { key: '$app_namespace', value: null },
+ { key: '$app_version', value: null },
+ { key: '$app_build', value: null },
+ ])
+ expect(breakdown.groupCount).toBe(1)
+ expect(breakdown.total).toBe(40)
+ })
+
+ it('labels a release with its app when the period spans more than one', () => {
+ const rows = parseReleaseRows(
+ [
+ ['web', '1.2.0', '', [['2026-06-01 00:00:00', 30]]],
+ ['ios', '4.1', '881', [['2026-06-01 00:00:00', 10]]],
+ ],
+ BUCKET_KEYS
+ )
+
+ expect(buildReleaseBreakdown(rows, BUCKET_KEYS, PALETTE).bands.map((band) => band.label)).toEqual([
+ 'web · 1.2.0',
+ 'ios · 4.1 (881)',
+ ])
+ })
+ })
+
+ describe('buildAppBreakdown', () => {
+ // The app query groups by namespace, but the fold still has to merge several rows per app:
+ // the release-shaped rows below are the shape parseReleaseRows produces for either query.
+ it('merges every release of an app into one band, filtering on the namespace alone', () => {
+ const rows = parseReleaseRows(
+ [
+ ['web', '1.2.0', '', [['2026-06-01 00:00:00', 30]]],
+ ['web', '1.3.0', '', [['2026-06-02 00:00:00', 12]]],
+ ['ios', '4.1', '881', [['2026-06-01 00:00:00', 10]]],
+ ],
+ BUCKET_KEYS
+ )
+
+ const breakdown = buildAppBreakdown(rows, BUCKET_KEYS, PALETTE)
+
+ expect(breakdown.bands.map((band) => band.label)).toEqual(['web', 'ios'])
+ expect(breakdown.bands[0]).toMatchObject({ total: 42, counts: [30, 12, 0] })
+ expect(breakdown.bands[0].filters).toEqual([{ key: '$app_namespace', value: 'web' }])
+ expect(breakdown.groupCount).toBe(2)
+ expect(breakdown.total).toBe(52)
+ })
+
+ // A release with a version but no namespace is a named release, yet it has no app — the two
+ // breakdowns have to split it differently.
+ it('counts a release with no namespace as having no app', () => {
+ const rows = parseReleaseRows(
+ [
+ ['web', '1.2.0', '', [['2026-06-01 00:00:00', 30]]],
+ ['', '9.9', '', [['2026-06-01 00:00:00', 10]]],
+ ],
+ BUCKET_KEYS
+ )
+
+ const breakdown = buildAppBreakdown(rows, BUCKET_KEYS, PALETTE)
+
+ expect(breakdown.bands.map((band) => band.label)).toEqual(['web', 'No app data'])
+ expect(breakdown.bands[1].filters).toEqual([{ key: '$app_namespace', value: null }])
+ expect(buildReleaseBreakdown(rows, BUCKET_KEYS, PALETTE).groupCount).toBe(2)
+ })
+ })
+})
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/releaseBreakdown.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/releaseBreakdown.ts
new file mode 100644
index 000000000000..386f922a253f
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/releaseBreakdown.ts
@@ -0,0 +1,268 @@
+import { normalizeBucket } from 'lib/utils/timeBuckets'
+
+import {
+ formatReleaseCount,
+ formatReleaseVersion,
+ UNATTRIBUTED_RELEASE_COLOR,
+} from 'products/error_tracking/frontend/components/IssueReleases/issueReleases'
+
+/** Values drawn as their own band. The rest fold into one "other" band. */
+export const MAX_VISIBLE_BANDS = 6
+
+/**
+ * Releases the query folds over. Past this the lowest-volume releases are dropped, so a capped
+ * response undercounts the "other" band while every named release stays exact. The response reports
+ * whether it was capped, so the panel can show its count as a lower bound.
+ */
+export const MAX_RELEASE_ROWS = 500
+
+export interface ReleaseIdentity {
+ namespace: string | null
+ version: string | null
+ build: string | null
+}
+
+export interface ReleaseRow extends ReleaseIdentity {
+ /** Occurrences per bucket, aligned with the bucket keys the row was parsed against. */
+ counts: number[]
+ total: number
+}
+
+/** One property filter a band click applies. A null value filters on "is not set". */
+export interface BandFilter {
+ key: string
+ value: string | null
+}
+
+export interface ExceptionBand {
+ key: string
+ label: string
+ color: string
+ counts: number[]
+ total: number
+ /** Share of the period's exceptions, as a percentage. */
+ share: number
+ /** Filters a click applies, or null for a band that folds several values together. */
+ filters: BandFilter[] | null
+}
+
+export interface ExceptionBreakdown {
+ bands: ExceptionBand[]
+ /** Named values the rows covered, before the visible/other split. */
+ groupCount: number
+ groupCountTruncated: boolean
+ total: number
+}
+
+export const EMPTY_EXCEPTION_BREAKDOWN: ExceptionBreakdown = {
+ bands: [],
+ groupCount: 0,
+ groupCountTruncated: false,
+ total: 0,
+}
+
+function emptyToNull(value: unknown): string | null {
+ const text = String(value ?? '')
+ return text === '' ? null : text
+}
+
+/**
+ * Project each release's `(bucket, occurrences)` pairs onto the full set of bucket keys.
+ *
+ * The query groups by release rather than emitting one row per bucket, so a release active over a
+ * long window still costs one row. Buckets it reported nothing in stay 0 here, which keeps every
+ * band the same length as the chart's x-axis. Every other figure is derived from the projected
+ * counts, so the table and the chart cannot disagree about a release's volume.
+ */
+export function parseReleaseRows(rawRows: unknown[][], bucketKeys: string[]): ReleaseRow[] {
+ const bucketIndex = new Map(bucketKeys.map((key, index) => [key, index]))
+ return rawRows.map((row) => {
+ const counts = bucketKeys.map(() => 0)
+ for (const pair of (row[3] ?? []) as [unknown, unknown][]) {
+ const index = bucketIndex.get(normalizeBucket(pair[0]))
+ if (index !== undefined) {
+ counts[index] += Number(pair[1] ?? 0)
+ }
+ }
+ return {
+ namespace: emptyToNull(row[0]),
+ version: emptyToNull(row[1]),
+ build: emptyToNull(row[2]),
+ counts,
+ total: counts.reduce((sum, count) => sum + count, 0),
+ }
+ })
+}
+
+/** One value of the property being broken down, with every release row that reported it. */
+interface BandGroup {
+ key: string
+ label: string
+ filters: BandFilter[]
+ rows: ReleaseRow[]
+}
+
+interface MergedCounts {
+ counts: number[]
+ total: number
+}
+
+function mergeRows(rows: ReleaseRow[], bucketCount: number): MergedCounts {
+ const counts = Array.from({ length: bucketCount }, () => 0)
+ for (const row of rows) {
+ row.counts.forEach((count, index) => {
+ counts[index] += count
+ })
+ }
+ return { counts, total: counts.reduce((sum, count) => sum + count, 0) }
+}
+
+/**
+ * Rank the groups, give the busiest their own band, and fold the rest into one. A group that stands
+ * for "the property was not set" keeps its filters, because filtering down to it is the point of
+ * showing it; the folded band cannot be filtered, so it carries none.
+ */
+/** Prefix that no grouped value can produce, so a band named "other" cannot collide with the fold. */
+const SYNTHETIC_KEY = '\0band:'
+
+function foldBands(
+ named: BandGroup[],
+ unset: BandGroup | null,
+ bucketKeys: string[],
+ palette: string[],
+ otherNoun: string,
+ truncated: boolean
+): ExceptionBreakdown {
+ const bucketCount = bucketKeys.length
+ const ranked = [...named]
+ .map((group) => ({ group, merged: mergeRows(group.rows, bucketCount) }))
+ .sort((a, b) => b.merged.total - a.merged.total)
+ const visible = ranked.slice(0, MAX_VISIBLE_BANDS)
+ const hidden = ranked.slice(MAX_VISIBLE_BANDS)
+ const unsetMerged = unset ? mergeRows(unset.rows, bucketCount) : null
+ const total = ranked.reduce((sum, { merged }) => sum + merged.total, 0) + (unsetMerged?.total ?? 0)
+ const share = (value: number): number => (total > 0 ? (value / total) * 100 : 0)
+
+ const bands: ExceptionBand[] = visible.map(({ group, merged }, index) => ({
+ key: group.key,
+ label: group.label,
+ color: palette[index % palette.length],
+ counts: merged.counts,
+ total: merged.total,
+ share: share(merged.total),
+ filters: group.filters,
+ }))
+
+ if (hidden.length > 0) {
+ const merged = mergeRows(
+ hidden.flatMap(({ group }) => group.rows),
+ bucketCount
+ )
+ bands.push({
+ key: `${SYNTHETIC_KEY}other`,
+ label: formatReleaseCount(hidden.length, `other ${otherNoun}`, truncated),
+ color: UNATTRIBUTED_RELEASE_COLOR,
+ counts: merged.counts,
+ total: merged.total,
+ share: share(merged.total),
+ filters: null,
+ })
+ }
+
+ if (unset && unsetMerged && unset.rows.length > 0) {
+ bands.push({
+ key: unset.key,
+ label: unset.label,
+ color: UNATTRIBUTED_RELEASE_COLOR,
+ counts: unsetMerged.counts,
+ total: unsetMerged.total,
+ share: share(unsetMerged.total),
+ filters: unset.filters,
+ })
+ }
+
+ return { bands, groupCount: named.length, groupCountTruncated: truncated, total }
+}
+
+/**
+ * Exceptions split by release.
+ *
+ * A release is identified by app namespace, version, and build together, matching the issue page's
+ * releases panel, so the same version shipped by two apps stays two releases.
+ */
+export function buildReleaseBreakdown(rows: ReleaseRow[], bucketKeys: string[], palette: string[]): ExceptionBreakdown {
+ const multipleApps = new Set(rows.filter((row) => row.version !== null).map((row) => row.namespace)).size > 1
+ // A row carrying only a namespace has no release. The Releases tile counts releases the same way
+ // (queries.ts, HAS_RELEASE), so the tile and this panel report the same number.
+ const named: BandGroup[] = rows
+ .filter((row) => row.version !== null)
+ .map((row) => {
+ const version = formatReleaseVersion(row)
+ return {
+ key: [row.namespace ?? '', row.version ?? '', row.build ?? ''].join('\0'),
+ label: multipleApps && row.namespace ? `${row.namespace} · ${version}` : version,
+ filters: [
+ { key: '$app_namespace', value: row.namespace },
+ { key: '$app_version', value: row.version },
+ { key: '$app_build', value: row.build },
+ ],
+ rows: [row],
+ }
+ })
+ const unattributed = rows.filter((row) => row.version === null)
+ return foldBands(
+ named,
+ {
+ key: `${SYNTHETIC_KEY}unattributed`,
+ label: 'No release data',
+ filters: [
+ { key: '$app_namespace', value: null },
+ { key: '$app_version', value: null },
+ { key: '$app_build', value: null },
+ ],
+ rows: unattributed,
+ },
+ bucketKeys,
+ palette,
+ 'release',
+ rows.length >= MAX_RELEASE_ROWS
+ )
+}
+
+/**
+ * Exceptions split by app, folded from the same release rows rather than a query of their own, so the
+ * two panels can never disagree about the period's totals.
+ */
+export function buildAppBreakdown(rows: ReleaseRow[], bucketKeys: string[], palette: string[]): ExceptionBreakdown {
+ const byNamespace = new Map<string, ReleaseRow[]>()
+ for (const row of rows) {
+ if (row.namespace === null) {
+ continue
+ }
+ const existing = byNamespace.get(row.namespace)
+ if (existing) {
+ existing.push(row)
+ } else {
+ byNamespace.set(row.namespace, [row])
+ }
+ }
+ const named: BandGroup[] = [...byNamespace.entries()].map(([namespace, namespaceRows]) => ({
+ key: namespace,
+ label: namespace,
+ filters: [{ key: '$app_namespace', value: namespace }],
+ rows: namespaceRows,
+ }))
+ return foldBands(
+ named,
+ {
+ key: `${SYNTHETIC_KEY}unattributed`,
+ label: 'No app data',
+ filters: [{ key: '$app_namespace', value: null }],
+ rows: rows.filter((row) => row.namespace === null),
+ },
+ bucketKeys,
+ palette,
+ 'app',
+ rows.length >= MAX_RELEASE_ROWS
+ )
+}
diff --git a/products/error_tracking/package.json b/products/error_tracking/package.json
index b27d7ea30d06..587a76729a5b 100644
--- a/products/error_tracking/package.json
+++ b/products/error_tracking/package.json
@@ -6,6 +6,7 @@
},
"dependencies": {
"@posthog/quill-charts": "workspace:*",
+ "@posthog/quill-components": "workspace:*",
"kea": "catalog:",
"kea-forms": "catalog:",
"kea-loaders": "catalog:",
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
index 27a20f7fada0..69420ce2d557 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsToolDetail.tsx
@@ -31,6 +31,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { formatBucketLabel } from 'lib/utils/timeBuckets'
import { PersonDisplay } from 'scenes/persons/PersonDisplay'
import { teamLogic } from 'scenes/teamLogic'
@@ -54,7 +55,6 @@ import {
mcpAnalyticsToolDetailLogic,
} from './mcpAnalyticsToolDetailLogic'
import { mcpToolQualityUrlWithDates } from './mcpAnalyticsToolQualityLogic'
-import { formatBucketLabel } from './timeBuckets'
import { CreateFixTaskButton } from './tool-quality/CreateFixTaskButton'
import { type MCPErrorContext, formatErrorContext, mcpSessionUrl } from './tool-quality/errorContext'
diff --git a/products/mcp_analytics/frontend/components/McpIntervalFilter.tsx b/products/mcp_analytics/frontend/components/McpIntervalFilter.tsx
index cd4272a23dc8..2446921483a7 100644
--- a/products/mcp_analytics/frontend/components/McpIntervalFilter.tsx
+++ b/products/mcp_analytics/frontend/components/McpIntervalFilter.tsx
@@ -1,8 +1,8 @@
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@posthog/quill-primitives'
-import { IntervalType } from '~/types'
+import { type IntervalOption } from 'lib/utils/timeBuckets'
-import { type IntervalOption } from '../timeBuckets'
+import { IntervalType } from '~/types'
interface McpIntervalFilterProps {
interval: IntervalType
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
index e0db4a44a02b..473adc1d1ee4 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolDetailLogic.ts
@@ -5,6 +5,13 @@ import { urlToAction } from 'kea-router'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { dateFilterToText, dateStringToDayJs } from 'lib/utils/dateFilters'
+import {
+ buildBucketKeys,
+ lastBucketIsInProgress,
+ normalizeBucket,
+ parseIntervalParam,
+ resolveInterval,
+} from 'lib/utils/timeBuckets'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -22,14 +29,6 @@ import {
NodeKind,
} from '~/queries/schema/schema-general'
import { IntervalType } from '~/types'
-
-import {
- buildBucketKeys,
- lastBucketIsInProgress,
- normalizeBucket,
- parseIntervalParam,
- resolveInterval,
-} from './timeBuckets'
export interface ToolSummary {
calls: number
errors: number
diff --git a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
index 70afb51a5335..72f485838918 100644
--- a/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
+++ b/products/mcp_analytics/frontend/mcpAnalyticsToolQualityLogic.ts
@@ -4,6 +4,15 @@ import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { dateFilterToText } from 'lib/utils/dateFilters'
+import {
+ type IntervalOption,
+ buildBucketKeys,
+ intervalOptionsForWindow,
+ lastBucketIsInProgress,
+ normalizeBucket,
+ parseIntervalParam,
+ resolveInterval,
+} from 'lib/utils/timeBuckets'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -17,16 +26,6 @@ import {
} from '~/queries/schema/schema-general'
import { IntervalType } from '~/types'
-import {
- type IntervalOption,
- buildBucketKeys,
- intervalOptionsForWindow,
- lastBucketIsInProgress,
- normalizeBucket,
- parseIntervalParam,
- resolveInterval,
-} from './timeBuckets'
-
export interface CategoryCount {
category: string
calls: number
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
index 6bb980b0c514..6c46acadbd61 100644
--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts
@@ -5,6 +5,7 @@ import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
+import { BUCKET_FORMAT } from 'lib/utils/timeBuckets'
import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
@@ -16,7 +17,6 @@ import {
type BucketRow,
buildDailyActivity,
buildKPIs,
- buildKpiWindow,
buildToolDailySeries,
deltaPct,
mcpDashboardOverviewLogic,
@@ -24,7 +24,6 @@ import {
type SessionRow,
type ToolDailyRow,
} from './mcpDashboardOverviewLogic'
-import { BUCKET_FORMAT } from './timeBuckets'
jest.mock('lib/api')
jest.mock('./generated/api', () => ({
@@ -220,44 +219,6 @@ describe('mcpDashboardOverviewLogic', () => {
})
})
- describe('buildKpiWindow', () => {
- it.each([
- ['2024-01-08', '2024-01-15', 'day', '2024-01-08 00:00:00', '2023-12-31'],
- ['2024-01-01', '2024-01-31', 'day', '2024-01-01 00:00:00', '2023-12-01'],
- ])(
- 'extends [%s, %s] back to an equal-length prior window with cutoff at the selected start',
- (dateFrom, dateTo, interval, expectedCutoff, expectedPriorStart) => {
- const window = buildKpiWindow({ dateFrom, dateTo }, 'UTC', interval as 'day')
- expect(window.currentStartBucket).toBe(expectedCutoff)
- expect(dayjs(window.dateFrom).format('YYYY-MM-DD')).toBe(expectedPriorStart)
- }
- )
-
- it('rolls an hour-level range from now and steps the prior window back equally', () => {
- jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:30:00Z'))
- try {
- // "-1h" resolves to the trailing hour; prior window is the hour before that.
- const window = buildKpiWindow({ dateFrom: '-1h', dateTo: null }, 'UTC', 'minute')
- expect(window.currentStartBucket).toBe('2026-06-18 11:30:00')
- expect(dayjs(window.dateFrom).toISOString()).toBe('2026-06-18T10:29:00.000Z')
- } finally {
- jest.useRealTimers()
- }
- })
-
- it('resolves the relative -7d default against now', () => {
- jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))
- try {
- const window = buildKpiWindow({ dateFrom: '-7d', dateTo: null }, 'UTC', 'day')
- expect(window.currentStartBucket).toBe('2026-06-11 00:00:00')
- // doubled window: prior 8 day-buckets before the cutoff
- expect(dayjs(window.dateFrom).format('YYYY-MM-DD')).toBe('2026-06-03')
- } finally {
- jest.useRealTimers()
- }
- })
- })
-
describe('buildKPIs', () => {
it('splits current vs prior buckets and computes values, deltas, and sparklines', () => {
const rows: BucketRow[] = [
diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
index 9801102aaf83..424e5029a8c5 100644
--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts
@@ -5,6 +5,13 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'
import { getDefaultInterval } from 'lib/utils/dateFilters'
+import {
+ type ComparisonWindow,
+ buildBucketKeys,
+ buildComparisonWindow,
+ lastBucketIsInProgress,
+ normalizeBucket,
+} from 'lib/utils/timeBuckets'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -21,7 +28,6 @@ import { AnyPropertyFilter, IntervalType, TeamType } from '~/types'
import type { TeamPublicType } from '../../../frontend/src/types'
import { mcpClusteringLogic } from './clustering/mcpClusteringLogic'
import type { MCPIntentClusterApi } from './generated/api.schemas'
-import { BUCKET_FORMAT, buildBucketKeys, lastBucketIsInProgress, normalizeBucket, resolveWindow } from './timeBuckets'
export interface DateFilter {
dateFrom: string | null
@@ -267,9 +273,8 @@ export function deltaPct(current: number, previous: number): number | null {
return ((current - previous) / previous) * 100
}
-// Window resolution, bucket keys, and the BUCKET_FORMAT contract are shared with the tab/detail
-// surfaces — see ./timeBuckets. The dashboard adds only the KPI-comparison window below, built on
-// those shared primitives.
+// Window resolution, bucket keys, the comparison window, and the bucket-key format are shared with the
+// tab and detail surfaces. See lib/utils/timeBuckets.
// Project the daily success/error rows onto the full set of buckets, defaulting empty buckets to 0.
export function buildDailyActivity(rows: ActivityRow[], bucketKeys: string[]): DailyActivity {
@@ -281,35 +286,11 @@ export function buildDailyActivity(rows: ActivityRow[], bucketKeys: string[]): D
}
}
-export interface KpiWindow {
- dateFrom: string
- dateTo: string
- currentStartBucket: string
-}
-
-// Extend the resolved window back by an equal number of `interval` buckets so a
-// single query returns both the selected period and its prior period.
-// `currentStartBucket` is the cutoff `buildKPIs` splits on — formatted to match
-// dateTrunc's DateTime output.
-export function buildKpiWindow(dateFilter: DateFilter, timezone: string, interval: IntervalType): KpiWindow {
- const { start, end } = resolveWindow(dateFilter.dateFrom, dateFilter.dateTo, timezone)
- // The selected period covers the inclusive buckets [start, end] — one more than
- // end.diff(start). Step the prior window back by that same count so the two
- // halves of the comparison span an equal number of buckets.
- const selectedBuckets = Math.max(1, end.diff(start, interval) + 1)
- const priorStart = start.subtract(selectedBuckets, interval)
- return {
- dateFrom: priorStart.toISOString(),
- dateTo: end.toISOString(),
- currentStartBucket: start.startOf(interval).format(BUCKET_FORMAT),
- }
-}
-
// Merge the dashboard's active filters with a doubled comparison window's date range.
// Shared by the KPI and Users loaders so both tiles are scoped to the exact same window —
// the tile-parity the reload test asserts. Keep the two loaders reading from here so the
// window/filter plumbing can't drift between them.
-function kpiWindowFilters(queryFilters: HogQLFilters, kpiWindow: KpiWindow): HogQLFilters {
+function kpiWindowFilters(queryFilters: HogQLFilters, kpiWindow: ComparisonWindow): HogQLFilters {
return { ...queryFilters, dateRange: { date_from: kpiWindow.dateFrom, date_to: kpiWindow.dateTo } }
}
@@ -662,7 +643,12 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([
{
loadKPIs: async (_: void, breakpoint) => {
const { interval } = values
- const kpiWindow = buildKpiWindow(values.dateFilter, values.timezone, interval)
+ const kpiWindow = buildComparisonWindow(
+ values.dateFilter.dateFrom,
+ values.dateFilter.dateTo,
+ values.timezone,
+ interval
+ )
const response = (await api.query({
kind: NodeKind.HogQLQuery,
query: KPI_QUERY.replace('__BUCKET__', bucketExpr(interval)),
@@ -679,12 +665,17 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([
{
loadUsers: async (_: void, breakpoint): Promise<KPIMetric> => {
const { interval, timezone } = values
- const kpiWindow = buildKpiWindow(values.dateFilter, timezone, interval)
+ const kpiWindow = buildComparisonWindow(
+ values.dateFilter.dateFrom,
+ values.dateFilter.dateTo,
+ timezone,
+ interval
+ )
// Split the doubled window at the selected period's start. currentStartBucket is
- // interval-aligned (buildKpiWindow → start.startOf(interval)), so comparing the raw
+ // interval-aligned (buildComparisonWindow truncates to the bucket start), so comparing the raw
// `timestamp` against toDateTime(bucket, tz) lands on the same instant as the KPI
// tiles' dateTrunc bucket-string split — keeping this count consistent with them.
- // (For rolling sub-day ranges the two halves can differ by up to one interval, the
+ // (For rolling sub-day ranges the two halves can differ by up to two intervals, the
// same bounded skew the KPI tiles already carry; splitting on the raw start instead
// would equalize the halves but desync Users from the other tiles, so don't.)
const curStart = `toDateTime('${kpiWindow.currentStartBucket}', '${timezone}')`