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(experiments): add pagination to the shared metrics view (#60755)

Rodrigo Iloroc9344172cdcc
diff --git a/ee/clickhouse/views/experiment_saved_metrics.py b/ee/clickhouse/views/experiment_saved_metrics.py
index 42eb3859a89a..1f2e11428118 100644
--- a/ee/clickhouse/views/experiment_saved_metrics.py
+++ b/ee/clickhouse/views/experiment_saved_metrics.py
@@ -1,7 +1,7 @@
from django.db.models.functions import Lower
from drf_spectacular.utils import extend_schema
-from rest_framework import serializers, viewsets
+from rest_framework import filters, serializers, viewsets
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
@@ -137,8 +137,10 @@ class ExperimentSavedMetricSerializer(
@extend_schema(extensions={"x-swagger-tag": "experiment_saved_metrics", "x-product": "experiments"})
class ExperimentSavedMetricViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
scope_object = "experiment_saved_metric"
- queryset = ExperimentSavedMetric.objects.prefetch_related("created_by").order_by(Lower("name")).all()
+ queryset = ExperimentSavedMetric.objects.prefetch_related("created_by").order_by(Lower("name")).distinct()
serializer_class = ExperimentSavedMetricSerializer
+ filter_backends = [filters.SearchFilter]
+ search_fields = ["name", "description", "tagged_items__tag__name"]
def perform_destroy(self, instance: ExperimentSavedMetric) -> None:
service = ExperimentSavedMetricService(team=self.team, user=self.request.user)
diff --git a/ee/clickhouse/views/test/test_experiment_saved_metrics.py b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
index 35c574f7808c..8c2af49e426b 100644
--- a/ee/clickhouse/views/test/test_experiment_saved_metrics.py
+++ b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
@@ -1,5 +1,6 @@
from unittest.mock import patch
+from parameterized import parameterized
from rest_framework import status
from products.experiments.backend.experiment_saved_metric_service import ExperimentSavedMetricService
@@ -922,3 +923,61 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
# Verify the old name is preserved
self.assertEqual(response.json()["query"]["source"]["name"], "Action to Delete")
self.assertEqual(response.json()["query"]["source"]["id"], action_id)
+
+ def _create_saved_metric(self, name: str, description: str = "", tags: list[str] | None = None) -> int:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/experiment_saved_metrics/",
+ data={
+ "name": name,
+ "description": description,
+ "tags": tags or [],
+ "query": {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ },
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ return response.json()["id"]
+
+ @parameterized.expand(
+ [
+ ("by_name", "alpha", {"Alpha conversion"}),
+ ("by_description", "revenue tracker", {"Beta signups"}),
+ ("by_tag", "growth", {"Beta signups"}),
+ ("no_match", "zzz-nothing", set()),
+ ]
+ )
+ def test_search_filters_saved_metrics(self, _name: str, search: str, expected_names: set[str]) -> None:
+ self._create_saved_metric("Alpha conversion", description="checkout funnel")
+ self._create_saved_metric("Beta signups", description="revenue tracker thing", tags=["growth"])
+
+ response = self.client.get(f"/api/projects/{self.team.id}/experiment_saved_metrics/?search={search}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ returned = {row["name"] for row in response.json()["results"]}
+ self.assertEqual(returned, expected_names)
+
+ def test_search_returns_each_metric_once_with_multiple_matching_tags(self) -> None:
+ self._create_saved_metric("Tagged metric", description="", tags=["growth", "growth-team"])
+
+ response = self.client.get(f"/api/projects/{self.team.id}/experiment_saved_metrics/?search=growth")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ self.assertEqual(body["count"], 1)
+ self.assertEqual(len(body["results"]), 1)
+
+ def test_list_paginates_with_limit_and_offset(self) -> None:
+ for i in range(5):
+ self._create_saved_metric(f"Metric {i:02d}")
+
+ page1 = self.client.get(f"/api/projects/{self.team.id}/experiment_saved_metrics/?limit=2&offset=0").json()
+ page2 = self.client.get(f"/api/projects/{self.team.id}/experiment_saved_metrics/?limit=2&offset=2").json()
+
+ self.assertEqual(page1["count"], 5)
+ self.assertEqual(len(page1["results"]), 2)
+ self.assertEqual(len(page2["results"]), 2)
+ ids_page1 = {row["id"] for row in page1["results"]}
+ ids_page2 = {row["id"] for row in page2["results"]}
+ self.assertEqual(ids_page1 & ids_page2, set())
diff --git a/frontend/src/scenes/experiments/SharedMetrics/SharedMetrics.tsx b/frontend/src/scenes/experiments/SharedMetrics/SharedMetrics.tsx
index 9148a25da547..535504354378 100644
--- a/frontend/src/scenes/experiments/SharedMetrics/SharedMetrics.tsx
+++ b/frontend/src/scenes/experiments/SharedMetrics/SharedMetrics.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { IconCopy, IconPencil, IconTrash } from '@posthog/icons'
+import { IconChevronLeft, IconChevronRight, IconCopy, IconPencil, IconTrash } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
@@ -17,6 +17,7 @@ import {
import { More } from 'lib/lemon-ui/LemonButton/More'
import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
+import { pluralize } from 'lib/utils'
import stringWithWBR from 'lib/utils/stringWithWBR'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -24,10 +25,10 @@ import { urls } from 'scenes/urls'
import { tagsModel } from '~/models/tagsModel'
import { NodeKind } from '~/queries/schema/schema-general'
-import { isLegacySharedMetric, matchesSharedMetricSearch } from '../utils'
+import { isLegacySharedMetric } from '../utils'
import { InlineTagEditor } from './InlineTagEditor'
import { SharedMetric } from './sharedMetricLogic'
-import { sharedMetricsLogic } from './sharedMetricsLogic'
+import { PAGE_SIZE, sharedMetricsLogic } from './sharedMetricsLogic'
export const scene: SceneExport = {
component: SharedMetrics,
@@ -35,14 +36,13 @@ export const scene: SceneExport = {
}
export function SharedMetrics(): JSX.Element {
- const { sharedMetrics, sharedMetricsLoading, searchTerm, savingTagsMetricId } = useValues(sharedMetricsLogic)
- const { setSearchTerm, updateSharedMetricTags, deleteSharedMetric } = useActions(sharedMetricsLogic)
+ const { sharedMetrics, sharedMetricsLoading, searchTerm, savingTagsMetricId, count, page } =
+ useValues(sharedMetricsLogic)
+ const { setSearchTerm, setPage, updateSharedMetricTags, deleteSharedMetric } = useActions(sharedMetricsLogic)
const { tags: allTags } = useValues(tagsModel)
- const searchLower = searchTerm.toLowerCase()
- const filteredMetrics = searchTerm
- ? (sharedMetrics || []).filter((metric) => matchesSharedMetricSearch(metric, searchLower))
- : sharedMetrics || []
+ const startCount = count === 0 ? 0 : (page - 1) * PAGE_SIZE + 1
+ const endCount = page * PAGE_SIZE < count ? page * PAGE_SIZE : count
const columns: LemonTableColumns<SharedMetric> = [
{
@@ -70,7 +70,6 @@ export function SharedMetrics(): JSX.Element {
/>
)
},
- sorter: (a, b) => a.name.localeCompare(b.name),
},
{
key: 'description',
@@ -178,22 +177,51 @@ export function SharedMetrics(): JSX.Element {
having to set them up each time.
</LemonBanner>
<div className="flex justify-between items-center gap-2">
- <LemonInput
- type="search"
- placeholder="Search shared metrics..."
- value={searchTerm}
- onChange={setSearchTerm}
- />
+ <div className="flex items-center gap-2">
+ <LemonInput
+ type="search"
+ placeholder="Search shared metrics..."
+ value={searchTerm}
+ onChange={setSearchTerm}
+ />
+ {count ? (
+ <span className="text-secondary whitespace-nowrap">
+ {`${startCount}${endCount > startCount ? '-' + endCount : ''} of ${pluralize(
+ count,
+ 'metric'
+ )}`}
+ </span>
+ ) : null}
+ </div>
<LemonButton size="small" type="primary" to={urls.experimentsSharedMetric('new')}>
New shared metric
</LemonButton>
</div>
<LemonTable
columns={columns}
- dataSource={filteredMetrics}
+ dataSource={sharedMetrics}
loading={sharedMetricsLoading}
emptyState={<div>You haven't created any shared metrics yet.</div>}
/>
+ {count > PAGE_SIZE ? (
+ <div className="flex items-center justify-end gap-1">
+ <span className="text-secondary whitespace-nowrap">
+ {`${startCount}${endCount > startCount ? '-' + endCount : ''} of ${pluralize(count, 'metric')}`}
+ </span>
+ <LemonButton
+ icon={<IconChevronLeft />}
+ size="small"
+ disabledReason={page <= 1 ? 'No previous page' : undefined}
+ onClick={() => setPage(page - 1)}
+ />
+ <LemonButton
+ icon={<IconChevronRight />}
+ size="small"
+ disabledReason={endCount >= count ? 'No next page' : undefined}
+ onClick={() => setPage(page + 1)}
+ />
+ </div>
+ ) : null}
</div>
)
}
diff --git a/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.test.ts b/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.test.ts
new file mode 100644
index 000000000000..68b32dee610f
--- /dev/null
+++ b/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.test.ts
@@ -0,0 +1,76 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { PAGE_SIZE, sharedMetricsLogic } from './sharedMetricsLogic'
+
+describe('sharedMetricsLogic', () => {
+ let logic: ReturnType<typeof sharedMetricsLogic.build>
+
+ const makeMetrics = (count: number, search: string, offset: number): any => ({
+ count,
+ results: [
+ { id: 1, name: `${search || 'metric'} a` },
+ { id: 2, name: `${search || 'metric'} b` },
+ ].slice(offset > 0 ? 1 : 0),
+ })
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiment_saved_metrics': (req) => [
+ 200,
+ makeMetrics(
+ 2,
+ req.url.searchParams.get('search') ?? '',
+ parseInt(req.url.searchParams.get('offset') ?? '0')
+ ),
+ ],
+ },
+ })
+ initKeaTests()
+ logic = sharedMetricsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => logic.unmount())
+
+ it('loads the first page with limit and offset 0', async () => {
+ jest.spyOn(api, 'get')
+ await expectLogic(logic, () => {
+ logic.actions.loadSharedMetrics()
+ }).toFinishAllListeners()
+ expect(api.get).toHaveBeenCalledWith(expect.stringContaining(`limit=${PAGE_SIZE}`))
+ expect(api.get).toHaveBeenCalledWith(expect.stringContaining('offset=0'))
+ await expectLogic(logic).toMatchValues({ count: 2 })
+ })
+
+ it('setPage reloads with the correct offset', async () => {
+ jest.spyOn(api, 'get')
+ await expectLogic(logic, () => {
+ logic.actions.setPage(2)
+ }).toFinishAllListeners()
+ expect(api.get).toHaveBeenLastCalledWith(expect.stringContaining(`offset=${PAGE_SIZE}`))
+ await expectLogic(logic).toMatchValues({ page: 2 })
+ })
+
+ it('setSearchTerm resets page to 1 and reloads with search', async () => {
+ logic.actions.setPage(3)
+ await expectLogic(logic).toMatchValues({ page: 3 })
+
+ jest.spyOn(api, 'get')
+ await expectLogic(logic, () => {
+ logic.actions.setSearchTerm('revenue')
+ }).toFinishAllListeners()
+ await expectLogic(logic).toMatchValues({ page: 1, searchTerm: 'revenue' })
+ expect(api.get).toHaveBeenLastCalledWith(expect.stringContaining('search=revenue'))
+ })
+
+ it('exposes current page and total count', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic).toMatchValues({ page: 1, count: 2 })
+ })
+})
diff --git a/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.tsx b/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.tsx
index aef3138ffe73..e2d002a3a542 100644
--- a/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.tsx
+++ b/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.tsx
@@ -3,12 +3,15 @@ import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
-import api from 'lib/api'
+import api, { CountedPaginatedResponse } from 'lib/api'
+import { toParams } from 'lib/utils'
import { teamLogic } from 'scenes/teamLogic'
import type { SharedMetric } from './sharedMetricLogic'
import type { sharedMetricsLogicType } from './sharedMetricsLogicType'
+export const PAGE_SIZE = 100
+
export const sharedMetricsLogic = kea<sharedMetricsLogicType>([
path(['scenes', 'experiments', 'sharedMetricsLogic']),
connect(() => ({ values: [teamLogic, ['currentProjectId']] })),
@@ -16,6 +19,8 @@ export const sharedMetricsLogic = kea<sharedMetricsLogicType>([
actions({
updateSharedMetricTags: (metricId: SharedMetric['id'], tags: string[]) => ({ metricId, tags }),
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
+ setPage: (page: number) => ({ page }),
+ setCount: (count: number) => ({ count }),
deleteSharedMetric: (metricId: SharedMetric['id']) => ({ metricId }),
}),
@@ -34,21 +39,49 @@ export const sharedMetricsLogic = kea<sharedMetricsLogicType>([
setSearchTerm: (_, { searchTerm }) => searchTerm,
},
],
+ page: [
+ 1,
+ {
+ setPage: (_, { page }) => page,
+ setSearchTerm: () => 1,
+ },
+ ],
+ count: [
+ 0,
+ {
+ setCount: (_, { count }) => count,
+ },
+ ],
}),
- loaders(({ values }) => ({
+ loaders(({ values, actions }) => ({
sharedMetrics: [
[] as SharedMetric[],
{
loadSharedMetrics: async () => {
- const response = await api.get(`api/projects/${values.currentProjectId}/experiment_saved_metrics`)
- return response.results as SharedMetric[]
+ const params = toParams({
+ limit: PAGE_SIZE,
+ offset: (values.page - 1) * PAGE_SIZE,
+ search: values.searchTerm || undefined,
+ })
+ const response: CountedPaginatedResponse<SharedMetric> = await api.get(
+ `api/projects/${values.currentProjectId}/experiment_saved_metrics?${params}`
+ )
+ actions.setCount(response.count)
+ return response.results
},
},
],
})),
listeners(({ actions, values }) => ({
+ setPage: async () => {
+ actions.loadSharedMetrics()
+ },
+ setSearchTerm: async (_, breakpoint) => {
+ await breakpoint(300)
+ actions.loadSharedMetrics()
+ },
updateSharedMetricTags: async ({ metricId, tags }) => {
try {
await api.update(`api/projects/${values.currentProjectId}/experiment_saved_metrics/${metricId}`, {
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 66b3dcc01e7b..529d0d4099d3 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -729,6 +729,10 @@ export type ExperimentSavedMetricsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * A search term.
+ */
+ search?: string
}
export type ExperimentsListParams = {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e0eea881cc6e..cadde96de65a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -46587,6 +46587,10 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * A search term.
+ */
+ search?: string;
};
export type ExperimentsListParams = {
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 554442876f3e..a126d410d13f 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -19,6 +19,7 @@ export const ExperimentSavedMetricsListParams = /* @__PURE__ */ zod.object({
export const ExperimentSavedMetricsListQueryParams = /* @__PURE__ */ zod.object({
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
+ search: zod.string().optional().describe('A search term.'),
})
export const ExperimentSavedMetricsCreateParams = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 255f5b063fec..17bf9bfddc99 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -477,6 +477,7 @@ const experimentSavedMetricsList = (): ToolBase<
query: {
limit: params.limit,
offset: params.offset,
+ search: params.search,
},
})
const filtered = {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-saved-metrics-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-saved-metrics-list.json
index 8331b796ac73..bc560e594d69 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-saved-metrics-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-saved-metrics-list.json
@@ -8,6 +8,10 @@
"offset": {
"description": "The initial index from which to return the results.",
"type": "number"
+ },
+ "search": {
+ "description": "A search term.",
+ "type": "string"
}
},
"type": "object"