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(insights): add slope graph as a trends chart type (#63443)

Paul D'Ambra3644bb285c77
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6a523478a89d..568bb3a88316 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -733,9 +733,13 @@ snapshots:
components-hogcharts-slopechart--default--light:
hash: v1.k794b7964.767c8b748b168ed3b5cc2f29304d021008daf84127b75cbd7c125f27a9a4ae1a.Uo_Ajb9L7xem1Kyi41a7splR7w_Jhtjdo2tRbNf5iHE
components-hogcharts-slopechart--empty--dark:
- hash: v1.k794b7964.c5de55c471941eed34d689ba85f43a07017bf231e8bdc4ffca98521cdab3bcd0.l5q1XuFp9vcETkmULkBOR7oZw7Y-MbeQkyuOTkrMiyw
+ hash: v1.k794b7964.8d705f1946799a1a5f51a9bfbf7a3b1180e07a50a1ed63c33eac9cbcc73d83ec.JOYzqA_2imgBQQPSnvfIuOGeNeGf-phBMLT5KEnbLw4
components-hogcharts-slopechart--empty--light:
- hash: v1.k794b7964.8c60ac901acd4c646cd3d874b8de6bd6dffe3c0ba4e6a920e202198b2f467f4e.seAawuDJwtjwqqjlVkBrYMcqoTTUh3LzjO5-kf9JiJ8
+ hash: v1.k794b7964.b60a9b53862703b0650c509f6efc52030ce9b892f98277b04db561e8eafbba37.yBlrhw2i9aAlxDq65nSAZ1g9-13awj42D6riEmYT__o
+ components-hogcharts-slopechart--incomplete-end--dark:
+ hash: v1.k794b7964.c20bbbeb5881733ea773011c9e1b3950dd08b07a04cbc0131c3e57b7efbc9440.VEnYJrfNO4b1DEjKCMNQL25NXoxX8dzKNPOYd6RJ3fA
+ components-hogcharts-slopechart--incomplete-end--light:
+ hash: v1.k794b7964.7152a8945cbe26c205284ddf9799eb4d808e4413babf9a87e5ec0860cdc6f850.JfQpbS54cCv0ATEec9Afhk1fHervgDL_4qMlXbMJW7E
components-hogcharts-slopechart--legend-right--dark:
hash: v1.k794b7964.5a3bd59b3c452187180052e9642e8f5b28fbee80eb37c147b326d9d886070cc4.ClqpcWz4o-XlMOOF9U5V6VHlURr6NnpmYhEhaAJ_HO8
components-hogcharts-slopechart--legend-right--light:
@@ -5314,6 +5318,22 @@ snapshots:
hash: v1.k794b7964.ee5568ad7c36562de11087860c424d458d38f9ab78086e13190a2d344c94886e.Phxh-Ba38MPL53L_jYU4xpEEnTv_7jfXmJZa8vWL3ME
scenes-app-insights-trendspie--trends-world-map-edit--light:
hash: v1.k794b7964.cd2f689b29e28b06f897a4bca768113926233988efb3fb4e600291b8af8324c0.5_HLaGKeRiEv5DpRKhp_wZ8UDLEGlx6s4LNsZMnY34Y
+ scenes-app-insights-trendsslopegraph--trends-slope-graph--dark:
+ hash: v1.k794b7964.90656a3ab0e0e884066438fe2010a954ca4f2324429a4fb223020be5d007bc8d.7NM5eEo9QQRZpP0UtTsJokSUnhjM-2iNUQ1aZxMtK3s
+ scenes-app-insights-trendsslopegraph--trends-slope-graph--light:
+ hash: v1.k794b7964.5ca06a070c6d7243e27caa9237342d54e06caf8cdbd207058c92a879280c192a.6YEtfvAGfLl4rHMwTvGr7d9g5_1FBijsuOJ0uDsqFvo
+ scenes-app-insights-trendsslopegraph--trends-slope-graph-edit--dark:
+ hash: v1.k794b7964.aa3925af9ff963c9a4ff078d763eefc4f431bfcb76743620d3aed87f5b34c6a2.pCD2J9ELy9nn_T3zZUkmdHqAhRQ2MwZR68H89gl5-1k
+ scenes-app-insights-trendsslopegraph--trends-slope-graph-edit--light:
+ hash: v1.k794b7964.f9f2e752c608d8934b6b7e4b67f350f27a36bb74f9fc40ecb5421b3bb7b1efe2.wnKSU54WQ7spstUfSvqqSE54kdOaY5dZ2-tAJgyCVqQ
+ scenes-app-insights-trendsslopegraph--trends-slope-graph-incomplete-period--dark:
+ hash: v1.k794b7964.6f48e3b26fa1dbcf874be5762183c59636a377033cabe4576701713a19fdb59d.yZOisLKz7E1FMLYJPW3JbH95A6ROCnbK-fdqHGd53MA
+ scenes-app-insights-trendsslopegraph--trends-slope-graph-incomplete-period--light:
+ hash: v1.k794b7964.9f0d760ee25679e5b817dc81b7df7ef326983eeef514c093d10cf8a08fc7679f.XmDKnPfkcpkFOYvnFDfh6gvJiKM0JL5HZS0Lj5SOkpI
+ scenes-app-insights-trendsslopegraph--trends-slope-graph-with-legend--dark:
+ hash: v1.k794b7964.828419ff8c260e3794e58b96e316dce5eea4f7577c269e7f337ac22a94f66a35.SEgHO0d83_dMCXDlDXyvs6thyJKeOwg9RWrve5PtTNk
+ scenes-app-insights-trendsslopegraph--trends-slope-graph-with-legend--light:
+ hash: v1.k794b7964.f69c8a996a7ed866d6f9c8f0eefc4db3959b1a38c4baeef46c4187c9c16a0d16.6HSKTeiFXbRGVfzwDHFKqE6GJYoLJt-if1LFCMMI10M
scenes-app-insights-trendsvalue--trends-area--dark:
hash: v1.k794b7964.3fce948481d1b3be054893a8e99508e85bdff69723c91f864e311ca498389e87.VY094hyWWNRusfn5-e_sxtQ3JZMauWFWoD9Nu0X8x4E
scenes-app-insights-trendsvalue--trends-area--light:
diff --git a/frontend/src/lib/components/ChartFilter/ChartFilter.tsx b/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
index 52d86f4beb3e..935f14d5e3de 100644
--- a/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
+++ b/frontend/src/lib/components/ChartFilter/ChartFilter.tsx
@@ -97,6 +97,22 @@ export function ChartFilter(): JSX.Element {
},
]
: []),
+ ...(featureFlags[FEATURE_FLAGS.SLOPE_GRAPH_INSIGHT]
+ ? [
+ {
+ value: ChartDisplayType.SlopeGraph,
+ icon: <IconTrends />,
+ label: 'Slope graph',
+ disabledReason: trendsOnlyDisabledReason,
+ labelInMenu: (
+ <ChartFilterOptionLabel
+ label="Slope graph"
+ description="Change from the start to the end of the range, one line per series."
+ />
+ ),
+ },
+ ]
+ : []),
],
},
{
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 1100bbaf13ed..9ce13128076c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -19,6 +19,9 @@ export const DISPLAY_TYPES_TO_CATEGORIES: Record<ChartDisplayType, ChartDisplayC
[ChartDisplayType.CalendarHeatmap]: ChartDisplayCategory.TotalValue,
[ChartDisplayType.TwoDimensionalHeatmap]: ChartDisplayCategory.TotalValue,
[ChartDisplayType.BoxPlot]: ChartDisplayCategory.TimeSeries,
+ // The slope's two points are the first and last interval bucket, so it's time-series at heart;
+ // it keeps the group-by interval and InsightDisplayConfig hides the options between the ends.
+ [ChartDisplayType.SlopeGraph]: ChartDisplayCategory.TimeSeries,
}
export const NON_TIME_SERIES_DISPLAY_TYPES = Object.entries(DISPLAY_TYPES_TO_CATEGORIES)
.filter(([, category]) => category === ChartDisplayCategory.TotalValue)
@@ -213,6 +216,7 @@ export const FEATURE_FLAGS = {
SETTINGS_SESSION_TABLE_VERSION: 'settings-session-table-version', // owner: #team-analytics-platform
SETTINGS_SESSIONS_V2_JOIN: 'settings-sessions-v2-join', // owner: @robbie-c #team-web-analytics
SETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES: 'web-analytics-pre-aggregated-tables', // owner: @lricoy #team-web-analytics
+ SLOPE_GRAPH_INSIGHT: 'slope-graph-insight', // owner: @pauldambra #team-product-analytics
STARTUP_PROGRAM_INTENT: 'startup-program-intent', // owner: @pawel-cebula #team-billing
SURVEYS_ACTIONS: 'surveys-actions', // owner: #team-surveys
SURVEYS_ADAPTIVE_LIMITS: 'surveys-adaptive-limits', // owner: #team-surveys
diff --git a/frontend/src/mocks/fixtures/api/projects/team_id/insights/trendsSlopeGraph.json b/frontend/src/mocks/fixtures/api/projects/team_id/insights/trendsSlopeGraph.json
new file mode 100644
index 000000000000..eda032025b15
--- /dev/null
+++ b/frontend/src/mocks/fixtures/api/projects/team_id/insights/trendsSlopeGraph.json
@@ -0,0 +1,525 @@
+{
+ "id": 51,
+ "short_id": "jEAIVJnO",
+ "name": "Trends slope graph",
+ "derived_name": "Pageview count by event's Library Version",
+ "filters": {
+ "display": "SlopeGraph"
+ },
+ "filters_hash": "cache_94f92e3691eff06429f04cf08a17330e",
+ "order": null,
+ "deleted": false,
+ "dashboard": null,
+ "layouts": {},
+ "color": null,
+ "last_refresh": null,
+ "refreshing": false,
+ "result": [
+ {
+ "action": {
+ "id": "$pageview",
+ "type": "events",
+ "order": 0,
+ "name": "$pageview",
+ "custom_name": null,
+ "math": null,
+ "math_property": null,
+ "math_group_type_index": null,
+ "properties": {}
+ },
+ "label": "$pageview - 1.10.5",
+ "count": 44182,
+ "data": [
+ 22750,
+ 0
+ ],
+ "labels": [
+ "8-Mar-2022",
+ "15-Mar-2022"
+ ],
+ "days": [
+ "2022-03-08",
+ "2022-03-15"
+ ],
+ "breakdown_value": "1.10.5",
+ "persons_urls": [
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-08",
+ "date_to": "2022-03-08",
+ "breakdown_value": "1.10.5",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-08&date_to=2022-03-08&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.10.5"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-09",
+ "date_to": "2022-03-09",
+ "breakdown_value": "1.10.5",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-09&date_to=2022-03-09&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.10.5"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-10",
+ "date_to": "2022-03-10",
+ "breakdown_value": "1.10.5",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-10&date_to=2022-03-10&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.10.5"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-11",
+ "date_to": "2022-03-11",
+ "breakdown_value": "1.10.5",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-11&date_to=2022-03-11&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.10.5"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-12",
+ "date_to": "2022-03-12",
+ "breakdown_value": "1.10.5",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-12&date_to=2022-03-12&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.10.5"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-13",
+ "date_to": "2022-03-13",
+ "breakdown_value": "1.10.5",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-13&date_to=2022-03-13&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.10.5"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-14",
+ "date_to": "2022-03-14",
+ "breakdown_value": "1.10.5",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-14&date_to=2022-03-14&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.10.5"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-15",
+ "date_to": "2022-03-15",
+ "breakdown_value": "1.10.5",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-15&date_to=2022-03-15&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.10.5"
+ }
+ ],
+ "filter": {
+ "breakdown": "$lib_version",
+ "breakdown_type": "event",
+ "date_from": "2022-03-08T00:00:00+00:00",
+ "date_to": "2022-03-15T21:32:16.712873+00:00",
+ "display": "ActionsLineGraph",
+ "events": [
+ {
+ "id": "$pageview",
+ "type": "events",
+ "order": 0,
+ "name": "$pageview",
+ "custom_name": null,
+ "math": null,
+ "math_property": null,
+ "math_group_type_index": null,
+ "properties": {}
+ }
+ ],
+ "insight": "TRENDS",
+ "interval": "day"
+ }
+ },
+ {
+ "action": {
+ "id": "$pageview",
+ "type": "events",
+ "order": 0,
+ "name": "$pageview",
+ "custom_name": null,
+ "math": null,
+ "math_property": null,
+ "math_group_type_index": null,
+ "properties": {}
+ },
+ "label": "$pageview - 1.13.9",
+ "count": 598,
+ "data": [
+ 0,
+ 0
+ ],
+ "labels": [
+ "8-Mar-2022",
+ "15-Mar-2022"
+ ],
+ "days": [
+ "2022-03-08",
+ "2022-03-15"
+ ],
+ "breakdown_value": "1.13.9",
+ "persons_urls": [
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-08",
+ "date_to": "2022-03-08",
+ "breakdown_value": "1.13.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-08&date_to=2022-03-08&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.13.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-09",
+ "date_to": "2022-03-09",
+ "breakdown_value": "1.13.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-09&date_to=2022-03-09&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.13.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-10",
+ "date_to": "2022-03-10",
+ "breakdown_value": "1.13.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-10&date_to=2022-03-10&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.13.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-11",
+ "date_to": "2022-03-11",
+ "breakdown_value": "1.13.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-11&date_to=2022-03-11&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.13.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-12",
+ "date_to": "2022-03-12",
+ "breakdown_value": "1.13.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-12&date_to=2022-03-12&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.13.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-13",
+ "date_to": "2022-03-13",
+ "breakdown_value": "1.13.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-13&date_to=2022-03-13&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.13.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-14",
+ "date_to": "2022-03-14",
+ "breakdown_value": "1.13.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-14&date_to=2022-03-14&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.13.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-15",
+ "date_to": "2022-03-15",
+ "breakdown_value": "1.13.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-15&date_to=2022-03-15&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.13.9"
+ }
+ ],
+ "filter": {
+ "breakdown": "$lib_version",
+ "breakdown_type": "event",
+ "date_from": "2022-03-08T00:00:00+00:00",
+ "date_to": "2022-03-15T21:32:16.712873+00:00",
+ "display": "ActionsLineGraph",
+ "events": [
+ {
+ "id": "$pageview",
+ "type": "events",
+ "order": 0,
+ "name": "$pageview",
+ "custom_name": null,
+ "math": null,
+ "math_property": null,
+ "math_group_type_index": null,
+ "properties": {}
+ }
+ ],
+ "insight": "TRENDS",
+ "interval": "day"
+ }
+ },
+ {
+ "action": {
+ "id": "$pageview",
+ "type": "events",
+ "order": 0,
+ "name": "$pageview",
+ "custom_name": null,
+ "math": null,
+ "math_property": null,
+ "math_group_type_index": null,
+ "properties": {}
+ },
+ "label": "$pageview - 1.17.9",
+ "count": 2478,
+ "data": [
+ 120,
+ 0
+ ],
+ "labels": [
+ "8-Mar-2022",
+ "15-Mar-2022"
+ ],
+ "days": [
+ "2022-03-08",
+ "2022-03-15"
+ ],
+ "breakdown_value": "1.17.9",
+ "persons_urls": [
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-08",
+ "date_to": "2022-03-08",
+ "breakdown_value": "1.17.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-08&date_to=2022-03-08&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.17.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-09",
+ "date_to": "2022-03-09",
+ "breakdown_value": "1.17.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-09&date_to=2022-03-09&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.17.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-10",
+ "date_to": "2022-03-10",
+ "breakdown_value": "1.17.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-10&date_to=2022-03-10&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.17.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-11",
+ "date_to": "2022-03-11",
+ "breakdown_value": "1.17.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-11&date_to=2022-03-11&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.17.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-12",
+ "date_to": "2022-03-12",
+ "breakdown_value": "1.17.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-12&date_to=2022-03-12&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.17.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-13",
+ "date_to": "2022-03-13",
+ "breakdown_value": "1.17.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-13&date_to=2022-03-13&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.17.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-14",
+ "date_to": "2022-03-14",
+ "breakdown_value": "1.17.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-14&date_to=2022-03-14&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.17.9"
+ },
+ {
+ "filter": {
+ "entity_id": "$pageview",
+ "entity_type": "events",
+ "entity_math": null,
+ "date_from": "2022-03-15",
+ "date_to": "2022-03-15",
+ "breakdown_value": "1.17.9",
+ "breakdown_type": "event"
+ },
+ "url": "api/projects/1/persons/trends/?breakdown=%24lib_version&breakdown_type=event&date_from=2022-03-15&date_to=2022-03-15&display=ActionsLineGraph&events=%5B%7B%22id%22%3A+%22%24pageview%22%2C+%22type%22%3A+%22events%22%2C+%22order%22%3A+0%2C+%22name%22%3A+%22%24pageview%22%2C+%22custom_name%22%3A+null%2C+%22math%22%3A+null%2C+%22math_property%22%3A+null%2C+%22math_group_type_index%22%3A+null%2C+%22properties%22%3A+%7B%7D%7D%5D&insight=TRENDS&interval=day&entity_id=%24pageview&entity_type=events&breakdown_value=1.17.9"
+ }
+ ],
+ "filter": {
+ "breakdown": "$lib_version",
+ "breakdown_type": "event",
+ "date_from": "2022-03-08T00:00:00+00:00",
+ "date_to": "2022-03-15T21:32:16.712873+00:00",
+ "display": "ActionsLineGraph",
+ "events": [
+ {
+ "id": "$pageview",
+ "type": "events",
+ "order": 0,
+ "name": "$pageview",
+ "custom_name": null,
+ "math": null,
+ "math_property": null,
+ "math_group_type_index": null,
+ "properties": {}
+ }
+ ],
+ "insight": "TRENDS",
+ "interval": "day"
+ }
+ }
+ ],
+ "created_at": "2022-03-15T21:31:00.192917Z",
+ "created_by": {
+ "id": 1,
+ "uuid": "017f7913-c1ee-0000-faff-0fe5ace3849a",
+ "distinct_id": "Q1OD2NmnqqbqrLR45mYm2p1VNNbSO9DBFsMig90GWkK",
+ "first_name": "Marius",
+ "email": "[email protected]"
+ },
+ "description": "",
+ "updated_at": "2022-03-15T21:32:28.399372Z",
+ "tags": [],
+ "favorited": false,
+ "saved": true,
+ "last_modified_at": "2022-03-15T21:32:28.394452Z",
+ "last_modified_by": {
+ "id": 1,
+ "uuid": "017f7913-c1ee-0000-faff-0fe5ace3849a",
+ "distinct_id": "Q1OD2NmnqqbqrLR45mYm2p1VNNbSO9DBFsMig90GWkK",
+ "first_name": "Marius",
+ "email": "[email protected]"
+ },
+ "is_sample": false,
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "breakdownFilter": {
+ "breakdown": "$lib_version",
+ "breakdown_type": "event"
+ },
+ "filterTestAccounts": false,
+ "interval": "day",
+ "kind": "TrendsQuery",
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": []
+ }
+ ]
+ },
+ "series": [
+ {
+ "event": "$pageview",
+ "kind": "EventsNode",
+ "name": "$pageview"
+ }
+ ],
+ "trendsFilter": {
+ "display": "SlopeGraph",
+ "resultCustomizationBy": "position",
+ "resultCustomizations": {
+ "2": {
+ "assignmentBy": "position",
+ "hidden": true
+ }
+ }
+ },
+ "version": 2
+ },
+ "full": true
+ }
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
index 0db357605337..788d507b40ab 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx
@@ -33,6 +33,7 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element
[ChartDisplayType.CalendarHeatmap]: 'Calendar heatmap',
[ChartDisplayType.TwoDimensionalHeatmap]: '2d heatmap',
[ChartDisplayType.BoxPlot]: 'Box plot',
+ [ChartDisplayType.SlopeGraph]: 'Slope graph',
}
const renderDisplayTypeLabel = (displayType: ChartDisplayType): string => {
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
index ccad23986866..3c1e8d2c3784 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx
@@ -102,7 +102,46 @@ describe('InsightDisplayConfig', () => {
})
})
+ describe('slope graph display options', () => {
+ it('shows the "group by time period" interval picker — grouping defines the slope', async () => {
+ setupAndRender(makeTrendsQuery(ChartDisplayType.SlopeGraph))
+ expect(screen.getByText(/grouped/i)).toBeInTheDocument()
+ })
+
+ it('hides the compare picker', async () => {
+ setupAndRender(makeTrendsQuery(ChartDisplayType.SlopeGraph))
+ expect(screen.queryByText(/Compare to|Previous period/i)).not.toBeInTheDocument()
+ })
+
+ it('shows only the legend in the Display section', async () => {
+ setupAndRender(makeTrendsQuery(ChartDisplayType.SlopeGraph))
+ await openOptionsMenu()
+
+ const items = getDisplaySectionItems()
+ expect(items).toEqual(['Show legend'])
+ // None of the time-series-only options should leak in.
+ expect(items).not.toContain('Show values on series')
+ expect(items).not.toContain('Show trend lines')
+ expect(items).not.toContain('Show alert threshold lines')
+ expect(items).not.toContain('Show multiple Y-axes')
+ expect(items).not.toContain('Show annotations')
+ })
+
+ it('hides the Y-axis scale and statistical analysis sections', async () => {
+ setupAndRender(makeTrendsQuery(ChartDisplayType.SlopeGraph))
+ await openOptionsMenu()
+
+ expect(screen.queryByText('Y-axis scale')).not.toBeInTheDocument()
+ expect(screen.queryByText('Statistical analysis')).not.toBeInTheDocument()
+ })
+ })
+
describe('line graph display options', () => {
+ it('shows the "group by time period" interval picker (control for the slope graph)', async () => {
+ setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph))
+ expect(screen.getByText(/grouped/i)).toBeInTheDocument()
+ })
+
it('shows multiple options in the Display section', async () => {
setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph))
await openOptionsMenu()
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index cac8ce750c80..89332aaf5723 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -115,13 +115,18 @@ export function InsightDisplayConfig(): JSX.Element {
)
const { featureFlags } = useValues(featureFlagLogic)
const hideWeekendsEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_HIDE_WEEKENDS]
+ // The slope graph shows the first vs last interval, so it keeps the group-by interval picker but
+ // drops the options that need the points between them (compare, smoothing, multiple axes,
+ // alert/annotation overlays, statistical analysis).
+ const isSlopeGraph = display === ChartDisplayType.SlopeGraph
const funnelsCompareEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_FUNNELS_COMPARE]
const showCompare =
(isTrends &&
display !== ChartDisplayType.ActionsAreaGraph &&
display !== ChartDisplayType.CalendarHeatmap &&
- display !== ChartDisplayType.BoxPlot) ||
+ display !== ChartDisplayType.BoxPlot &&
+ !isSlopeGraph) ||
isStickiness ||
isWebAnalyticsInsightQuery(querySource) ||
(funnelsCompareEnabled && (isTrendsFunnel || isTimeToConvertFunnel))
@@ -135,9 +140,9 @@ export function InsightDisplayConfig(): JSX.Element {
(!display || display === ChartDisplayType.ActionsLineGraph || display === ChartDisplayType.ActionsAreaGraph) &&
!!interval &&
(smoothingOptions[interval]?.length ?? 0) > 0
- const showMultipleYAxesConfig = (isTrends || isStickiness) && !isNonTimeSeriesDisplay
- const showAlertThresholdLinesConfig = isTrends && !isNonTimeSeriesDisplay
- const showAnnotationsConfig = (isTrends && !isNonTimeSeriesDisplay) || isTrendsFunnel
+ const showMultipleYAxesConfig = (isTrends || isStickiness) && !isNonTimeSeriesDisplay && !isSlopeGraph
+ const showAlertThresholdLinesConfig = isTrends && !isNonTimeSeriesDisplay && !isSlopeGraph
+ const showAnnotationsConfig = (isTrends && !isNonTimeSeriesDisplay && !isSlopeGraph) || isTrendsFunnel
const isLineDisplay = isDefaultTrendsLineDisplay(display, querySource) || displayMatches(display, LINE_DISPLAYS)
const isBarDisplay = displayMatches(display, BAR_DISPLAYS)
const isCumulativeLineDisplay = display === ChartDisplayType.ActionsLineGraphCumulative
@@ -219,34 +224,42 @@ export function InsightDisplayConfig(): JSX.Element {
),
},
]
- : [
- ...(isLifecycle ? [{ label: () => <LifecycleStackingFilter /> }] : []),
- ...(supportsValueOnSeries ? [{ label: () => <ValueOnSeriesFilter /> }] : []),
- ...(isLifecycle ? [{ label: () => <LifecyclePercentagesFilter /> }] : []),
- ...(supportsPercentStackView ? [{ label: () => <PercentStackViewFilter /> }] : []),
- ...(supportsBarValueStacking ? [{ label: () => <StackBreakdownFilter /> }] : []),
- ...(hasLegend || showFunnelLegendConfig ? [{ label: () => <ShowLegendFilter /> }] : []),
- ...(display === ChartDisplayType.ActionsPie
- ? [{ label: () => <ShowPieTotalFilter /> }]
- : []),
- ...(showAlertThresholdLinesConfig
- ? [
- { label: () => <ShowAlertThresholdLinesFilter /> },
- { label: () => <ShowAlertAnomalyPointsFilter /> },
- ]
- : []),
- ...(showMultipleYAxesConfig ? [{ label: () => <ShowMultipleYAxesFilter /> }] : []),
- ...((isTrends || isRetention || isTrendsFunnel) && !isNonTimeSeriesDisplay
- ? [{ label: () => <ShowTrendLinesFilter /> }]
- : []),
- ...(isTrendsFunnel && !isNonTimeSeriesDisplay
- ? [{ label: () => <HideIncompleteConversionWindowPeriodsFilter /> }]
- : []),
- ...(isTrends && !isNonTimeSeriesDisplay && hideWeekendsEnabled
- ? [{ label: () => <HideWeekendsFilter /> }]
- : []),
- ...(showAnnotationsConfig ? [{ label: () => <ShowAnnotationsFilter /> }] : []),
- ],
+ : isSlopeGraph
+ ? // A slope only shows the first vs last interval of each series — the
+ // legend (when there are multiple series) is the only display option that applies.
+ hasLegend
+ ? [{ label: () => <ShowLegendFilter /> }]
+ : []
+ : [
+ ...(isLifecycle ? [{ label: () => <LifecycleStackingFilter /> }] : []),
+ ...(supportsValueOnSeries ? [{ label: () => <ValueOnSeriesFilter /> }] : []),
+ ...(isLifecycle ? [{ label: () => <LifecyclePercentagesFilter /> }] : []),
+ ...(supportsPercentStackView ? [{ label: () => <PercentStackViewFilter /> }] : []),
+ ...(supportsBarValueStacking ? [{ label: () => <StackBreakdownFilter /> }] : []),
+ ...(hasLegend || showFunnelLegendConfig
+ ? [{ label: () => <ShowLegendFilter /> }]
+ : []),
+ ...(display === ChartDisplayType.ActionsPie
+ ? [{ label: () => <ShowPieTotalFilter /> }]
+ : []),
+ ...(showAlertThresholdLinesConfig
+ ? [
+ { label: () => <ShowAlertThresholdLinesFilter /> },
+ { label: () => <ShowAlertAnomalyPointsFilter /> },
+ ]
+ : []),
+ ...(showMultipleYAxesConfig ? [{ label: () => <ShowMultipleYAxesFilter /> }] : []),
+ ...((isTrends || isRetention || isTrendsFunnel) && !isNonTimeSeriesDisplay
+ ? [{ label: () => <ShowTrendLinesFilter /> }]
+ : []),
+ ...(isTrendsFunnel && !isNonTimeSeriesDisplay
+ ? [{ label: () => <HideIncompleteConversionWindowPeriodsFilter /> }]
+ : []),
+ ...(isTrends && !isNonTimeSeriesDisplay && hideWeekendsEnabled
+ ? [{ label: () => <HideWeekendsFilter /> }]
+ : []),
+ ...(showAnnotationsConfig ? [{ label: () => <ShowAnnotationsFilter /> }] : []),
+ ],
},
]
: []),
@@ -275,7 +288,7 @@ export function InsightDisplayConfig(): JSX.Element {
},
]
: []),
- ...(!isNonTimeSeriesDisplay && isTrends && display !== ChartDisplayType.CalendarHeatmap
+ ...(!isNonTimeSeriesDisplay && isTrends && display !== ChartDisplayType.CalendarHeatmap && !isSlopeGraph
? [
{
title: 'Y-axis scale',
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index 8feef4de4e8d..763cfcb93132 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -279,6 +279,9 @@ export function InsightVizDisplay({
return null
})()
+ // The slope graph draws its own legend inside the chart, so it opts out of the side-legend column.
+ const showSideLegend = supportsDisplay && showLegend && display !== ChartDisplayType.SlopeGraph
+
function renderActiveView(): JSX.Element | null {
switch (activeView) {
case InsightType.TRENDS:
@@ -466,12 +469,12 @@ export function InsightVizDisplay({
<div
className={clsx(
'InsightVizDisplay__content',
- supportsDisplay && showLegend && 'InsightVizDisplay__content--with-legend'
+ showSideLegend && 'InsightVizDisplay__content--with-legend'
)}
>
{BlockingEmptyState ? (
BlockingEmptyState
- ) : supportsDisplay && showLegend ? (
+ ) : showSideLegend ? (
<>
<div className="InsightVizDisplay__content__left">{renderActiveView()}</div>
<div className="InsightVizDisplay__content__right empty:hidden">
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index bc4472d90154..adb0d3337d0b 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -4210,6 +4210,10 @@
"const": "BoxPlot",
"type": "string"
},
+ {
+ "const": "SlopeGraph",
+ "type": "string"
+ },
{
"not": {}
}
@@ -4307,7 +4311,8 @@
"WorldMap",
"CalendarHeatmap",
"TwoDimensionalHeatmap",
- "BoxPlot"
+ "BoxPlot",
+ "SlopeGraph"
],
"type": "string"
},
@@ -11619,7 +11624,8 @@
"WorldMap",
"CalendarHeatmap",
"TwoDimensionalHeatmap",
- "BoxPlot"
+ "BoxPlot",
+ "SlopeGraph"
],
"type": "string"
},
diff --git a/frontend/src/scenes/insights/stories/TrendsSlopeGraph.stories.tsx b/frontend/src/scenes/insights/stories/TrendsSlopeGraph.stories.tsx
new file mode 100644
index 000000000000..bf45ac93aaee
--- /dev/null
+++ b/frontend/src/scenes/insights/stories/TrendsSlopeGraph.stories.tsx
@@ -0,0 +1,68 @@
+import { samplePersonProperties, sampleRetentionPeopleResponse } from 'scenes/insights/__mocks__/insight.mocks'
+
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { createInsightStory } from 'scenes/insights/__mocks__/createInsightScene'
+
+import { mswDecorator } from '~/mocks/browser'
+
+type Story = StoryObj<{}>
+const meta: Meta = {
+ title: 'Scenes-App/Insights/TrendsSlopeGraph',
+ parameters: {
+ layout: 'fullscreen',
+ testOptions: {
+ snapshotBrowsers: ['chromium'],
+ viewport: {
+ width: 1300,
+ height: 720,
+ },
+ },
+ viewMode: 'story',
+ mockDate: '2022-04-01',
+ featureFlags: [FEATURE_FLAGS.SLOPE_GRAPH_INSIGHT],
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/environments/:team_id/persons/retention': sampleRetentionPeopleResponse,
+ '/api/environments/:team_id/persons/properties': samplePersonProperties,
+ '/api/projects/:team_id/groups_types': [],
+ },
+ post: {
+ '/api/projects/:team_id/cohorts/': { id: 1 },
+ },
+ }),
+ ],
+}
+export default meta
+/* eslint-disable @typescript-eslint/no-var-requires */
+export const TrendsSlopeGraph: Story = createInsightStory(
+ require('../../../mocks/fixtures/api/projects/team_id/insights/trendsSlopeGraph.json')
+)
+TrendsSlopeGraph.parameters = { testOptions: { waitForSelector: '[data-attr=trends-slope-graph] canvas' } }
+export const TrendsSlopeGraphEdit: Story = createInsightStory(
+ require('../../../mocks/fixtures/api/projects/team_id/insights/trendsSlopeGraph.json'),
+ 'edit'
+)
+TrendsSlopeGraphEdit.parameters = { testOptions: { waitForSelector: '[data-attr=trends-slope-graph] canvas' } }
+// With the "Show legend" toggle on, the slope chart shows its own legend with each series'
+// first-to-last change — there's only ever the one legend.
+export const TrendsSlopeGraphWithLegend: Story = createInsightStory(
+ require('../../../mocks/fixtures/api/projects/team_id/insights/trendsSlopeGraph.json'),
+ 'view',
+ true
+)
+TrendsSlopeGraphWithLegend.parameters = { testOptions: { waitForSelector: '[data-attr=trends-slope-graph] canvas' } }
+// The backend flags the last bucket as the current incomplete period (`incomplete_end`), so the
+// second half of the connector to the end point is dashed — the same affordance the line chart uses.
+const slopeInsight = require('../../../mocks/fixtures/api/projects/team_id/insights/trendsSlopeGraph.json')
+export const TrendsSlopeGraphIncompletePeriod: Story = createInsightStory({
+ ...slopeInsight,
+ result: slopeInsight.result.map((series: Record<string, unknown>) => ({ ...series, incomplete_end: true })),
+})
+TrendsSlopeGraphIncompletePeriod.parameters = {
+ testOptions: { waitForSelector: '[data-attr=trends-slope-graph] canvas' },
+}
+/* eslint-enable @typescript-eslint/no-var-requires */
diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.ts
index c0451e9a6e91..75f51440b50d 100644
--- a/frontend/src/scenes/insights/utils/queryUtils.ts
+++ b/frontend/src/scenes/insights/utils/queryUtils.ts
@@ -200,6 +200,9 @@ const groupedChartDisplayTypes: Record<ChartDisplayType, ChartDisplayType> = {
// separate runner
[ChartDisplayType.BoxPlot]: ChartDisplayType.BoxPlot,
+
+ // separate runner — only the two range endpoints, cached on its own key
+ [ChartDisplayType.SlopeGraph]: ChartDisplayType.SlopeGraph,
}
/** clean insight queries so that we can check for semantic equality with a deep equality check */
diff --git a/frontend/src/scenes/trends/Trends.tsx b/frontend/src/scenes/trends/Trends.tsx
index 0f0a3d39125a..ba57aafa0c20 100644
--- a/frontend/src/scenes/trends/Trends.tsx
+++ b/frontend/src/scenes/trends/Trends.tsx
@@ -23,6 +23,12 @@ const TrendsCalendarHeatMap = lazy(() =>
import('scenes/insights/views/CalendarHeatMap').then((m) => ({ default: m.TrendsCalendarHeatMap }))
)
const BoxPlotChart = lazy(() => import('scenes/insights/views/BoxPlot').then((m) => ({ default: m.BoxPlotChart })))
+// Flag-gated — keep the quill/d3 slope chart out of the eager Trends/Dashboard bundle
+const TrendsSlopeChart = lazy(() =>
+ import('products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart').then((m) => ({
+ default: m.TrendsSlopeChart,
+ }))
+)
// Flag-gated — keep full d3 out of the eager Trends/Dashboard bundle
const TrendsLineChart = lazy(() =>
import('products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart').then((m) => ({
@@ -167,6 +173,9 @@ export function TrendInsight({ view, context, embedded, inSharedMode, editMode }
if (display === ChartDisplayType.BoxPlot) {
return <BoxPlotChart {...commonProps} inCardView={embedded} />
}
+ if (display === ChartDisplayType.SlopeGraph) {
+ return <TrendsSlopeChart context={context} />
+ }
}
return (
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 3ccafa993b47..048c6e9c613e 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2872,6 +2872,7 @@ export enum ChartDisplayType {
CalendarHeatmap = 'CalendarHeatmap',
TwoDimensionalHeatmap = 'TwoDimensionalHeatmap',
BoxPlot = 'BoxPlot',
+ SlopeGraph = 'SlopeGraph',
}
export enum ChartDisplayCategory {
TimeSeries = 'TimeSeries',
@@ -3315,6 +3316,9 @@ export interface TrendResult {
* formula index for formula results (uniform across a formula's breakdown rows).
* Unlike `action.order`, this is always populated — formula results carry `action: null`. */
order?: number
+ /** Slope graph only: whether the last bucket is the current, still-accumulating period. Set by
+ * SlopeGraphTrendsQueryRunner so the insight and MCP dash the provisional end identically. */
+ incomplete_end?: boolean
}
interface Person {
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 175bbd1273b6..7353b7db44b1 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -67,7 +67,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original.
- `Legend` is presentational: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).
-- `SlopeChart` config: `showSeriesLabels` (name beside each end point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout.
+- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
## Maintenance
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.stories.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.stories.tsx
index 54eb2784ca09..d3e8305bb834 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.stories.tsx
@@ -30,6 +30,20 @@ export const Default: Story = {
},
}
+/** When the last point is the current, still-accumulating period (`meta.incompleteEnd`), only the
+ * second half of each connector dashes — the start-to-mid half stays solid. */
+export const IncompleteEnd: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const series: Series<SlopeSeriesMeta>[] = SERIES.map((s) => ({ ...s, meta: { incompleteEnd: true } }))
+ return (
+ <Stage width={420}>
+ <SlopeChart series={series} labels={LABELS} theme={theme} />
+ </Stage>
+ )
+ },
+}
+
export const WithoutSeriesLabels: Story = {
render: () => {
const theme = useReactiveTheme()
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
index 4de8c10e2cc2..0c20307d1776 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx
@@ -153,6 +153,68 @@ describe('SlopeChart', () => {
})
})
+ describe('incompleteEnd', () => {
+ it.each([
+ [
+ 'one series with incompleteEnd',
+ [{ key: 'a', label: 'A', data: [10, 90], meta: { incompleteEnd: true } }] as Series<SlopeSeriesMeta>[],
+ ],
+ [
+ 'multiple series, one with incompleteEnd',
+ [
+ { key: 'a', label: 'A', data: [10, 90], meta: { incompleteEnd: true } },
+ { key: 'b', label: 'B', data: [80, 20] },
+ ] as Series<SlopeSeriesMeta>[],
+ ],
+ ])('%s: xTicks shows only the two real labels', (_desc, series) => {
+ const { chart } = renderHogChart(<SlopeChart series={series} labels={LABELS} theme={THEME} />)
+ expect(chart.xTicks()).toEqual(['Before', 'After'])
+ })
+
+ it.each([
+ [
+ 'one series with incompleteEnd',
+ [{ key: 'a', label: 'A', data: [10, 90], meta: { incompleteEnd: true } }] as Series<SlopeSeriesMeta>[],
+ [
+ { side: 'start', text: '10' },
+ { side: 'end', text: '90' },
+ ],
+ ],
+ [
+ 'multiple series, one with incompleteEnd',
+ [
+ { key: 'a', label: 'A', data: [10, 90], meta: { incompleteEnd: true } },
+ { key: 'b', label: 'B', data: [80, 20] },
+ ] as Series<SlopeSeriesMeta>[],
+ [
+ { side: 'start', text: '10' },
+ { side: 'end', text: '90' },
+ { side: 'start', text: '80' },
+ { side: 'end', text: '20' },
+ ],
+ ],
+ ])('%s: value labels read the true start and end values', (_desc, series, expected) => {
+ const { chart } = renderHogChart(<SlopeChart series={series} labels={LABELS} theme={THEME} />)
+ const labels = chart.slopeValueLabels().map((l) => ({ side: l.side, text: l.text }))
+ for (const e of expected) {
+ expect(labels).toContainEqual(e)
+ }
+ })
+ })
+
+ describe('full-series reduction', () => {
+ it('slopes a >2-point series to its first and last point and labels', () => {
+ const series: Series<SlopeSeriesMeta>[] = [{ key: 'a', label: 'A', data: [10, 20, 30, 40] }]
+ const labels = ['Jan', 'Feb', 'Mar', 'Apr']
+ const { chart } = renderHogChart(<SlopeChart series={series} labels={labels} theme={THEME} />)
+ // Only the two ends are shown — interior points and labels are dropped.
+ expect(chart.xTicks()).toEqual(['Jan', 'Apr'])
+ const values = chart.slopeValueLabels().map((l) => ({ side: l.side, text: l.text }))
+ expect(values).toContainEqual({ side: 'start', text: '10' })
+ expect(values).toContainEqual({ side: 'end', text: '40' })
+ })
+ })
+
it('forwards dataAttr to the chart wrapper', () => {
const { chart } = renderHogChart(
<SlopeChart series={SERIES} labels={LABELS} theme={THEME} dataAttr="slope-instance" />
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
index 208c3b5b9862..bfb12a1e0748 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx
@@ -12,7 +12,7 @@ import type {
TooltipContext,
ValueDomain,
} from '../../core/types'
-import { FONT_FAMILY, measureLabelWidth } from '../../utils/text-measure'
+import { AXIS_LABEL_FONT, FONT_FAMILY, measureLabelWidth } from '../../utils/text-measure'
import { LineChart } from '../LineChart/LineChart'
import {
defaultDeltaFormatter,
@@ -32,7 +32,7 @@ const LABEL_FONT = `600 12px ${FONT_FAMILY}`
const VALUE_GAP = 8
const NAME_GAP = 8
const EDGE_PAD = 8
-const DEFAULT_ENDPOINT_RADIUS = 4
+const DEFAULT_POINT_RADIUS = 4
export interface SlopeChartLegendConfig {
/** Show the legend. Default false. */
@@ -43,7 +43,7 @@ export interface SlopeChartLegendConfig {
}
export interface SlopeChartConfig extends ChartConfig {
- /** Show the series name labels beside each end point. Default true. */
+ /** Show the series name labels beside each series' last point. Default true. */
showSeriesLabels?: boolean
/** Default for the start (left) value labels; per-series `meta.showStartLabel` overrides. Default true. */
showStartLabels?: boolean
@@ -55,8 +55,8 @@ export interface SlopeChartConfig extends ChartConfig {
valueFormatter?: (value: number) => string
/** Formats the per-series change shown in the legend. Defaults to a signed `toLocaleString`. */
deltaFormatter?: (delta: number) => string
- /** Radius of the endpoint dots in px. Default 4. */
- endpointRadius?: number
+ /** Radius of the point markers in px. Default 4. */
+ pointRadius?: number
/** Value-axis domain control — omit for data-derived auto-scaling. */
valueDomain?: ValueDomain
}
@@ -105,7 +105,7 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
legend,
valueFormatter = defaultValueFormatter,
deltaFormatter = defaultDeltaFormatter,
- endpointRadius = DEFAULT_ENDPOINT_RADIUS,
+ pointRadius = DEFAULT_POINT_RADIUS,
valueDomain,
} = config ?? {}
@@ -118,6 +118,11 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
[showEndLabels]
)
+ // A slope plots only its two ends, so reduce any-length labels to [first, last] to match — this
+ // lets a caller hand over a full time-series (data + labels) and have the chart slope it, so the
+ // first/last reduction lives here once rather than in every caller.
+ const slopeLabels = useMemo(() => (labels.length > 2 ? [labels[0], labels[labels.length - 1]] : labels), [labels])
+
// Reserve left/right gutters for the value/name labels, which sit in the margins beyond the plot.
const { margins, nameOffsetX } = useMemo(() => {
const startWidth = maxLabelWidth(series.filter(showsStart).map((s) => valueFormatter(slopeStart(s))))
@@ -130,31 +135,52 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
)
: 0
- const left = startWidth > 0 ? startWidth + VALUE_GAP + EDGE_PAD : EDGE_PAD
+ // The x-axis labels sit centred under the two points, so half of the first/last label
+ // overhangs the side gutter — reserve room for it too, else a wide label (e.g. a date) clips.
+ const firstAxisHalf = slopeLabels.length > 0 ? measureLabelWidth(slopeLabels[0], AXIS_LABEL_FONT) / 2 : 0
+ const lastAxisHalf =
+ slopeLabels.length > 1 ? measureLabelWidth(slopeLabels[slopeLabels.length - 1], AXIS_LABEL_FONT) / 2 : 0
+
+ const left = Math.max(startWidth > 0 ? startWidth + VALUE_GAP + EDGE_PAD : EDGE_PAD, firstAxisHalf + EDGE_PAD)
const endGutter = endWidth > 0 ? VALUE_GAP + endWidth : 0
const nameGutter = nameWidth > 0 ? NAME_GAP + nameWidth : 0
- const right = endGutter || nameGutter ? endGutter + nameGutter + EDGE_PAD : EDGE_PAD
+ const right = Math.max(
+ endGutter || nameGutter ? endGutter + nameGutter + EDGE_PAD : EDGE_PAD,
+ lastAxisHalf + EDGE_PAD
+ )
// Names start just past the end value column.
const offset = (endWidth > 0 ? VALUE_GAP + endWidth : 0) + NAME_GAP
const base: Partial<ChartMargins> = { left, right }
return { margins: { ...base, ...config?.margins }, nameOffsetX: offset }
- }, [series, showsStart, showsEnd, showSeriesLabels, valueFormatter, config?.margins])
+ }, [series, slopeLabels, showsStart, showsEnd, showSeriesLabels, valueFormatter, config?.margins])
+
+ // When the last point is the current incomplete period, dash only the *second half* of the
+ // connector so it reads as "the end is provisional", not the whole comparison.
+ const dashEnd = useMemo(() => series.some((s) => (s.meta as SlopeSeriesMeta | undefined)?.incompleteEnd), [series])
- // A slope is a two-point line — collapse each series to its endpoints, with a dot at each.
+ // A slope is a two-point line — collapse each series to its two points, with a dot at each. A
+ // dashed end splits the single segment at its midpoint (renderer-side, no phantom point).
const slopeSeries = useMemo<Series<Meta>[]>(
() =>
series.map((s) => ({
...s,
data: [slopeStart(s), slopeEnd(s)],
- points: { ...s.points, radius: endpointRadius },
+ points: { ...s.points, radius: pointRadius },
+ ...(dashEnd ? { stroke: { ...s.stroke, partial: { ...s.stroke?.partial, fromFraction: 0.5 } } } : {}),
})),
- [series, endpointRadius]
+ [series, pointRadius, dashEnd]
)
const lineConfig = useMemo<LineChartConfig>(
- () => ({ ...config, hideYAxis: config?.hideYAxis ?? true, showGrid: false, margins, valueDomain }),
+ () => ({
+ ...config,
+ hideYAxis: config?.hideYAxis ?? true,
+ showGrid: false,
+ margins,
+ valueDomain,
+ }),
[config, margins, valueDomain]
)
@@ -171,7 +197,7 @@ function SlopeChartInner<Meta = SlopeSeriesMeta>({
>
<LineChart<Meta>
series={slopeSeries}
- labels={labels}
+ labels={slopeLabels}
config={lineConfig}
theme={theme}
tooltip={tooltip}
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeSeriesLabels.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeSeriesLabels.tsx
index eb4b6bb80570..82622359286f 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeSeriesLabels.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeSeriesLabels.tsx
@@ -13,7 +13,7 @@ const LABEL_PADDING_Y = 3
export interface SlopeSeriesLabelsProps {
/** Render the series name labels. Default true. */
show?: boolean
- /** Px to the right of the right endpoint where the name labels begin. */
+ /** Px to the right of the last point where the name labels begin. */
offsetX?: number
}
@@ -23,7 +23,7 @@ interface NameEntry {
label: string
}
-/** Series name labels anchored beside each series' end point. When two names would overlap, the
+/** Series name labels anchored beside each series' last point. When two names would overlap, the
* series with the larger change (`|end − start|`) wins — it is always kept, and lower-change names
* that collide with it are dropped (requirement: the steepest line never loses its label). */
export function SlopeSeriesLabels({ show = true, offsetX = 8 }: SlopeSeriesLabelsProps): React.ReactElement | null {
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeValueLabels.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeValueLabels.tsx
index 948fb7d3ce6f..2630e2b277fb 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeValueLabels.tsx
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeValueLabels.tsx
@@ -11,7 +11,7 @@ export interface SlopeValueLabelsProps {
showStartLabels?: boolean
/** Chart-level default for the end (right) value labels. Per-series `meta.showEndLabel` wins. */
showEndLabels?: boolean
- /** Px gap between the endpoint dot and its value label. */
+ /** Px gap between the point and its value label. */
gap?: number
/** Min vertical px between two labels in the same column before the lower one is dropped. */
minGap?: number
@@ -44,7 +44,7 @@ function columnSweep(candidates: ValueCandidate[], minGap: number): ValueCandida
}
/** Start (left) and end (right) value labels for a slope chart, one per series per side. Each side
- * is a vertical column anchored on the endpoint dots; within a column, lower-priority labels are
+ * is a vertical column anchored on the points; within a column, lower-priority labels are
* dropped on collision. Per-series visibility comes from `meta.showStartLabel`/`showEndLabel`. */
export function SlopeValueLabels({
valueFormatter = defaultValueFormatter,
diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts b/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts
index 4a1015d3e5a5..5da5f8d41197 100644
--- a/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts
+++ b/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts
@@ -7,6 +7,9 @@ export interface SlopeSeriesMeta {
showStartLabel?: boolean
/** Show this series' end (right) value label. Falls back to the chart-level default. */
showEndLabel?: boolean
+ /** The last point is the current, still-accumulating period. The chart dashes only the second
+ * half of the connector to show the end — not the whole comparison — is provisional. */
+ incompleteEnd?: boolean
}
export type SlopeSide = 'start' | 'end'
@@ -28,7 +31,7 @@ export function slopeLabelVisible(
}
/** A slope chart series carries exactly two values — `[start, end]`. These helpers read the first
- * and last entry, substituting 0 when an endpoint is absent. */
+ * and last entry, substituting 0 when a value is absent. */
export function slopeStart(series: Pick<Series, 'data'>): number {
return series.data[0] ?? 0
}
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
index 08b5744369ad..a4af25e07a53 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.test.ts
@@ -299,6 +299,50 @@ describe('hog-charts canvas-renderer', () => {
})
})
+ describe('drawLine — fractional tail dash (stroke.partial.fromFraction)', () => {
+ it.each([
+ // A two-point line: solid first half, dashed second half. One subpath each.
+ { name: 'two points, 0.5 → solid half + dashed half', data: [10, 90], labels: ['a', 'b'], fraction: 0.5 },
+ // Leading points stay solid; only the final segment's tail dashes.
+ {
+ name: 'three points, 0.5 → leading solid, final-segment tail dashed',
+ data: [10, 20, 30],
+ labels: ['a', 'b', 'c'],
+ fraction: 0.5,
+ },
+ ])('$name: two subpaths, solid then dashed', ({ data, labels, fraction }) => {
+ const ctx = mockCanvasContext()
+ const series = makeSeries({ key: 's1', data, stroke: { partial: { fromFraction: fraction } } })
+ drawLine(makeDrawContext(ctx, labels), series)
+ expect(ctx.beginPath).toHaveBeenCalledTimes(2)
+ expect(dashCalls(ctx)).toEqual([[], [10, 10], []])
+ })
+
+ it('dashes the tail with the partial pattern override', () => {
+ const ctx = mockCanvasContext()
+ const series = makeSeries({
+ key: 's1',
+ data: [10, 90],
+ stroke: { partial: { fromFraction: 0.5, pattern: [2, 8] } },
+ })
+ drawLine(makeDrawContext(ctx, ['a', 'b']), series)
+ expect(dashCalls(ctx)).toEqual([[], [2, 8], []])
+ })
+
+ it('takes precedence over fromIndex', () => {
+ const ctx = mockCanvasContext()
+ const series = makeSeries({
+ key: 's1',
+ data: [10, 90],
+ stroke: { partial: { fromFraction: 0.5, fromIndex: 0 } },
+ })
+ drawLine(makeDrawContext(ctx, ['a', 'b']), series)
+ // fromIndex 0 alone would be a single whole-line dashed stroke; the fraction path splits it.
+ expect(ctx.beginPath).toHaveBeenCalledTimes(2)
+ expect(dashCalls(ctx)).toEqual([[], [10, 10], []])
+ })
+ })
+
describe('drawArea — stacked bands', () => {
it('traces bottom values in reverse when bottomValues is provided', () => {
const ctx = mockCanvasContext()
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.ts
index 2bfea4ed4c33..d7028d0222e8 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts
@@ -24,6 +24,11 @@ export function drawLine(drawCtx: DrawContext, series: ResolvedSeries, yValues?:
ctx.lineJoin = 'round'
ctx.lineCap = 'round'
+ if (drawFractionalTailDash(drawCtx, series, data)) {
+ ctx.setLineDash([])
+ return
+ }
+
for (const { start, end, pattern } of planLineStrokes(series, data.length)) {
ctx.beginPath()
ctx.setLineDash(pattern)
@@ -33,6 +38,45 @@ export function drawLine(drawCtx: DrawContext, series: ResolvedSeries, yValues?:
ctx.setLineDash([])
}
+/** Dashes only the tail of the final segment, split at `stroke.partial.fromFraction`. Draws the line
+ * solid up to the split pixel, then dashed to the last point. Returns false (no-op) when the option
+ * is unset or the final segment's endpoints aren't both drawable, so the caller falls back to the
+ * index-based stroke plan. */
+function drawFractionalTailDash(drawCtx: DrawContext, series: ResolvedSeries, data: number[]): boolean {
+ const fraction = series.stroke?.partial?.fromFraction
+ if (fraction == null || data.length < 2) {
+ return false
+ }
+ const { ctx, xScale, yScale, labels } = drawCtx
+ const last = data.length - 1
+ const x0 = xScale(labels[last - 1])
+ const y0 = yScale(data[last - 1])
+ const x1 = xScale(labels[last])
+ const y1 = yScale(data[last])
+ if (x0 == null || x1 == null || !isFinite(y0) || !isFinite(y1)) {
+ return false
+ }
+
+ const f = Math.max(0, Math.min(1, fraction))
+ const splitX = x0 + (x1 - x0) * f
+ const splitY = y0 + (y1 - y0) * f
+
+ // Solid: every leading point through to the split pixel inside the final segment.
+ ctx.beginPath()
+ ctx.setLineDash(series.stroke?.pattern ?? [])
+ tracePath(drawCtx, data, 0, last - 1)
+ ctx.lineTo(splitX, splitY)
+ ctx.stroke()
+
+ // Dashed: the split pixel out to the final point.
+ ctx.beginPath()
+ ctx.setLineDash(series.stroke?.partial?.pattern ?? [10, 10])
+ ctx.moveTo(splitX, splitY)
+ ctx.lineTo(x1, y1)
+ ctx.stroke()
+ return true
+}
+
/** One contiguous stroke: indices [start, end] inclusive, rendered with `pattern`. */
interface Stroke {
start: number
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index 439ebe612e96..98e499038fb7 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -57,6 +57,10 @@ export interface Series<Meta = unknown> {
fromIndex?: number
/** Index up to which the partial pattern applies (inclusive). Clamped to [0, data.length-1]. */
toIndex?: number
+ /** Split the *final* segment at this fraction (0–1) of its length and dash only the part
+ * beyond it — everything before stays solid. Lets a two-point line dash just its second
+ * half without a phantom interior point. Takes precedence over `fromIndex`/`toIndex`. */
+ fromFraction?: number
/** Dash pattern for the partial range. Defaults to [10, 10]. */
pattern?: number[]
}
diff --git a/posthog/hogql_queries/insights/trends/slope_graph_trends_query_runner.py b/posthog/hogql_queries/insights/trends/slope_graph_trends_query_runner.py
new file mode 100644
index 000000000000..fb7530764a57
--- /dev/null
+++ b/posthog/hogql_queries/insights/trends/slope_graph_trends_query_runner.py
@@ -0,0 +1,118 @@
+from datetime import datetime
+
+from posthog.schema import (
+ BaseMathType,
+ ChartDisplayType,
+ FilterLogicalOperator,
+ HogQLPropertyFilter,
+ PropertyGroupFilter,
+ PropertyGroupFilterValue,
+ TrendsFilter,
+ TrendsQuery,
+ TrendsQueryResponse,
+)
+
+from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
+
+# Active-users maths compute each bucket from a trailing window, so they need the days *between* the
+# two end buckets — the two-bucket scan restriction can't be applied without starving the lookback.
+_ACTIVE_USERS_MATHS = (BaseMathType.WEEKLY_ACTIVE, BaseMathType.MONTHLY_ACTIVE)
+
+
+def _needs_full_scan(query: TrendsQuery) -> bool:
+ return any(getattr(s, "math", None) in _ACTIVE_USERS_MATHS for s in query.series)
+
+
+def _keep_first_and_last_bucket(result: dict) -> None:
+ """Keep only the first and last bucket of a trends series — the slope's two points."""
+ for key in ("data", "labels", "days"):
+ values = result.get(key)
+ if isinstance(values, list) and len(values) > 2:
+ result[key] = [values[0], values[-1]]
+
+
+class SlopeGraphTrendsQueryRunner(TrendsQueryRunner):
+ """Renders the change between the first and last interval bucket of the selected range.
+
+ A slope shows two points: the value of the first group and the value of the last group, at the
+ chosen interval (day/week/month). It runs the ordinary trends time series once — reusing every
+ math type, breakdown and filter — but restricts the scan to the first and last bucket's date
+ windows, so ClickHouse only reads those two buckets instead of the whole range. The series still
+ zero-fills the buckets in between; we slice them off. A range spanning a single bucket yields a
+ one-point series, which the frontend drops (there's no slope to draw). The last bucket is shown
+ as-is even when it is the current, still-accumulating period; the frontend dashes that last segment,
+ mirroring the line chart. Because it has its own display type it caches under its own key.
+ """
+
+ def _calculate(self) -> TrendsQueryResponse:
+ series_query = self.query.model_copy(deep=True)
+ # The two ends *are* the comparison — don't also overlay the prior period.
+ series_query.compareFilter = None
+ if series_query.trendsFilter is None:
+ series_query.trendsFilter = TrendsFilter()
+ # Compute the interval series in one query; we slice it to its ends below.
+ series_query.trendsFilter.display = ChartDisplayType.ACTIONS_LINE_GRAPH
+ # Smoothing is a trailing-window moving average — like active-users math it reads the buckets
+ # the scan restriction drops, and it's meaningless on a two-point slope anyway. Clear it.
+ series_query.trendsFilter.smoothingIntervals = None
+ # Read only the two end buckets, not everything between them — ANDed alongside the query's
+ # own filters so a filtered (e.g. shared) slope keeps them rather than going unfiltered.
+ # Active-users maths need the days between the buckets for their trailing window, so they skip
+ # the restriction and scan the full range (still sliced to two points below).
+ if not _needs_full_scan(series_query):
+ existing = series_query.properties
+ end_buckets_filter = self._end_buckets_filter()
+ if isinstance(existing, PropertyGroupFilter):
+ # Wrap the existing group and the bucket filter under a new AND so the saved filters
+ # are preserved, never replaced.
+ series_query.properties = PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(**existing.model_dump()),
+ PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=[end_buckets_filter]),
+ ],
+ )
+ else:
+ series_query.properties = [*(existing or []), end_buckets_filter]
+
+ response = TrendsQueryRunner(
+ query=series_query,
+ team=self.team,
+ timings=self.timings,
+ limit_context=self.limit_context,
+ modifiers=self.modifiers,
+ user=self.user,
+ ).calculate()
+
+ # Whether the last bucket is the current, still-accumulating period — computed once here so
+ # the insight and the MCP both forward it rather than each re-deriving it on the frontend.
+ incomplete_end = self._last_bucket_is_current()
+ for result in response.results or []:
+ _keep_first_and_last_bucket(result)
+ result["incomplete_end"] = incomplete_end
+ return response
+
+ def _last_bucket_is_current(self) -> bool:
+ last_start = self.query_date_range.align_with_interval(self.query_date_range.date_to())
+ next_start = last_start + self.query_date_range.interval_relativedelta()
+ now = self.query_date_range.now_with_timezone
+ return last_start <= now < next_start
+
+ def _end_buckets_filter(self) -> HogQLPropertyFilter:
+ """Restrict the scan to the first and last interval bucket, aligned to the runner's own
+ bucketing so the kept events land in exactly the first and last GROUP BY bucket."""
+ date_from = self.query_date_range.date_from()
+ date_to = self.query_date_range.date_to()
+ first_start = self.query_date_range.align_with_interval(date_from)
+ last_start = self.query_date_range.align_with_interval(date_to)
+ first_end = first_start + self.query_date_range.interval_relativedelta()
+ tz = self.team.timezone
+
+ def lit(value: datetime) -> str:
+ return f"toDateTime('{value.strftime('%Y-%m-%d %H:%M:%S')}', '{tz}')"
+
+ expr = (
+ f"(timestamp >= {lit(first_start)} and timestamp < {lit(first_end)}) "
+ f"or (timestamp >= {lit(last_start)} and timestamp <= {lit(date_to)})"
+ )
+ return HogQLPropertyFilter(key=expr)
diff --git a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_slope_graph_trends_query_runner.ambr b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_slope_graph_trends_query_runner.ambr
new file mode 100644
index 000000000000..f5d3a5bb8c79
--- /dev/null
+++ b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_slope_graph_trends_query_runner.ambr
@@ -0,0 +1,590 @@
+# serializer version: 1
+# name: TestSlopeGraphTrendsQueryRunner.test_active_users_math_keeps_its_trailing_window
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-14 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT counts AS total,
+ toStartOfDay(timestamp) AS day_start
+ FROM
+ (SELECT d.timestamp AS timestamp,
+ count(DISTINCT e.actor_id) AS counts
+ FROM
+ (SELECT toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS timestamp,
+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ WHERE and(equals(e.team_id, 99999), equals(e.event, '$pageview'), greaterOrEquals(timestamp, minus(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(7))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-05-14 23:59:59', 'UTC'))))
+ GROUP BY timestamp, actor_id) AS e
+ CROSS JOIN
+ (SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-14 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestamp
+ FROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(7)), assumeNotNull(toDateTime('2024-05-14 23:59:59', 'UTC')))) AS numbers) AS d
+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(7))))
+ GROUP BY d.timestamp
+ ORDER BY d.timestamp ASC)
+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-05-14 23:59:59', 'UTC')))))
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_breakdown_produces_one_two_point_line_per_value
+ '''
+ SELECT groupArray(1)(date)[1] AS date,
+ arrayFold((acc, x) -> arrayMap(i -> plus(acc[i], x[i]), range(1, plus(length(date), 1))), groupArray(ifNull(total, 0)), arrayWithConstant(length(date), reinterpretAsFloat64(0))) AS total,
+ if(ifNull(greaterOrEquals(row_number, 25), 0), '$$_posthog_breakdown_other_$$', breakdown_value) AS breakdown_value
+ FROM
+ (SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total,
+ breakdown_value AS breakdown_value,
+ rowNumberInAllBlocks() AS row_number
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start,
+ breakdown_value AS breakdown_value
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start,
+ ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'plan'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$') AS breakdown_value
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start,
+ breakdown_value)
+ GROUP BY day_start,
+ breakdown_value
+ ORDER BY day_start ASC,
+ breakdown_value ASC)
+ GROUP BY breakdown_value
+ ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC)
+ WHERE isNotNull(breakdown_value)
+ GROUP BY breakdown_value
+ ORDER BY if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_other_$$'), 0), 2, if(ifNull(equals(breakdown_value, '$$_posthog_breakdown_null_$$'), 0), 1, 0)) ASC, arraySum(total) DESC, breakdown_value ASC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_formula_series
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_groups_by_month_returning_first_and_last_month
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC')), toIntervalMonth(1)), toIntervalMonth(number)), range(0, plus(coalesce(dateDiff('month', toStartOfInterval(assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC')), toIntervalMonth(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-03-31 23:59:59', 'UTC')), toIntervalMonth(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-03-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-01-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-02-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-03-31 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_hour_interval_first_and_last_hour
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-06-14 00:00:00', 'UTC')), toIntervalHour(1)), toIntervalHour(number)), range(0, plus(coalesce(dateDiff('hour', toStartOfInterval(assumeNotNull(toDateTime('2024-06-14 00:00:00', 'UTC')), toIntervalHour(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-06-14 04:30:00', 'UTC')), toIntervalHour(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfHour(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-06-14 00:00:00', 'UTC')), toIntervalHour(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-06-14 04:30:00', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-14 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-14 01:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-14 04:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-14 04:30:00', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_keeps_the_query_property_filter_alongside_the_bucket_restriction
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'UTC'))))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_last_bucket_is_the_current_partial_period_not_trimmed
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalMonth(1)), toIntervalMonth(number)), range(0, plus(coalesce(dateDiff('month', toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalMonth(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-06-15 23:59:59', 'UTC')), toIntervalMonth(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-06-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-04-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-15 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_monthly_active_math_keeps_its_trailing_window
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-13 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT counts AS total,
+ toStartOfDay(timestamp) AS day_start
+ FROM
+ (SELECT d.timestamp AS timestamp,
+ count(DISTINCT e.actor_id) AS counts
+ FROM
+ (SELECT toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS timestamp,
+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ WHERE and(equals(e.team_id, 99999), equals(e.event, '$pageview'), greaterOrEquals(timestamp, minus(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalDay(30))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-05-13 23:59:59', 'UTC'))))
+ GROUP BY timestamp, actor_id) AS e
+ CROSS JOIN
+ (SELECT minus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-13 23:59:59', 'UTC')), toIntervalDay(1)), toIntervalDay(numbers.number)) AS timestamp
+ FROM numbers(dateDiff('day', minus(toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(30)), assumeNotNull(toDateTime('2024-05-13 23:59:59', 'UTC')))) AS numbers) AS d
+ WHERE and(lessOrEquals(e.timestamp, d.timestamp), greater(e.timestamp, minus(d.timestamp, toIntervalDay(30))))
+ GROUP BY d.timestamp
+ ORDER BY d.timestamp ASC)
+ WHERE and(greaterOrEquals(timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-04-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-05-13 23:59:59', 'UTC')))))
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_no_events_yields_zero_endpoints
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_non_utc_team_timezone
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'US/Pacific')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'US/Pacific')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'US/Pacific')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'US/Pacific')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'US/Pacific')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'US/Pacific'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'US/Pacific')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'US/Pacific'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'US/Pacific')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'US/Pacific')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_preserves_a_property_group_filter
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'paid'), 0), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'UTC'))))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_relative_date_range
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-06-08 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-06-08 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-06-15 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-06-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-06-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-08 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-09 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-15 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-15 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_returns_first_and_last_day_buckets_ignoring_the_middle
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_single_bucket_range_yields_a_one_point_series
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalMonth(1)), toIntervalMonth(number)), range(0, plus(coalesce(dateDiff('month', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalMonth(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-31 23:59:59', 'UTC')), toIntervalMonth(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfMonth(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalMonth(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-31 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-06-01 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-31 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_smoothing_does_not_starve_the_last_point
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_unique_users_math_is_per_bucket
+ '''
+ SELECT arrayMap(number -> plus(toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(number)), range(0, plus(coalesce(dateDiff('day', toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1)), toStartOfInterval(assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC')), toIntervalDay(1)))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count(DISTINCT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)) AS total,
+ toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-10 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-01 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-02 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-10 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestSlopeGraphTrendsQueryRunner.test_week_interval_scan_filter_aligns_with_the_buckets
+ '''
+ SELECT arrayMap(number -> plus(toStartOfWeek(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), 0), toIntervalWeek(number)), range(0, plus(coalesce(dateDiff('week', toStartOfWeek(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), 0), toStartOfWeek(assumeNotNull(toDateTime('2024-05-28 23:59:59', 'UTC')), 0))), 1))) AS date,
+ arrayMap(_match_date -> arraySum(arraySlice(groupArray(ifNull(count, 0)), indexOf(groupArray(day_start) AS _days_for_count, _match_date) AS _index, plus(minus(arrayLastIndex(x -> ifNull(equals(x, _match_date), isNull(x)
+ and isNull(_match_date)), _days_for_count), _index), 1))), date) AS total
+ FROM
+ (SELECT sum(total) AS count,
+ day_start AS day_start
+ FROM
+ (SELECT count() AS total,
+ toStartOfWeek(toTimeZone(e.timestamp, 'UTC'), 0) AS day_start
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2024-05-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2024-05-28 23:59:59', 'UTC'))), equals(e.event, '$pageview'), or(and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-04-28 00:00:00', 6, 'UTC')), less(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-05 00:00:00', 6, 'UTC'))), and(greaterOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-26 00:00:00', 6, 'UTC')), lessOrEquals(e.timestamp, parseDateTime64BestEffortOrNull('2024-05-28 23:59:59', 6, 'UTC')))))
+ GROUP BY day_start)
+ GROUP BY day_start
+ ORDER BY day_start ASC)
+ ORDER BY arraySum(total) DESC
+ LIMIT 50000 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
diff --git a/posthog/hogql_queries/insights/trends/test/test_slope_graph_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_slope_graph_trends_query_runner.py
new file mode 100644
index 000000000000..252dd70a7828
--- /dev/null
+++ b/posthog/hogql_queries/insights/trends/test/test_slope_graph_trends_query_runner.py
@@ -0,0 +1,348 @@
+from freezegun import freeze_time
+from posthog.test.base import (
+ APIBaseTest,
+ ClickhouseTestMixin,
+ _create_event,
+ _create_person,
+ snapshot_clickhouse_queries,
+)
+
+from posthog.schema import (
+ BreakdownFilter,
+ ChartDisplayType,
+ DateRange,
+ EventPropertyFilter,
+ EventsNode,
+ FilterLogicalOperator,
+ PropertyGroupFilter,
+ PropertyGroupFilterValue,
+ PropertyOperator,
+ TrendsFilter,
+ TrendsQuery,
+)
+
+from posthog.hogql_queries.insights.trends.slope_graph_trends_query_runner import SlopeGraphTrendsQueryRunner
+from posthog.models.utils import uuid7
+
+
+@freeze_time("2024-06-15T12:00:00Z")
+class TestSlopeGraphTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
+ def _create_events(self, data, event="$pageview"):
+ for distinct_id, timestamps in data:
+ with freeze_time(timestamps[0][0]):
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], properties={"name": distinct_id})
+ for timestamp, *rest in timestamps:
+ _create_event(
+ team=self.team,
+ event=event,
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ uuid=str(uuid7()),
+ properties=rest[0] if rest else {},
+ )
+
+ def _run(self, date_from, date_to, series=None, breakdown=None, interval="day"):
+ query = TrendsQuery(
+ dateRange=DateRange(date_from=date_from, date_to=date_to),
+ interval=interval,
+ breakdownFilter=breakdown,
+ trendsFilter=TrendsFilter(display=ChartDisplayType.SLOPE_GRAPH),
+ series=series or [EventsNode(kind="EventsNode", event="$pageview", math="total")],
+ )
+ return SlopeGraphTrendsQueryRunner(team=self.team, query=query).calculate()
+
+ @snapshot_clickhouse_queries
+ def test_returns_first_and_last_day_buckets_ignoring_the_middle(self):
+ self._create_events(
+ [
+ ("first_day", [("2024-05-01T10:00:00Z",), ("2024-05-01T11:00:00Z",)]),
+ ("middle", [("2024-05-05T10:00:00Z",), ("2024-05-06T10:00:00Z",)]),
+ ("last_day", [("2024-05-10T08:00:00Z",), ("2024-05-10T09:00:00Z",), ("2024-05-10T10:00:00Z",)]),
+ ]
+ )
+ response = self._run("2024-05-01", "2024-05-10")
+
+ assert len(response.results) == 1
+ result = response.results[0]
+ assert len(result["data"]) == 2
+ # Only the first and last day count — the middle days are never queried.
+ assert result["data"][0] == 2
+ assert result["data"][1] == 3
+ # The range ends well before "now" (2024-06-15), so the last bucket is complete.
+ assert result["incomplete_end"] is False
+
+ @snapshot_clickhouse_queries
+ def test_groups_by_month_returning_first_and_last_month(self):
+ self._create_events(
+ [
+ ("jan", [("2024-01-05T10:00:00Z",), ("2024-01-20T10:00:00Z",)]),
+ ("feb", [("2024-02-10T10:00:00Z",)]),
+ ("mar", [("2024-03-01T10:00:00Z",), ("2024-03-10T10:00:00Z",), ("2024-03-20T10:00:00Z",)]),
+ ]
+ )
+ response = self._run("2024-01-01", "2024-03-31", interval="month")
+
+ result = response.results[0]
+ # First month total vs last month total; February (the middle bucket) is ignored.
+ assert result["data"][0] == 2
+ assert result["data"][1] == 3
+ assert result["days"] == ["2024-01-01", "2024-03-01"]
+
+ @snapshot_clickhouse_queries
+ def test_no_events_yields_zero_endpoints(self):
+ response = self._run("2024-05-01", "2024-05-10")
+ for result in response.results:
+ assert len(result["data"]) == 2
+ assert result["data"][0] == 0
+ assert result["data"][1] == 0
+
+ @snapshot_clickhouse_queries
+ def test_breakdown_produces_one_two_point_line_per_value(self):
+ self._create_events(
+ [
+ ("a", [("2024-05-01T10:00:00Z", {"plan": "free"})]),
+ ("b", [("2024-05-10T10:00:00Z", {"plan": "paid"}), ("2024-05-10T11:00:00Z", {"plan": "paid"})]),
+ ]
+ )
+ response = self._run(
+ "2024-05-01",
+ "2024-05-10",
+ breakdown=BreakdownFilter(breakdown="plan", breakdown_type="event"),
+ )
+
+ # Each breakdown value is its own slope line, each with exactly two points.
+ assert len(response.results) >= 2
+ for result in response.results:
+ assert len(result["data"]) == 2
+ assert len(result["labels"]) == 2
+
+ @snapshot_clickhouse_queries
+ def test_last_bucket_is_the_current_partial_period_not_trimmed(self):
+ response = self._run("2024-04-01", "2024-06-15", interval="month")
+
+ result = response.results[0]
+ # The last bucket is the current, still-accumulating month — kept as-is (the frontend dashes it).
+ assert result["days"] == ["2024-04-01", "2024-06-01"]
+ assert result["incomplete_end"] is True
+ assert response.resolved_date_range is not None
+ assert response.resolved_date_range.date_to.strftime("%Y-%m-%d") == "2024-06-15"
+
+ @snapshot_clickhouse_queries
+ def test_single_bucket_range_yields_a_one_point_series(self):
+ self._create_events([("a", [("2024-05-03T10:00:00Z",), ("2024-05-04T10:00:00Z",)])])
+ # A range within one month bucket can't form a slope — one bucket, one point.
+ response = self._run("2024-05-01", "2024-05-31", interval="month")
+
+ for result in response.results:
+ assert len(result["data"]) == 1
+
+ @snapshot_clickhouse_queries
+ def test_keeps_the_query_property_filter_alongside_the_bucket_restriction(self):
+ self._create_events(
+ [
+ ("paid_first", [("2024-05-01T10:00:00Z", {"plan": "paid"})]),
+ ("free_first", [("2024-05-01T11:00:00Z", {"plan": "free"})]),
+ ("paid_last", [("2024-05-10T10:00:00Z", {"plan": "paid"})]),
+ ]
+ )
+ query = TrendsQuery(
+ dateRange=DateRange(date_from="2024-05-01", date_to="2024-05-10"),
+ interval="day",
+ trendsFilter=TrendsFilter(display=ChartDisplayType.SLOPE_GRAPH),
+ series=[EventsNode(kind="EventsNode", event="$pageview", math="total")],
+ properties=[EventPropertyFilter(key="plan", value=["paid"], operator=PropertyOperator.EXACT)],
+ )
+ response = SlopeGraphTrendsQueryRunner(team=self.team, query=query).calculate()
+
+ result = response.results[0]
+ # The query's "plan = paid" filter is preserved, so the free event on the first day is excluded.
+ assert result["data"][0] == 1
+ assert result["data"][1] == 1
+
+ @snapshot_clickhouse_queries
+ def test_active_users_math_keeps_its_trailing_window(self):
+ # weekly_active counts users active in the trailing 7 days of each bucket. A user active only
+ # on May 10 must still count toward the last bucket (May 14), even though May 10 is neither the
+ # first nor last bucket — so the two-bucket scan restriction must not apply to this math.
+ self._create_events([("u", [("2024-05-10T10:00:00Z",)])])
+ response = self._run(
+ "2024-05-01",
+ "2024-05-14",
+ series=[EventsNode(kind="EventsNode", event="$pageview", math="weekly_active")],
+ )
+
+ result = response.results[0]
+ # May 1: nobody in its trailing window -> 0. May 14: the May 10 user is in its window -> 1.
+ assert result["data"] == [0, 1]
+
+ @snapshot_clickhouse_queries
+ def test_week_interval_scan_filter_aligns_with_the_buckets(self):
+ # The scan filter's bucket windows must line up with the trends week bucketing (incl. team
+ # week-start), or first/last week events would be wrongly excluded.
+ self._create_events(
+ [
+ ("first_week", [("2024-05-02T10:00:00Z",)]),
+ ("middle_week", [("2024-05-15T10:00:00Z",)]),
+ ("last_week", [("2024-05-27T10:00:00Z",)]),
+ ]
+ )
+ response = self._run("2024-05-01", "2024-05-28", interval="week")
+
+ result = response.results[0]
+ # First and last week each keep their event; the middle week is sliced off either way.
+ assert result["data"] == [1, 1]
+
+ @snapshot_clickhouse_queries
+ def test_unique_users_math_is_per_bucket(self):
+ self._create_events(
+ [
+ ("u1", [("2024-05-01T10:00:00Z",), ("2024-05-10T10:00:00Z",)]),
+ ("u2", [("2024-05-01T11:00:00Z",)]),
+ ]
+ )
+ response = self._run(
+ "2024-05-01",
+ "2024-05-10",
+ series=[EventsNode(kind="EventsNode", event="$pageview", math="dau")],
+ )
+
+ result = response.results[0]
+ # May 1: u1 + u2 = 2 unique; May 10: u1 = 1.
+ assert result["data"] == [2, 1]
+
+ @snapshot_clickhouse_queries
+ def test_formula_series(self):
+ self._create_events([("a", [("2024-05-01T10:00:00Z",), ("2024-05-10T10:00:00Z",), ("2024-05-10T11:00:00Z",)])])
+ query = TrendsQuery(
+ dateRange=DateRange(date_from="2024-05-01", date_to="2024-05-10"),
+ interval="day",
+ trendsFilter=TrendsFilter(display=ChartDisplayType.SLOPE_GRAPH, formula="A * 2"),
+ series=[EventsNode(kind="EventsNode", event="$pageview", math="total")],
+ )
+ response = SlopeGraphTrendsQueryRunner(team=self.team, query=query).calculate()
+
+ result = response.results[0]
+ # Formula A*2 over the two end buckets: May 1 has 1 event -> 2, May 10 has 2 -> 4.
+ assert result["data"] == [2, 4]
+
+ @snapshot_clickhouse_queries
+ def test_smoothing_does_not_starve_the_last_point(self):
+ # Smoothing is a trailing-window moving average that reads interior buckets. The slope must
+ # clear it and return the raw first/last bucket values, not a window-starved average.
+ self._create_events(
+ [
+ ("first_day", [("2024-05-01T10:00:00Z",), ("2024-05-01T11:00:00Z",)]),
+ ("middle", [("2024-05-05T10:00:00Z",), ("2024-05-06T10:00:00Z",)]),
+ ("last_day", [("2024-05-10T08:00:00Z",), ("2024-05-10T09:00:00Z",), ("2024-05-10T10:00:00Z",)]),
+ ]
+ )
+ query = TrendsQuery(
+ dateRange=DateRange(date_from="2024-05-01", date_to="2024-05-10"),
+ interval="day",
+ trendsFilter=TrendsFilter(display=ChartDisplayType.SLOPE_GRAPH, smoothingIntervals=7),
+ series=[EventsNode(kind="EventsNode", event="$pageview", math="total")],
+ )
+ response = SlopeGraphTrendsQueryRunner(team=self.team, query=query).calculate()
+
+ result = response.results[0]
+ # Same raw endpoints as the unsmoothed query — smoothing is ignored, not applied to a starved window.
+ assert result["data"] == [2, 3]
+
+ @snapshot_clickhouse_queries
+ def test_monthly_active_math_keeps_its_trailing_window(self):
+ # monthly_active is a 30-day trailing window; like weekly_active it must skip the scan restriction.
+ self._create_events([("u", [("2024-04-20T10:00:00Z",)])])
+ response = self._run(
+ "2024-04-01",
+ "2024-05-13",
+ series=[EventsNode(kind="EventsNode", event="$pageview", math="monthly_active")],
+ )
+
+ result = response.results[0]
+ # Apr 1: nobody in its trailing 30 days -> 0. May 13: Apr 20 is within its window -> 1.
+ assert result["data"] == [0, 1]
+
+ @snapshot_clickhouse_queries
+ def test_hour_interval_first_and_last_hour(self):
+ self._create_events(
+ [
+ ("first_hour", [("2024-06-14T00:15:00Z",)]),
+ ("middle_hour", [("2024-06-14T02:15:00Z",)]),
+ ("last_hour", [("2024-06-14T04:15:00Z",)]),
+ ]
+ )
+ query = TrendsQuery(
+ dateRange=DateRange(date_from="2024-06-14T00:00:00Z", date_to="2024-06-14T04:30:00Z"),
+ interval="hour",
+ trendsFilter=TrendsFilter(display=ChartDisplayType.SLOPE_GRAPH),
+ series=[EventsNode(kind="EventsNode", event="$pageview", math="total")],
+ )
+ response = SlopeGraphTrendsQueryRunner(team=self.team, query=query).calculate()
+
+ result = response.results[0]
+ # First hour (00:00) and last hour (04:00) each keep their event; the 02:00 hour is sliced off.
+ assert result["data"] == [1, 1]
+
+ @snapshot_clickhouse_queries
+ def test_non_utc_team_timezone(self):
+ self.team.timezone = "US/Pacific"
+ self.team.save()
+ # 20:00 UTC is ~13:00 the same calendar day in Pacific, so these land on May 1 and May 10 PT.
+ self._create_events(
+ [
+ ("first", [("2024-05-01T20:00:00Z",)]),
+ ("middle", [("2024-05-05T20:00:00Z",)]),
+ ("last", [("2024-05-10T20:00:00Z",)]),
+ ]
+ )
+ response = self._run("2024-05-01", "2024-05-10")
+
+ result = response.results[0]
+ # The scan filter aligns to the team's timezone, so the first and last Pacific days are kept.
+ assert result["data"] == [1, 1]
+
+ @snapshot_clickhouse_queries
+ def test_relative_date_range(self):
+ # "now" is frozen at 2024-06-15, so the last 7 days span 2024-06-08..2024-06-15.
+ self._create_events(
+ [
+ ("first", [("2024-06-08T10:00:00Z",)]),
+ ("middle", [("2024-06-11T10:00:00Z",)]),
+ ("last", [("2024-06-15T10:00:00Z",)]),
+ ]
+ )
+ response = self._run("-7d", None)
+
+ result = response.results[0]
+ assert result["data"] == [1, 1]
+
+ @snapshot_clickhouse_queries
+ def test_preserves_a_property_group_filter(self):
+ self._create_events(
+ [
+ ("paid_first", [("2024-05-01T10:00:00Z", {"plan": "paid"})]),
+ ("free_first", [("2024-05-01T11:00:00Z", {"plan": "free"})]),
+ ("paid_last", [("2024-05-10T10:00:00Z", {"plan": "paid"})]),
+ ]
+ )
+ group = PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[EventPropertyFilter(key="plan", value=["paid"], operator=PropertyOperator.EXACT)],
+ )
+ ],
+ )
+ query = TrendsQuery(
+ dateRange=DateRange(date_from="2024-05-01", date_to="2024-05-10"),
+ interval="day",
+ trendsFilter=TrendsFilter(display=ChartDisplayType.SLOPE_GRAPH),
+ series=[EventsNode(kind="EventsNode", event="$pageview", math="total")],
+ properties=group,
+ )
+ response = SlopeGraphTrendsQueryRunner(team=self.team, query=query).calculate()
+
+ result = response.results[0]
+ # The group's "plan = paid" survives the bucket restriction, so the free event is excluded.
+ assert result["data"] == [1, 1]
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 7fd43b4f977e..c1454692fdf3 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -362,6 +362,18 @@ def get_query_runner(
user=user,
)
+ if display_type == ChartDisplayType.SLOPE_GRAPH:
+ from .insights.trends.slope_graph_trends_query_runner import SlopeGraphTrendsQueryRunner
+
+ return SlopeGraphTrendsQueryRunner(
+ query=query_obj,
+ team=team,
+ timings=timings,
+ limit_context=limit_context,
+ modifiers=modifiers,
+ user=user,
+ )
+
from .insights.trends.trends_query_runner import TrendsQueryRunner
return TrendsQueryRunner(
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index bfa4f13ae60b..84e2c85e8b67 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -436,6 +436,7 @@ class Display(StrEnum):
CALENDAR_HEATMAP = "CalendarHeatmap"
TWO_DIMENSIONAL_HEATMAP = "TwoDimensionalHeatmap"
BOX_PLOT = "BoxPlot"
+ SLOPE_GRAPH = "SlopeGraph"
class YAxisScaleType(StrEnum):
@@ -566,6 +567,7 @@ class ChartDisplayType(StrEnum):
CALENDAR_HEATMAP = "CalendarHeatmap"
TWO_DIMENSIONAL_HEATMAP = "TwoDimensionalHeatmap"
BOX_PLOT = "BoxPlot"
+ SLOPE_GRAPH = "SlopeGraph"
class ColorMode(StrEnum):
diff --git a/posthog/schema_helpers.py b/posthog/schema_helpers.py
index 5489ee404020..5519b6e4eb8d 100644
--- a/posthog/schema_helpers.py
+++ b/posthog/schema_helpers.py
@@ -198,6 +198,10 @@ def grouped_chart_display_types(display: ChartDisplayType) -> ChartDisplayType:
# separate runner
return ChartDisplayType.BOX_PLOT
+ case ChartDisplayType.SLOPE_GRAPH:
+ # separate runner — only the two range endpoints, cached on its own key
+ return ChartDisplayType.SLOPE_GRAPH
+
case ChartDisplayType.AUTO:
return ChartDisplayType.AUTO
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 0bc686fa2c3e..c0283ba273cb 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1936,6 +1936,7 @@ export const ChartDisplayTypeApi = {
CalendarHeatmap: 'CalendarHeatmap',
TwoDimensionalHeatmap: 'TwoDimensionalHeatmap',
BoxPlot: 'BoxPlot',
+ SlopeGraph: 'SlopeGraph',
} as const
export interface TrendsFormulaNodeApi {
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 0a68407abc4e..c087a0bc81e6 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -1449,6 +1449,7 @@ export const ChartDisplayTypeApi = {
CalendarHeatmap: 'CalendarHeatmap',
TwoDimensionalHeatmap: 'TwoDimensionalHeatmap',
BoxPlot: 'BoxPlot',
+ SlopeGraph: 'SlopeGraph',
} as const
export interface TrendsFormulaNodeApi {
diff --git a/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx
new file mode 100644
index 000000000000..161b08957f99
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/TrendsSlopeChart/TrendsSlopeChart.tsx
@@ -0,0 +1,86 @@
+import { useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { SlopeChart, createXAxisTickCallback } from '@posthog/quill-charts'
+import type { Series, SlopeChartConfig, SlopeSeriesMeta } from '@posthog/quill-charts'
+
+import { buildTheme } from 'lib/charts/utils/theme'
+import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
+import { InsightEmptyState } from 'scenes/insights/EmptyStates'
+import { insightLogic } from 'scenes/insights/insightLogic'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
+import type { IndexedTrendResult } from 'scenes/trends/types'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+import { InsightVizNode } from '~/queries/schema/schema-general'
+import { QueryContext } from '~/queries/types'
+
+import { makeChartErrorHandler } from '../shared/chartErrorHandler'
+
+interface TrendsSlopeChartProps {
+ context?: QueryContext<InsightVizNode>
+}
+
+const handleChartError = makeChartErrorHandler('trends-slope-chart')
+
+export function TrendsSlopeChart({ context }: TrendsSlopeChartProps): JSX.Element | null {
+ const { isDarkModeOn } = useValues(themeLogic)
+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+ const { insightProps } = useValues(insightLogic)
+
+ const { indexedResults, currentPeriodResult, getTrendsColor, getTrendsHidden, trendsFilter, interval, showLegend } =
+ useValues(trendsDataLogic(insightProps))
+ const { timezone } = useValues(insightVizDataLogic(insightProps))
+ const { baseCurrency } = useValues(teamLogic)
+
+ // The backend returns each series as its two points (first and last interval bucket) with two
+ // matching labels, so we just map to quill series: resolve the theme colour, drop legend-hidden
+ // series, and forward the backend's `incomplete_end` flag (which dashes the connector). A
+ // single-bucket range comes back as one point and is dropped — there's no slope to draw.
+ const labels = currentPeriodResult?.labels ?? []
+ const series = useMemo<Series<SlopeSeriesMeta>[]>(() => {
+ return (indexedResults ?? [])
+ .filter((result: IndexedTrendResult) => !getTrendsHidden(result) && (result.data?.length ?? 0) >= 2)
+ .map((result: IndexedTrendResult) => ({
+ key: String(result.id),
+ label: result.label ?? '',
+ color: getTrendsColor(result),
+ data: result.data,
+ meta: result.incomplete_end ? { incompleteEnd: true } : undefined,
+ }))
+ }, [indexedResults, getTrendsColor, getTrendsHidden])
+
+ const config = useMemo<SlopeChartConfig>(
+ () => ({
+ valueFormatter: (value: number) => formatAggregationAxisValue(trendsFilter, value, baseCurrency),
+ // The chart's own legend carries the series name + first-to-last change, gated on the
+ // insight's "Show legend" toggle, so there's only ever one legend and no in-chart names.
+ showSeriesLabels: false,
+ legend: { show: !!showLegend, position: 'bottom' },
+ xTickFormatter: createXAxisTickCallback({
+ interval: interval ?? 'day',
+ allDays: currentPeriodResult?.days ?? [],
+ timezone,
+ }),
+ }),
+ [trendsFilter, baseCurrency, showLegend, interval, currentPeriodResult, timezone]
+ )
+
+ if (series.length === 0) {
+ return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />
+ }
+
+ return (
+ <SlopeChart
+ series={series}
+ labels={labels}
+ theme={theme}
+ config={config}
+ className="SlopeGraph"
+ dataAttr="trends-slope-graph"
+ onError={handleChartError}
+ />
+ )
+}
diff --git a/products/product_analytics/skills/choosing-trend-or-slope-view/SKILL.md b/products/product_analytics/skills/choosing-trend-or-slope-view/SKILL.md
index 25e8b5f218c7..f4a5d0694595 100644
--- a/products/product_analytics/skills/choosing-trend-or-slope-view/SKILL.md
+++ b/products/product_analytics/skills/choosing-trend-or-slope-view/SKILL.md
@@ -63,11 +63,15 @@ are the points you want compared (the slope uses the first and last interval).
## Important limits
-- **Slope is a view, not a saved insight type.** It lives on Max's inline trends
- result card (the `query-trends` visualizer). A _saved_ insight has no slope
- display — `SlopeChart` is not a `ChartDisplayType`, so `posthog:insight-create`
- with a slope display is not available. If the user wants a saved/dashboard chart,
- save the line and offer the slope as the inline view, or note the limitation.
+- **Two surfaces, one computation.** Both the inline slope (Max's `query-trends`
+ result card) and the saved-insight slope (`ChartDisplayType.SlopeGraph`, behind the
+ `slope-graph-insight` feature flag) show the same thing: the first interval's value
+ vs the last interval's value, at the chosen group-by interval. The grouping defines
+ the slope — group by month to compare the first vs last month, by day for the first
+ vs last day. Use the inline view for a quick before→after on a result you're already
+ looking at; reach for the saved display to persist it on a dashboard where the flag
+ is enabled. A still-accumulating final period is shown as-is with a dashed connector,
+ the same affordance the line chart uses for an incomplete tail.
- For period-over-period on a single series (this month vs last), a line with
`compareFilter: { "compare": true }` overlays the two periods; a slope is the
better fit when comparing the endpoints of **many** series at once.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 82922fcb3f9a..146d9293a36e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2187,6 +2187,7 @@ export namespace Schemas {
CalendarHeatmap: 'CalendarHeatmap',
TwoDimensionalHeatmap: 'TwoDimensionalHeatmap',
BoxPlot: 'BoxPlot',
+ SlopeGraph: 'SlopeGraph',
} as const;
export interface TrendsFormulaNode {
diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.ts
index cd0f2767b258..2c9b1f1d3b50 100644
--- a/services/mcp/src/tools/generated/query-wrappers.ts
+++ b/services/mcp/src/tools/generated/query-wrappers.ts
@@ -509,6 +509,7 @@ const AssistantTrendsFilter = z.object({
'CalendarHeatmap',
'TwoDimensionalHeatmap',
'BoxPlot',
+ 'SlopeGraph',
])
.describe(
'Visualization type. Available values: `ActionsLineGraph` - time-series line chart; most common option, as it shows change over time. `ActionsBar` - time-series bar chart. `ActionsAreaGraph` - time-series area chart. `ActionsLineGraphCumulative` - cumulative time-series line chart; good for cumulative metrics. `BoldNumber` - total value single large number. Use when user explicitly asks for a single output number. You CANNOT use this with breakdown or if the insight has more than one series. `ActionsBarValue` - total value (NOT time-series) bar chart; good for categorical data. `ActionsPie` - total value pie chart; good for visualizing proportions. `ActionsTable` - total value table; good when using breakdown to list users or other entities. `WorldMap` - total value world map; use when breaking down by country name using property `$geoip_country_name`, and only then.'
diff --git a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
index 4f2834d449b2..c61eeb2b8cef 100644
--- a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
+++ b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
@@ -49,7 +49,11 @@ function calculateTotal(results: TrendsResultItem[]): number {
export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): ReactElement {
const displayType = getDisplayType(query)
- const [chartMode, setChartMode] = useState<ChartMode>(isBarChart(displayType) ? 'bar' : 'line')
+ // Honour the backend slope runner: a SlopeGraph query already comes back as two points per series,
+ // so open straight into slope mode rather than line + a manual toggle.
+ const [chartMode, setChartMode] = useState<ChartMode>(
+ isBarChart(displayType) ? 'bar' : displayType === 'SlopeGraph' ? 'slope' : 'line'
+ )
if (!results || results.length === 0) {
return (
@@ -95,6 +99,7 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea
label: getSeriesLabel(item, i),
data: item.data ?? [],
days: item.days,
+ incompleteEnd: !!item.incomplete_end,
}))
const yAxisLabel = results.length === 1 && results[0] ? getSeriesLabel(results[0], 0) : undefined
@@ -107,20 +112,19 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea
// Build only the active mode's chart model — toggling shouldn't recompute the hidden one.
const renderChart = (): ReactElement => {
if (effectiveMode === 'slope') {
+ // Hand quill the full series and labels — it reduces to the first and last point itself,
+ // so the slope shaping lives once in quill, not here. The backend's incomplete_end flag is
+ // forwarded so the provisional end dashes exactly as it does in the insight.
const slopeSeries = trendResults
- .map((item, index) => {
- if (item.data.length < 2) {
- return null
- }
- return {
- key: String(item.id),
- label: item.label,
- color: colorAt(index),
- data: [item.data[0]!, item.data[item.data.length - 1]!],
- }
- })
- .filter((s): s is NonNullable<typeof s> => s !== null)
- const slopeLabels = [formatDate(labels[0]!), formatDate(labels[labels.length - 1]!)]
+ .filter((item) => item.data.length >= 2)
+ .map((item) => ({
+ key: String(item.id),
+ label: item.label,
+ color: colorAt(item.id),
+ data: item.data,
+ meta: item.incompleteEnd ? { incompleteEnd: true } : undefined,
+ }))
+ const slopeLabels = labels.map((label) => formatDate(String(label)))
return (
<SlopeChart
series={slopeSeries}
diff --git a/services/mcp/src/ui-apps/components/types.ts b/services/mcp/src/ui-apps/components/types.ts
index 1bf5b9b53969..e15b7ca050ea 100644
--- a/services/mcp/src/ui-apps/components/types.ts
+++ b/services/mcp/src/ui-apps/components/types.ts
@@ -21,6 +21,7 @@ export type ChartDisplayType =
| 'ActionsPie'
| 'ActionsTable'
| 'WorldMap'
+ | 'SlopeGraph'
export interface TrendsFilter {
display?: ChartDisplayType
@@ -77,6 +78,9 @@ export interface TrendsResultItem {
days?: string[]
count?: number
aggregated_value?: number
+ /** Slope graph only: the last bucket is the current, still-accumulating period (set by the
+ * backend SlopeGraphTrendsQueryRunner) so the slope dashes the provisional end like the insight. */
+ incomplete_end?: boolean
action?: {
name?: string
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
index 5f3517d9b43d..69671540b26c 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
@@ -3810,7 +3810,8 @@
"WorldMap",
"CalendarHeatmap",
"TwoDimensionalHeatmap",
- "BoxPlot"
+ "BoxPlot",
+ "SlopeGraph"
],
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
index 0868bc5f566c..47eb67b2e94f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
@@ -3622,7 +3622,8 @@
"WorldMap",
"CalendarHeatmap",
"TwoDimensionalHeatmap",
- "BoxPlot"
+ "BoxPlot",
+ "SlopeGraph"
],
"type": "string"
},