:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp-analytics): span chart x-axis across the full date range (#64777)
Sam Pennington49d50b493d1b
diff --git a/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx b/products/mcp_analytics/frontend/dashboard/ActivityChart.tsxindex f7534f364369..b0751c93bb9f 100644--- a/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ActivityChart.tsx@@ -48,7 +48,7 @@ export function ActivityChart({<Card className="flex flex-1 flex-col" title="Tool calls and errors"><CardStateloading={loading}- isEmpty={daily.labels.length === 0}+ isEmpty={daily.successes.every((v) => v === 0) && daily.errors.every((v) => v === 0)}skeleton={<Skeleton className="min-h-[300px] flex-1" />}empty={<div className="flex flex-1 items-center justify-center py-6 text-center text-[12px] text-secondary">diff --git a/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx b/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsxindex 46c6f971b351..6905fa0abe0c 100644--- a/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx+++ b/products/mcp_analytics/frontend/dashboard/ToolUsageChart.tsx@@ -51,7 +51,7 @@ export function ToolUsageChart({<Card title="Tool call breakdown"><CardStateloading={loading}- isEmpty={data.labels.length === 0}+ isEmpty={data.tools.length === 0}skeleton={<Skeleton className="h-[260px] w-full" />}empty={<div className="py-6 text-center text-[12px] text-secondary">No tool calls yet.</div>}>diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.tsindex 73f2e39f0442..10516da85f35 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.test.ts@@ -8,8 +8,11 @@ import { dayjs } from 'lib/dayjs'import { initKeaTests } from '~/test/init'import {+ type ActivityRow,aggregateHarnessRows,type BucketRow,+ buildBucketKeys,+ buildDailyActivity,buildKPIs,buildKpiWindow,buildToolDailySeries,@@ -17,6 +20,7 @@ import {deltaPct,type HarnessRawRow,mcpDashboardOverviewLogic,+ normalizeBucket,pickNotableSessions,type SessionRow,type ToolDailyRow,@@ -144,6 +148,97 @@ describe('mcpDashboardOverviewLogic', () => {// Other = tool-8 (92) + tool-9 (91)expect(tools[8]).toEqual({ tool: 'Other', data: [183] })})++ it('spans the supplied bucket keys and zero-fills days without calls', () => {+ const rows: ToolDailyRow[] = [{ day: '2024-01-02', tool: 'a', calls: 5 }]+ const bucketKeys = ['2024-01-01', '2024-01-02', '2024-01-03']+ expect(buildToolDailySeries(rows, bucketKeys)).toEqual({+ labels: bucketKeys,+ tools: [{ tool: 'a', data: [0, 5, 0] }],+ })+ })++ it('returns empty tools with the supplied labels when there are no rows', () => {+ expect(buildToolDailySeries([], ['2024-01-01'])).toEqual({ labels: ['2024-01-01'], tools: [] })+ })+ })++ describe('buildBucketKeys', () => {+ it('emits one key per day across the resolved window, including empty trailing days', () => {+ jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))+ try {+ expect(buildBucketKeys({ dateFrom: '-7d', dateTo: null }, 'UTC', 'day')).toEqual([+ '2026-06-11 00:00:00',+ '2026-06-12 00:00:00',+ '2026-06-13 00:00:00',+ '2026-06-14 00:00:00',+ '2026-06-15 00:00:00',+ '2026-06-16 00:00:00',+ '2026-06-17 00:00:00',+ '2026-06-18 00:00:00',+ ])+ } finally {+ jest.useRealTimers()+ }+ })++ it('truncates weekly buckets to ISO Monday starts (matching ClickHouse dateTrunc)', () => {+ // 2026-06-01 is a Monday; every key should land on a Monday.+ const keys = buildBucketKeys({ dateFrom: '2026-06-01', dateTo: '2026-06-21' }, 'UTC', 'week')+ expect(keys).toEqual(['2026-06-01 00:00:00', '2026-06-08 00:00:00', '2026-06-15 00:00:00'])+ })+ })++ describe('buildDailyActivity', () => {+ it('projects rows onto the bucket keys, defaulting missing buckets to zero', () => {+ const rows: ActivityRow[] = [+ { day: '2024-01-01 00:00:00', successes: 10, errors: 2 },+ { day: '2024-01-03 00:00:00', successes: 4, errors: 1 },+ ]+ const bucketKeys = ['2024-01-01 00:00:00', '2024-01-02 00:00:00', '2024-01-03 00:00:00']+ expect(buildDailyActivity(rows, bucketKeys)).toEqual({+ labels: bucketKeys,+ successes: [10, 0, 4],+ errors: [2, 0, 1],+ })+ })++ it('returns all-zero series when there are no rows', () => {+ const bucketKeys = ['2024-01-01 00:00:00', '2024-01-02 00:00:00', '2024-01-03 00:00:00']+ expect(buildDailyActivity([], bucketKeys)).toEqual({+ labels: bucketKeys,+ successes: [0, 0, 0],+ errors: [0, 0, 0],+ })+ })+ })++ describe('normalizeBucket', () => {+ // The query API serializes dateTrunc buckets as ISO datetimes; they must come back in the+ // same format buildBucketKeys emits, otherwise the zero-fill join misses every bucket.+ it.each([+ ['2026-06-19T00:00:00Z', 'UTC', '2026-06-19 00:00:00'],+ ['2026-06-19T00:00:00+00:00', 'UTC', '2026-06-19 00:00:00'],+ ['2026-06-19T11:30:00Z', 'UTC', '2026-06-19 11:30:00'],+ ])('normalizes %s (%s) to %s', (raw, timezone, expected) => {+ expect(normalizeBucket(raw, timezone)).toBe(expected)+ })++ it('returns empty string for missing values', () => {+ expect(normalizeBucket(null, 'UTC')).toBe('')+ expect(normalizeBucket('', 'UTC')).toBe('')+ })++ it('produces keys that match buildBucketKeys so the activity join lands', () => {+ jest.useFakeTimers().setSystemTime(new Date('2026-06-18T12:00:00Z'))+ try {+ const bucketKeys = buildBucketKeys({ dateFrom: '-7d', dateTo: null }, 'UTC', 'day')+ const normalized = normalizeBucket('2026-06-18T00:00:00Z', 'UTC')+ expect(bucketKeys).toContain(normalized)+ } finally {+ jest.useRealTimers()+ }+ })})describe('buildKpiWindow', () => {diff --git a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.tsindex 1bd170ac1543..57ce3511e58f 100644--- a/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts+++ b/products/mcp_analytics/frontend/mcpDashboardOverviewLogic.ts@@ -293,9 +293,12 @@ export function aggregateHarnessRows(raw: HarnessRawRow[]): HarnessRow[] {const TOOL_SERIES_LIMIT = 8// Pivot flat (day, tool, calls) rows into a label array + one data series per tool, tools ordered-// by total volume (biggest first) so the stack and legend read consistently.-export function buildToolDailySeries(rows: ToolDailyRow[]): ToolDailySeries {- const days = [...new Set(rows.map((r) => r.day))].sort()+// by total volume (biggest first) so the stack and legend read consistently. When `bucketKeys` is+// supplied the labels span the full selected window (zero-filling empty buckets) so the x-axis+// matches the date range instead of collapsing to the days that happened to have calls; without it+// the labels fall back to the days present in the rows (a plain pivot, used in tests).+export function buildToolDailySeries(rows: ToolDailyRow[], bucketKeys?: string[]): ToolDailySeries {+ const days = bucketKeys ?? [...new Set(rows.map((r) => r.day))].sort()const totalByTool = new Map<string, number>()const byToolDay = new Map<string, Map<string, number>>()for (const row of rows) {@@ -340,6 +343,49 @@ function resolveWindow(dateFilter: DateFilter, timezone: string): { start: dayjsreturn { start, end }}+// Truncate to the start of an interval bucket the same way ClickHouse's dateTrunc does, so the keys+// we generate line up with the query's bucket strings. dayjs' startOf covers minute/hour/day/month;+// only 'week' differs — dateTrunc('week') is ISO (Monday-start) while dayjs defaults to Sunday.+function startOfBucket(d: dayjs.Dayjs, interval: IntervalType): dayjs.Dayjs {+ if (interval === 'week') {+ const day = d.day() // 0 = Sunday … 6 = Saturday+ return d.startOf('day').subtract((day + 6) % 7, 'day')+ }+ return d.startOf(interval)+}++// Every bucket key across the resolved window [start, end] at the active interval, formatted to+// match dateTrunc's DateTime output ('YYYY-MM-DD HH:mm:ss'). The activity and tool-usage series are+// zero-filled against these so the x-axis spans the whole selected range instead of clipping to the+// buckets that happened to have events.+export function buildBucketKeys(dateFilter: DateFilter, timezone: string, interval: IntervalType): string[] {+ const { start, end } = resolveWindow(dateFilter, timezone)+ const last = startOfBucket(end, interval).valueOf()+ const keys: string[] = []+ let cursor = startOfBucket(start, interval)+ // Bounded dashboard windows keep this small; the cap is just a guard against a pathological range.+ for (let i = 0; cursor.valueOf() <= last && i < 100000; i++) {+ keys.push(cursor.format('YYYY-MM-DD HH:mm:ss'))+ cursor = cursor.add(1, interval)+ }+ return keys+}++export function normalizeBucket(raw: unknown, timezone: string): string {+ const s = String(raw ?? '')+ return s ? dayjs(s).tz(timezone).format('YYYY-MM-DD HH:mm:ss') : ''+}++// 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 {+ const byDay = new Map(rows.map((r) => [r.day, r]))+ return {+ labels: bucketKeys,+ successes: bucketKeys.map((k) => byDay.get(k)?.successes ?? 0),+ errors: bucketKeys.map((k) => byDay.get(k)?.errors ?? 0),+ }+}+export interface KpiWindow {dateFrom: stringdateTo: string@@ -548,7 +594,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([breakpoint()const raw = (response?.results as unknown[][]) ?? []return raw.map((r) => ({- day: String(r[0] ?? ''),+ day: normalizeBucket(r[0], values.timezone),successes: Number(r[1] ?? 0),errors: Number(r[2] ?? 0),}))@@ -567,7 +613,7 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([breakpoint()const raw = (response?.results as unknown[][]) ?? []return raw.map((r) => ({- day: String(r[0] ?? ''),+ day: normalizeBucket(r[0], values.timezone),tool: String(r[1] ?? ''),calls: Number(r[2] ?? 0),}))@@ -593,18 +639,19 @@ export const mcpDashboardOverviewLogic = kea<mcpDashboardOverviewLogicType>([(s) => [s.dateFilter],(dateFilter: DateFilter): IntervalType => getDefaultInterval(dateFilter.dateFrom, dateFilter.dateTo),],+ bucketKeys: [+ (s) => [s.dateFilter, s.timezone, s.interval],+ (dateFilter: DateFilter, timezone: string, interval: IntervalType): string[] =>+ buildBucketKeys(dateFilter, timezone, interval),+ ],harnessRows: [(s) => [s.harnessRawRows], (raw: HarnessRawRow[]): HarnessRow[] => aggregateHarnessRows(raw)],dailyActivity: [- (s) => [s.activityRows],- (rows: ActivityRow[]): DailyActivity => ({- labels: rows.map((r) => r.day),- successes: rows.map((r) => r.successes),- errors: rows.map((r) => r.errors),- }),+ (s) => [s.activityRows, s.bucketKeys],+ (rows: ActivityRow[], bucketKeys: string[]): DailyActivity => buildDailyActivity(rows, bucketKeys),],toolDailySeries: [- (s) => [s.toolDailyRows],- (rows: ToolDailyRow[]): ToolDailySeries => buildToolDailySeries(rows),+ (s) => [s.toolDailyRows, s.bucketKeys],+ (rows: ToolDailyRow[], bucketKeys: string[]): ToolDailySeries => buildToolDailySeries(rows, bucketKeys),],notableSessions: [(s) => [s.sessionRows],