: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
refactor(insights): drill into trends results by the query series (#116862)
Thomas Obermüllerf9879f71e155
diff --git a/frontend/src/queries/nodes/InsightViz/exportAdapters.test.ts b/frontend/src/queries/nodes/InsightViz/exportAdapters.test.tsindex a0029bd28df6..a2701c7a076a 100644--- a/frontend/src/queries/nodes/InsightViz/exportAdapters.test.ts+++ b/frontend/src/queries/nodes/InsightViz/exportAdapters.test.ts@@ -1,4 +1,10 @@-import { EventsHeatMapDataResult, InsightVizNode, NodeKind, TrendsQueryResponse } from '~/queries/schema/schema-general'+import {+ AnyEntityNode,+ EventsHeatMapDataResult,+ InsightVizNode,+ NodeKind,+ TrendsQueryResponse,+} from '~/queries/schema/schema-general'import {CalendarHeatmapAdapter,@@ -272,22 +278,38 @@ describe('insight export adapters', () => {])})- it('uses custom_name when available', () => {+ it.each<[string, AnyEntityNode, string]>([+ [+ 'a custom name',+ { kind: NodeKind.EventsNode, event: 'pageview', custom_name: 'Page Views' },+ 'Page Views',+ ],+ ['a name other than the event', { kind: NodeKind.EventsNode, event: 'pageview', name: 'Views' }, 'Views'],+ [+ 'the label when the name matches it',+ { kind: NodeKind.EventsNode, event: 'pageview', name: 'pageview' },+ 'pageview',+ ],+ ])('names the series by %s', (_, node, expected) => {const response: TrendsQueryResponse = {results: [{label: 'pageview',- action: { custom_name: 'Page Views' } as any,+ order: 0,data: [10, 15],labels: ['2024-01-01', '2024-01-02'],},],}+ const renamedQuery: InsightVizNode = {+ kind: NodeKind.InsightVizNode,+ source: { kind: NodeKind.TrendsQuery, series: [node] },+ }- const adapter = new TrendsAdapter(response, trendsQuery)+ const adapter = new TrendsAdapter(response, renamedQuery)const result = adapter.toTableData()- expect(result[0]).toEqual(['Date', 'Page Views'])+ expect(result[0]).toEqual(['Date', expected])})it('includes compare_label when present', () => {diff --git a/frontend/src/queries/nodes/InsightViz/exportAdapters.ts b/frontend/src/queries/nodes/InsightViz/exportAdapters.tsindex ddfffc3af004..dffad7d923d8 100644--- a/frontend/src/queries/nodes/InsightViz/exportAdapters.ts+++ b/frontend/src/queries/nodes/InsightViz/exportAdapters.ts@@ -3,6 +3,8 @@ import Papa from 'papaparse'import { lemonToast } from '@posthog/lemon-ui'import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { ensureStringIsNotBlank } from 'lib/utils/strings'+import { getResultSeries } from 'scenes/insights/utils/resultSeries'import {EventsHeatMapColumnAggregationResult,@@ -224,13 +226,29 @@ export class TrendsAdapter implements ExportAdapter {) {}private getSeriesLabel(series: Record<string, any>): string {- // Use breakdown value if available, otherwise use action name or label+ // Use breakdown value if available, otherwise use the series rename or labelconst breakdownValue = series.breakdown_value- const baseName = breakdownValue ?? series.action?.custom_name ?? series.label ?? 'Series'+ const baseName = breakdownValue ?? this.getSeriesRename(series) ?? series.label ?? 'Series'const compareLabel = series.compare_labelreturn compareLabel ? `${baseName} (${compareLabel})` : String(baseName)}+ /**+ * The rename the trends runner reports for a series: its `custom_name`, or a `name` other than the series' raw+ * label. Mirrors `resolve_series_custom_name` in `query_runner.py`. A row without a breakdown carries the raw+ * label as its `label`, and a breakdown row is named by its breakdown value instead.+ */+ private getSeriesRename(series: Record<string, any>): string | null {+ const source = this.query?.kind === NodeKind.InsightVizNode ? (this.query as InsightVizNode).source : null+ const node = getResultSeries(isTrendsQuery(source) ? source : null, series).node+ const customName = ensureStringIsNotBlank(node?.custom_name)+ if (customName) {+ return customName+ }+ const name = ensureStringIsNotBlank(node?.name)+ return name && name !== series.label ? name : null+ }+// Value-aggregated displays (bold number, pie, total value bar) return a single number per// series and no date axis, so the table is one row per series instead of one row per date.private getAggregateTableData(): string[][] {diff --git a/frontend/src/queries/nodes/WebVitals/WebVitals.tsx b/frontend/src/queries/nodes/WebVitals/WebVitals.tsxindex 327a144a6023..afec3130df97 100644--- a/frontend/src/queries/nodes/WebVitals/WebVitals.tsx+++ b/frontend/src/queries/nodes/WebVitals/WebVitals.tsx@@ -58,20 +58,20 @@ export function WebVitals(props: {const webVitalsQueryResponse = responseLoading ? undefined : (response as WebVitalsQueryResponse | undefined)const INP = useMemo(- () => getMetric(webVitalsQueryResponse?.results, 'INP', webVitalsPercentile),- [webVitalsQueryResponse, webVitalsPercentile]+ () => getMetric(webVitalsQueryResponse?.results, props.query.source, 'INP', webVitalsPercentile),+ [webVitalsQueryResponse, props.query.source, webVitalsPercentile])const LCP = useMemo(- () => getMetric(webVitalsQueryResponse?.results, 'LCP', webVitalsPercentile),- [webVitalsQueryResponse, webVitalsPercentile]+ () => getMetric(webVitalsQueryResponse?.results, props.query.source, 'LCP', webVitalsPercentile),+ [webVitalsQueryResponse, props.query.source, webVitalsPercentile])const CLS = useMemo(- () => getMetric(webVitalsQueryResponse?.results, 'CLS', webVitalsPercentile),- [webVitalsQueryResponse, webVitalsPercentile]+ () => getMetric(webVitalsQueryResponse?.results, props.query.source, 'CLS', webVitalsPercentile),+ [webVitalsQueryResponse, props.query.source, webVitalsPercentile])const FCP = useMemo(- () => getMetric(webVitalsQueryResponse?.results, 'FCP', webVitalsPercentile),- [webVitalsQueryResponse, webVitalsPercentile]+ () => getMetric(webVitalsQueryResponse?.results, props.query.source, 'FCP', webVitalsPercentile),+ [webVitalsQueryResponse, props.query.source, webVitalsPercentile])return (@@ -116,7 +116,11 @@ export function WebVitals(props: {</div><div className="flex flex-col sm:flex-row gap-2">- <WebVitalsContent webVitalsQueryResponse={webVitalsQueryResponse} isLoading={responseLoading} />+ <WebVitalsContent+ webVitalsQueryResponse={webVitalsQueryResponse}+ querySource={props.query.source}+ isLoading={responseLoading}+ /><div className="flex flex-col flex-1 bg-surface-primary rounded border p-4"><Querykey={webVitalsTab}diff --git a/frontend/src/queries/nodes/WebVitals/WebVitalsContent.tsx b/frontend/src/queries/nodes/WebVitals/WebVitalsContent.tsxindex d897cb03f403..2a4e8e02fa89 100644--- a/frontend/src/queries/nodes/WebVitals/WebVitalsContent.tsx+++ b/frontend/src/queries/nodes/WebVitals/WebVitalsContent.tsx@@ -6,7 +6,7 @@ import { LemonSkeleton, Tooltip } from '@posthog/lemon-ui'import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'-import { WebVitalsQueryResponse } from '~/queries/schema/schema-general'+import { InsightQueryNode, WebVitalsQueryResponse } from '~/queries/schema/schema-general'import {EXPERIENCE_PER_BAND,@@ -25,15 +25,20 @@ import {type WebVitalsContentProps = {webVitalsQueryResponse?: WebVitalsQueryResponse+ querySource: InsightQueryNodeisLoading: boolean}-export const WebVitalsContent = ({ webVitalsQueryResponse, isLoading }: WebVitalsContentProps): JSX.Element => {+export const WebVitalsContent = ({+ webVitalsQueryResponse,+ querySource,+ isLoading,+}: WebVitalsContentProps): JSX.Element => {const { webVitalsTab, webVitalsPercentile } = useValues(webAnalyticsLogic)const value = useMemo(- () => getMetric(webVitalsQueryResponse?.results, webVitalsTab, webVitalsPercentile),- [webVitalsQueryResponse, webVitalsPercentile, webVitalsTab]+ () => getMetric(webVitalsQueryResponse?.results, querySource, webVitalsTab, webVitalsPercentile),+ [webVitalsQueryResponse, querySource, webVitalsPercentile, webVitalsTab])const withMilliseconds = (values: number[]): string =>diff --git a/frontend/src/queries/nodes/WebVitals/__mocks__/WebVitals.json b/frontend/src/queries/nodes/WebVitals/__mocks__/WebVitals.jsonindex 1c35a990862e..a1f9f8205dc5 100644--- a/frontend/src/queries/nodes/WebVitals/__mocks__/WebVitals.json+++ b/frontend/src/queries/nodes/WebVitals/__mocks__/WebVitals.json@@ -177,7 +177,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 0},{"data": [@@ -297,7 +298,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 1},{"data": [@@ -419,7 +421,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 2},{"data": [@@ -541,7 +544,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 3},{"data": [@@ -663,7 +667,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 4},{"data": [@@ -785,7 +790,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 5},{"data": [@@ -907,7 +913,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 6},{"data": [@@ -1029,7 +1036,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 7},{"data": [@@ -1151,7 +1159,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 8},{"data": [@@ -1273,7 +1282,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 9},{"data": [@@ -1395,7 +1405,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 10},{"data": [@@ -1517,7 +1528,8 @@"math_hogql": null,"math_group_type_index": null,"properties": {}- }+ },+ "order": 11}],"timezone": "US/Pacific",diff --git a/frontend/src/queries/nodes/WebVitals/definitions.ts b/frontend/src/queries/nodes/WebVitals/definitions.tsindex c1a9272ed9dc..4bb8d89cfb90 100644--- a/frontend/src/queries/nodes/WebVitals/definitions.ts+++ b/frontend/src/queries/nodes/WebVitals/definitions.ts@@ -3,7 +3,11 @@ import { IconCheckCircle, IconWarning } from '@posthog/icons'import { IconExclamation } from 'lib/lemon-ui/icons'import { WebVitalsPercentile } from 'scenes/web-analytics/common'-import { WebVitalsItem, WebVitalsMetric, WebVitalsMetricBand } from '~/queries/schema/schema-general'+import { InsightQueryNode, WebVitalsItem, WebVitalsMetric, WebVitalsMetricBand } from '~/queries/schema/schema-general'+import type { TrendResult } from '~/types'++/** A web vitals result row. The trends runner gives every row an `order`, which `WebVitalsItem` does not declare. */+export type WebVitalsRow = WebVitalsItem & Pick<TrendResult, 'order'>const PERCENTILE_NAME: Record<WebVitalsPercentile, string> = {p75: '75%',@@ -63,13 +67,18 @@ export const EXPERIENCE_PER_BAND: Record<WebVitalsMetricBand, string> = {}export const getMetric = (- results: WebVitalsItem[] | undefined,+ results: WebVitalsRow[] | undefined,+ querySource: InsightQueryNode | undefined,metric: WebVitalsMetric,percentile: WebVitalsPercentile): number | undefined => {- const data = results- ?.filter((result) => result.action.custom_name === metric) // Filter to the right metric- .find((result) => result.action.math === percentile)?.data // Get the right percentile // Get the actual data array+ // The toolbar bundles this file, so it indexes the query series itself instead of importing+ // `getResultSeries` from `scenes/`. A web vitals query has no formulas, so `order` is always a series index.+ const series = querySource && 'series' in querySource ? querySource.series : []+ const data = results?.find((result) => {+ const node = result.order != null ? series[result.order] : undefined+ return node?.custom_name === metric && node.math === percentile+ })?.dataif (!data || data.length === 0) {return undefineddiff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsxindex dd598ce24a76..f34d8edc17c9 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx@@ -14,6 +14,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { liveEventsHostOrigin } from 'lib/utils/apiHost'import { CATEGORY_LABELS } from 'lib/utils/botDetection'import { ConcurrencyController } from 'lib/utils/concurrencyController'+import { parseDateInTimezone } from 'lib/utils/datetime'import { isAbortedRequest } from 'lib/utils/requests'import { hashCodeForString } from 'lib/utils/strings'import { deduplicateEvents } from 'scenes/activity/live/deduplicateEvents'@@ -769,7 +770,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypeaddUserDataToBuckets(data.usersPageviews, bucketMap)addBreakdownDataToBuckets(data.device, bucketMap, (b) => b.devices)addBreakdownDataToBuckets(data.browser, bucketMap, (b) => b.browsers)- addPathDataToBuckets(data.paths, bucketMap)+ addPathDataToBuckets(data.paths, bucketMap, values.currentTeam?.timezone ?? 'UTC')addReferrerDataToBuckets(data.referrer, bucketMap)addGeoDataToBuckets(data.geo, bucketMap)addCityDataToBuckets(data.city, bucketMap)@@ -1596,14 +1597,17 @@ const addBreakdownDataToBuckets = (const addPathDataToBuckets = (pathsResponse: TrendsQueryResponse | null,- bucketMap: Map<number, SlidingWindowBucket>+ bucketMap: Map<number, SlidingWindowBucket>,+ timezone: string): void => {if (!pathsResponse) {return}for (const result of pathsResponse.results) {for (let i = 0; i < result.data.length; i++) {- const timestamp = Date.parse(result.action.days[i])+ // The trends runner writes `days` as wall-clock times in the project timezone, while the other live+ // queries key buckets by instant.+ const timestamp = parseDateInTimezone(result.days[i], timezone).valueOf()const bucket = getOrCreateBucket(bucketMap, timestamp)const path = result.breakdown_valuediff --git a/frontend/src/scenes/web-analytics/WebAnalyticsExport.test.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsExport.test.tsxindex 9f9b788b82d6..b3d17e75c297 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsExport.test.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsExport.test.tsx@@ -1,5 +1,6 @@import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'+import type { WebVitalsRow } from '~/queries/nodes/WebVitals/definitions'import {DataTableNode,NodeKind,@@ -26,24 +27,32 @@ const webVitalsQuery: WebVitalsQuery = {properties: [],source: {kind: NodeKind.TrendsQuery,- series: [],+ series: (['LCP', 'CLS'] as const).map((metric) => ({+ kind: NodeKind.EventsNode,+ event: '$web_vitals',+ custom_name: metric,+ math: PropertyMathType.P90,+ math_property: `$web_vitals_${metric}_value`,+ })),},}-const webVitalsResponse: WebVitalsQueryResponse = {- results: [- {- action: { custom_name: 'LCP', math: PropertyMathType.P90 },- days: ['2026-09-01', '2026-09-02'],- data: [2400, 2600],- },- {- action: { custom_name: 'CLS', math: PropertyMathType.P90 },- days: ['2026-09-01', '2026-09-02'],- data: [0.04, 0.05],- },- ],-}+const webVitalsRows: WebVitalsRow[] = [+ {+ action: { custom_name: 'LCP', math: PropertyMathType.P90 },+ order: 0,+ days: ['2026-09-01', '2026-09-02'],+ data: [2400, 2600],+ },+ {+ action: { custom_name: 'CLS', math: PropertyMathType.P90 },+ order: 1,+ days: ['2026-09-01', '2026-09-02'],+ data: [0.04, 0.05],+ },+]++const webVitalsResponse: WebVitalsQueryResponse = { results: webVitalsRows }const pathBreakdownQuery: WebVitalsPathBreakdownQuery = {kind: NodeKind.WebVitalsPathBreakdownQuery,diff --git a/frontend/src/scenes/web-analytics/webAnalyticsExportUtils.ts b/frontend/src/scenes/web-analytics/webAnalyticsExportUtils.tsindex e153f54626da..1cd1519b307c 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsExportUtils.ts+++ b/frontend/src/scenes/web-analytics/webAnalyticsExportUtils.ts@@ -4,6 +4,7 @@ import { lemonToast } from '@posthog/lemon-ui'import { downloadFile } from 'lib/utils/dom'import { slugify } from 'lib/utils/strings'+import { getResultSeries } from 'scenes/insights/utils/resultSeries'import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import {@@ -13,7 +14,7 @@ import {getInsightExportAdapter,} from '~/queries/nodes/InsightViz/exportAdapters'import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'-import { GRADE_PER_BAND } from '~/queries/nodes/WebVitals/definitions'+import { GRADE_PER_BAND, WebVitalsRow } from '~/queries/nodes/WebVitals/definitions'import {DataTableNode,NodeKind,@@ -26,6 +27,7 @@ import {WebVitalsMetricBand,WebVitalsPathBreakdownQuery,WebVitalsPathBreakdownQueryResponse,+ WebVitalsQuery,WebVitalsQueryResponse,} from '~/queries/schema/schema-general'import {@@ -100,7 +102,7 @@ export function getExportAdapter(insightDataRaw: unknown, query: QuerySchema | ureturn null}if (isWebVitalsQuery(query)) {- return webVitalsTrendsAdapter(insightDataRaw as WebVitalsQueryResponse)+ return webVitalsTrendsAdapter(insightDataRaw as WebVitalsQueryResponse, query)}if (isWebVitalsPathBreakdownQuery(query)) {return new WebVitalsPathBreakdownAdapter(insightDataRaw as WebVitalsPathBreakdownQueryResponse, query)@@ -284,13 +286,15 @@ function webVitalsColumnName(metric: WebVitalsMetric, percentile: string): strinreturn metric === 'CLS' ? `${metric} ${percentile}` : `${metric} ${percentile} (ms)`}-function webVitalsTrendsAdapter(response: WebVitalsQueryResponse): TrendsAdapter {+function webVitalsTrendsAdapter(response: WebVitalsQueryResponse, query: WebVitalsQuery): TrendsAdapter {return new TrendsAdapter({...response,- results: (response.results ?? []).map((item) => ({- ...item,- action: { ...item.action, custom_name: webVitalsColumnName(item.action.custom_name, item.action.math) },- })),+ results: ((response.results ?? []) as WebVitalsRow[]).map((item) => {+ const node = getResultSeries(query.source, { order: item.order }).node+ return node?.custom_name && node.math+ ? { ...item, label: webVitalsColumnName(node.custom_name as WebVitalsMetric, node.math) }+ : item+ }),})}diff --git a/frontend/src/test/insight-testing/interactions.ts b/frontend/src/test/insight-testing/interactions.tsindex 6493d5d273ca..f7b2b65be03c 100644--- a/frontend/src/test/insight-testing/interactions.ts+++ b/frontend/src/test/insight-testing/interactions.ts@@ -126,12 +126,10 @@ export const legend = {async toggle(label: string): Promise<void> {const props: InsightLogicProps = { dashboardItemId: INSIGHT_TEST_ID }const logic = trendsDataLogic(props)- const dataset = (logic.values.indexedResults as IndexedTrendResult[]).find(- (d) => (d.label ?? d.action?.name) === label- )+ const dataset = (logic.values.indexedResults as IndexedTrendResult[]).find((d) => d.label === label)if (!dataset) {const available = (logic.values.indexedResults as IndexedTrendResult[])- .map((d) => `"${d.label ?? d.action?.name}"`)+ .map((d) => `"${d.label}"`).join(', ')throw new Error(`No series labeled "${label}". Available: ${available}`)}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 8d1edb1044c1..3d74b5b4ea59 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5480,8 +5480,6 @@ export type GraphDataset = Partial<| 'compare'| 'compare_label'| 'status'- | 'action'- | 'actions'| 'order'| 'breakdown_value'| 'persons_urls'@@ -5506,8 +5504,6 @@ export type GraphDataset = Partial<pointValue?: number/** Value (count) for specific data point; only valid in the context of an xy intercept */personUrl?: string- /** Action/event filter defition */- action?: ActionFilter | nullyAxisID?: string}diff --git a/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.ts b/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.tsindex b21cf73918b6..248dd4fd5744 100644--- a/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.ts+++ b/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.ts@@ -1,3 +1,5 @@+import { getResultOrder } from 'scenes/insights/utils/resultSeries'+import { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'import { WebOverviewItem } from '~/queries/schema/schema-general'import { TrendResult } from '~/types'@@ -26,7 +28,7 @@ export function sumTrendSeries(results: TrendResult[] | undefined): { value: num* `value` is undefined when that series returned nothing, which the caller shows as N/A rather* than as a zero it cannot stand behind. */export function seriesTotal(results: TrendResult[] | undefined, order: number): { value?: number; previous?: number } {- const matching = (results ?? []).filter((result) => (result.order ?? result.action?.order ?? 0) === order)+ const matching = (results ?? []).filter((result) => getResultOrder(result) === order)if (!matching.length) {return {}}diff --git a/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts b/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.tsindex eb12066ad931..a9bf85091eb7 100644--- a/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts+++ b/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts@@ -1,4 +1,5 @@import { BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'+import { getResultOrder } from 'scenes/insights/utils/resultSeries'import { TrendResult } from '~/types'@@ -13,8 +14,6 @@ export interface ConversionValueByBreakdown {const TOTAL_ORDER = 0const AVERAGE_ORDER = 1-const seriesOrder = (result: TrendResult): number => result.order ?? result.action?.order ?? 0-/** Trends reports an untagged visit as its own sentinel, while the stats table reports SQL NULL,* which `webStatsRows` reads as an empty string. Both have to land on the same key or the two* halves of a row never meet. */@@ -34,7 +33,7 @@ export function conversionValueRows(results: TrendResult[] | undefined): Map<strconst rows = (results ?? []).filter(// The fold row is an aggregate over values the stats table lists individually, so// merging it would attribute the whole tail to one row.- (result) => seriesOrder(result) === order && result.breakdown_value !== BREAKDOWN_OTHER_STRING_LABEL+ (result) => getResultOrder(result) === order && result.breakdown_value !== BREAKDOWN_OTHER_STRING_LABEL)const current = rows.filter((result) => result.compare_label !== 'previous')const previous = new Map(diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.tsindex 40ab89800efe..10a46517151c 100644--- a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts@@ -1,4 +1,4 @@-import type { AnyResponseType, TrendsQuery } from '~/queries/schema/schema-general'+import type { AnyResponseType, MathType, TrendsQuery } from '~/queries/schema/schema-general'import { NodeKind } from '~/queries/schema/schema-general'import { ChartDisplayType, CompareLabelType } from '~/types'import type { TrendResult } from '~/types'@@ -70,7 +70,10 @@ describe('deriveChartPreview', () => {expect(deriveChartPreview(ChartDisplayType.BoldNumber,- query(ChartDisplayType.ActionsLineGraph, queryOverrides),+ query(ChartDisplayType.ActionsLineGraph, {+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: math as MathType }],+ ...queryOverrides,+ }),response([series({ math })]))).toBeNull()diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.tsindex 7ada7fdafe43..840136b1ec15 100644--- a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts@@ -1,3 +1,5 @@+import { getResultOrder, getResultSeries } from 'scenes/insights/utils/resultSeries'+import type { AnyResponseType, TrendsQuery } from '~/queries/schema/schema-general'import { ChartDisplayType, type TrendResult } from '~/types'@@ -82,7 +84,10 @@ function canSumBuckets(source: TrendsQuery, results: TrendResult[]): boolean {(source.trendsFilter?.smoothingIntervals ?? 1) <= 1 &&// The backend rounds each sampled bucket, so their sum can differ from a sampled total.(source.samplingFactor ?? 1) === 1 &&- results.every((result) => result.action != null && SUMMABLE_MATHS.has(result.action.math ?? 'total'))+ results.every((result) => {+ const math = getResultSeries(source, result).math+ return math != null && SUMMABLE_MATHS.has(math.math ?? 'total')+ }))}@@ -201,7 +206,7 @@ function candidateRows(}function seriesKey(result: TrendResult): string {- return JSON.stringify([result.order ?? result.action?.order, result.breakdown_value])+ return JSON.stringify([getResultOrder(result), result.breakdown_value])}// Keeps whole series, so a comparison keeps the previous-period row of each series it shows.diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewSamples.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewSamples.tsindex 271e741f881e..4636e7c0d26c 100644--- a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewSamples.ts+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewSamples.ts@@ -16,12 +16,12 @@ const SAMPLE_COUNTRIES: [string, number][] = [const SAMPLE_BOX_PLOT_DAYS = 7-function sampleAction(result: TrendResult | undefined): Pick<TrendResult, 'action' | 'label'> {- return { action: result?.action ?? null, label: result?.label ?? 'Sample' }+function sampleSeries(result: TrendResult | undefined): Pick<TrendResult, 'order' | 'label'> {+ return { order: result?.order, label: result?.label ?? 'Sample' }}export function sampleWorldMapRows(loaded: TrendResult[]): unknown[] {- const base = sampleAction(loaded[0])+ const base = sampleSeries(loaded[0])return SAMPLE_COUNTRIES.map(([code, value]) => ({...base,breakdown_value: code,@@ -51,7 +51,7 @@ export function sampleCalendarHeatmapRows(loaded: TrendResult[]): unknown[] {}return [{- ...sampleAction(loaded[0]),+ ...sampleSeries(loaded[0]),data: [],days: [],labels: [],diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/handleStickinessChartClick.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/handleStickinessChartClick.tsxindex 1946317a6684..ec59f7cc5ccd 100644--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/handleStickinessChartClick.tsx+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/handleStickinessChartClick.tsx@@ -29,7 +29,7 @@ export function handleStickinessChartClick(seriesKey: string, dataIndex: number,return}- const day = dataset.action?.days?.[dataIndex] ?? dataset.days?.[dataIndex]+ const day = dataset.days?.[dataIndex]if (day == null || day === '') {return}diff --git a/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.ts b/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.tsindex b5e6cbb107af..4d1578c3e5fe 100644--- a/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsPieChart/persons-modal-parity.test.ts@@ -18,7 +18,7 @@ describe('persons modal parity between ActionsPie and TrendsPieChart', () => {dateRange: { date_from: '-7d' },} as unknown as InsightActorsQuery['source']- const action: ActionFilter = { id: 99, math: 'total', order: 2 } as unknown as ActionFilter+ const action: ActionFilter = { id: '$pageview', type: 'events', order: 0 }const indexedResults: IndexedTrendResult[] = [{@@ -32,6 +32,7 @@ describe('persons modal parity between ActionsPie and TrendsPieChart', () => {labels: [],count: 100,action,+ order: 0,breakdown_value: 'chrome',compare_label: 'current',} as IndexedTrendResult,@@ -46,6 +47,7 @@ describe('persons modal parity between ActionsPie and TrendsPieChart', () => {labels: [],count: 50,action,+ order: 0,breakdown_value: 'safari',compare_label: 'current',} as IndexedTrendResult,@@ -54,26 +56,15 @@ describe('persons modal parity between ActionsPie and TrendsPieChart', () => {// Build the input ActionsPie passes to datasetToActorsQuery.function legacyActionsPieDataset(): Pick<GraphDataset,- 'action' | 'breakdownValues' | 'compareLabels' | 'breakdown_value' | 'compare_label'+ 'order' | 'breakdownValues' | 'compareLabels' | 'breakdown_value' | 'compare_label'> {return {- action,+ order: 0,breakdownValues: indexedResults.map((r) => r.breakdown_value),compareLabels: indexedResults.map((r) => r.compare_label),}}- // Build the input the hog-charts TrendsPieChart passes to datasetToActorsQuery — single slice.- function newPieDatasetForSlice(- slice: IndexedTrendResult- ): Pick<GraphDataset, 'action' | 'breakdown_value' | 'compare_label'> {- return {- action: slice.action,- breakdown_value: slice.breakdown_value,- compare_label: slice.compare_label,- }- }-it('produces an identical query for a slice', () => {const legacyQuery = datasetToActorsQuery({dataset: legacyActionsPieDataset(),@@ -81,7 +72,8 @@ describe('persons modal parity between ActionsPie and TrendsPieChart', () => {index: 0,})const newQuery = datasetToActorsQuery({- dataset: newPieDatasetForSlice(indexedResults[0]),+ // The hog-charts TrendsPieChart passes the clicked slice's result itself.+ dataset: indexedResults[0],query: querySource,})expect(newQuery).toEqual(legacyQuery)diff --git a/products/product_analytics/frontend/insights/trends/shared/anomalyPointsAdapter.test.ts b/products/product_analytics/frontend/insights/trends/shared/anomalyPointsAdapter.test.tsindex a998f5b45fb4..5905dbc8f78c 100644--- a/products/product_analytics/frontend/insights/trends/shared/anomalyPointsAdapter.test.ts+++ b/products/product_analytics/frontend/insights/trends/shared/anomalyPointsAdapter.test.ts@@ -10,13 +10,15 @@ function makeResult(overrides: Partial<IndexedTrendResult> = {}): IndexedTrendReid: 0,seriesIndex: 0,colorIndex: 0,+ // The trends runner sends `action.days` as datetimes, which never match an alert's dates.action: {id: '$pageview',type: EntityTypes.EVENTS,order: 0,name: '$pageview',- days: ['2024-06-10', '2024-06-11', '2024-06-12'],+ days: ['2024-06-10T00:00:00Z', '2024-06-11T00:00:00Z', '2024-06-12T00:00:00Z'],},+ order: 0,label: '$pageview',count: 10,aggregated_value: 10,@@ -82,17 +84,6 @@ describe('buildAnomalyMarkers', () => {expect(buildAnomalyMarkers(anomalies, [result], colorOf, yAxisOf, notHidden)).toEqual([])})- it('falls back to result.days when action.days is missing', () => {- const result = makeResult({- action: { id: '$pageview', type: EntityTypes.EVENTS, order: 0, name: '$pageview' },- days: ['D0', 'D1', 'D2'],- })- const anomalies: AnomalyPoint[] = [{ index: 0, date: 'D2', score: 0.5, seriesIndex: 0 }]- const markers = buildAnomalyMarkers(anomalies, [result], colorOf, yAxisOf, notHidden)- expect(markers).toHaveLength(1)- expect(markers[0]).toMatchObject({ dataIndex: 2, value: 3 })- })-it('uses the y-axis id supplied by the caller', () => {const anomalies: AnomalyPoint[] = [{ index: 0, date: '2024-06-10', score: null, seriesIndex: 0 }]const markers = buildAnomalyMarkers(anomalies, [makeResult()], colorOf, () => 'y2', notHidden)diff --git a/products/product_analytics/frontend/insights/trends/shared/anomalyPointsAdapter.ts b/products/product_analytics/frontend/insights/trends/shared/anomalyPointsAdapter.tsindex 5184d2c9e75a..e809e2c0d1cc 100644--- a/products/product_analytics/frontend/insights/trends/shared/anomalyPointsAdapter.ts+++ b/products/product_analytics/frontend/insights/trends/shared/anomalyPointsAdapter.ts@@ -32,7 +32,7 @@ export function buildAnomalyMarkers(if (!result || isHidden(result)) {continue}- const days: string[] = result.action?.days ?? result.days ?? []+ const days: string[] = result.days ?? []if (!days.length) {continue}diff --git a/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.test.tsx b/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.test.tsxindex aa5574cf8080..417fbfc9c553 100644--- a/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.test.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.test.tsx@@ -10,13 +10,8 @@ function makeTrendResult(overrides: Partial<IndexedTrendResult> = {}): IndexedTrid: 0,seriesIndex: 0,colorIndex: 0,- action: {- id: '$pageview',- type: EntityTypes.EVENTS,- order: 0,- name: '$pageview',- days: ['2024-06-10', '2024-06-11', '2024-06-12'],- },+ action: { id: '$pageview', type: EntityTypes.EVENTS, order: 0, name: '$pageview' },+ order: 0,label: '$pageview',count: 10,aggregated_value: 10,@@ -195,28 +190,26 @@ describe('handleTrendsChartClick', () => {expect(onDataPointClick).not.toHaveBeenCalled()})- it('uses trendResult.days[index] as fallback when action.days is missing', () => {+ it('sends a previous-period click with the current-period day, which the actors query shifts back', () => {const openPersonsModal = jest.fn()- const trendResult = makeTrendResult({- // ActionFilter without a `days` array — the adapter should fall- // back to reading from the top-level trend result `days`.- action: { id: '$pageview', type: EntityTypes.EVENTS, order: 0, name: '$pageview' },- days: ['D0', 'D1', 'D2'],+ const current = makeTrendResult({ compare: true, compare_label: CompareLabelType.Current })+ const previous = makeTrendResult({+ id: 1,+ compare: true,+ compare_label: CompareLabelType.Previous,+ days: ['2024-06-03', '2024-06-04', '2024-06-05'],})- const deps = makeDeps({ openPersonsModal, indexedResults: [trendResult] })+ const deps = makeDeps({ openPersonsModal, indexedResults: [current, previous] })- handleTrendsChartClick(keyFor(trendResult), 2, deps)+ handleTrendsChartClick(keyFor(previous), 1, deps)- expect(openPersonsModal.mock.calls[0][0].query).toMatchObject({ day: 'D2' })+ expect(openPersonsModal.mock.calls[0][0].query).toMatchObject({ day: '2024-06-11', compare: 'previous' })})- it('no-ops when neither action.days nor trendResult.days can supply a day', () => {+ it('no-ops when the clicked row has no day at that index', () => {const openPersonsModal = jest.fn()const onDataPointClick = jest.fn()- const trendResult = makeTrendResult({- action: { id: '$pageview', type: EntityTypes.EVENTS, order: 0, name: '$pageview' },- days: [],- })+ const trendResult = makeTrendResult({ days: [] })const deps = makeDeps({openPersonsModal,indexedResults: [trendResult],diff --git a/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.tsx b/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.tsxindex ee444297be00..43566577e06e 100644--- a/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/handleTrendsChartClick.tsx@@ -3,7 +3,7 @@ import type { OpenPersonsModalProps } from 'scenes/trends/persons-modal/PersonsMimport { InsightActorsQuery, InsightVizNode, ResolvedDateRangeResponse } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'-import { IntervalType } from '~/types'+import { CompareLabelType, IntervalType } from '~/types'import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'import { datasetToActorsQuery } from 'products/product_analytics/frontend/insights/trends/viz/datasetToActorsQuery'@@ -68,7 +68,13 @@ export function handleTrendsChartClick(return}- const day = dataset.action?.days?.[dataIndex] ?? dataset.days?.[dataIndex]+ // A previous-period row lists its own dates, but the actors query takes the current-period date+ // and shifts it back itself, so read the day from a current-period row.+ const currentPeriodDataset =+ dataset.compare_label === CompareLabelType.Previous+ ? (deps.indexedResults.find((r) => r.compare_label !== CompareLabelType.Previous) ?? dataset)+ : dataset+ const day = currentPeriodDataset.days?.[dataIndex]if (day == null || day === '') {return}diff --git a/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx b/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsxindex d82a3d26a376..3fc0e60fc9ba 100644--- a/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx+++ b/products/product_analytics/frontend/insights/trends/shared/useTrendsPartOfWholeChart.tsx@@ -181,14 +181,7 @@ export function useTrendsPartOfWholeChart({}openPersonsModal({title: label || '',- query: datasetToActorsQuery({- dataset: {- action: result.action,- breakdown_value: result.breakdown_value,- compare_label: result.compare_label,- },- query: querySource,- }),+ query: datasetToActorsQuery({ dataset: result, query: querySource }),additionalSelect: {value_at_data_point: 'event_count',matched_recordings: 'matched_recordings',diff --git a/products/product_analytics/frontend/insights/trends/viz/datasetToActorsQuery.ts b/products/product_analytics/frontend/insights/trends/viz/datasetToActorsQuery.tsindex 6e9307c58e2a..73bba0ec378e 100644--- a/products/product_analytics/frontend/insights/trends/viz/datasetToActorsQuery.ts+++ b/products/product_analytics/frontend/insights/trends/viz/datasetToActorsQuery.ts@@ -1,10 +1,10 @@+import { ResultSeriesRow, getResultSeriesIndex } from 'scenes/insights/utils/resultSeries'+import { InsightActorsQuery, NodeKind } from '~/queries/schema/schema-general'import { GraphDataset } from '~/types'-type DatasetToActorsInput = Pick<- GraphDataset,- 'action' | 'breakdown_value' | 'compare_label' | 'status' | 'breakdownValues' | 'compareLabels'->+type DatasetToActorsInput = ResultSeriesRow &+ Pick<GraphDataset, 'breakdown_value' | 'compare_label' | 'status' | 'breakdownValues' | 'compareLabels'>interface DatasetToActorsQueryProps {dataset: DatasetToActorsInput@@ -26,7 +26,7 @@ export function datasetToActorsQuery({ query, dataset, day, index }: DatasetToAcsource: query,day,status: dataset.status,- series: dataset.action?.order ?? 0,+ series: getResultSeriesIndex(query, dataset) ?? 0,breakdown,compare,includeRecordings: true,