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(bi): add searchable catalog metric picker (#124961)

Marius Andra25b21e345f14
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 63e6a000218f..93faf28f13b8 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -436,7 +436,7 @@ Implementation audit, October 28, 2026. These are proposed integration contracts
- [x] Adopt the catalog overwrite-confirmation flow for worksheet metric proposals. Preserve entered values on cancel, allow retry, and keep overwritten metrics proposed.
- [x] Show catalog trust context when exploring a metric: approval and drift status, unit, owner, and stable identity. Saved copies retain metadata from copy time, labeled **Catalog status when copied (unverified)** without positive approval styling. Only Proposed and Approved statuses are recorded. Older copies explicitly say no status was recorded. The metadata is editable worksheet content, not verified provenance or a live approval; authors are directed to the current catalog entry. Live version checks remain shared-layer work.
-- [ ] Add deliberate, searchable metric discovery in BI using the existing catalog search API. Handle loading, failure, no matches, pagination, and unsupported definition kinds explicitly.
+- [x] Add deliberate, searchable metric discovery in BI using the existing catalog search API. The picker handles loading, failure, no matches, pagination, and unsupported definition kinds explicitly.
- [ ] Surface existing field descriptions and data-quality context in the data pane. Preserve raw field identities and distinguish certification from current check health.
### Shared-layer requests
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1173d0baf8d3..65425bee9ef8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6690,6 +6690,18 @@ snapshots:
hash: v1.k794b7964.31703656b8a306a7d49b09cc8f656c7c42736668885c84bc98bb313bf1ebf501.mQsSNC-D51SFFN3Ck7nPjwPYTva-iHTshY5Nn4Nprqg
products-autoresearch-training-run-row--run-produced-the-champion--light:
hash: v1.k794b7964.0ca7c29c5445ee44d47a1cef4c7c8f6d331310b0176e173f43530b99079e4e86.tjZPXyNflXDsKIgM8KBKf31qxG5l2W-_GViGBr51tn0
+ products-business-intelligence-catalog-metric-picker--empty--dark:
+ hash: v1.k794b7964.d720ec072a609015330a04f41d87b1a818f8220e17f1d06ffc29b2efaecba461.g9DVnk37vCW2Y1DYp4RRiW9zJroZLiUF1k2hKwWJCe4
+ products-business-intelligence-catalog-metric-picker--empty--light:
+ hash: v1.k794b7964.f534a88199894d3c8fa4d8990b25c45d6617495dfe5b76eb43bb1ad2a38b4a67.PSXPc4BqPVgHa9oBoUXc363PVvm2pbnJYFmpWuYVc7k
+ products-business-intelligence-catalog-metric-picker--error--dark:
+ hash: v1.k794b7964.d720ec072a609015330a04f41d87b1a818f8220e17f1d06ffc29b2efaecba461.tVkqzRsssFFOiAbYtXU9RTOnJ43gfGy_p_Iy9qd1lsk
+ products-business-intelligence-catalog-metric-picker--error--light:
+ hash: v1.k794b7964.f534a88199894d3c8fa4d8990b25c45d6617495dfe5b76eb43bb1ad2a38b4a67.R_YB0437a_f0kOwNGZiCtwPzXjpalwtZ72BgtPXUt5M
+ products-business-intelligence-catalog-metric-picker--metrics--dark:
+ hash: v1.k794b7964.d720ec072a609015330a04f41d87b1a818f8220e17f1d06ffc29b2efaecba461.GorW3yGOHai9TqWzRjVR0H6m62T8qiKA_M2QwdehxDM
+ products-business-intelligence-catalog-metric-picker--metrics--light:
+ hash: v1.k794b7964.f534a88199894d3c8fa4d8990b25c45d6617495dfe5b76eb43bb1ad2a38b4a67.gn4BCzeyH8nRlL4JslkOFstSnrR0dxEWNOnyJlL_a8o
products-business-intelligence-chart-years--many-years-narrow--dark:
hash: v1.k794b7964.54ae233495f20e81b0fd03abe4649f9147b0d87142b515fce894b1325b57b104.67n9Ipd2-Q0jG4n-8sao7_rHt4kFjQghNhHqbr-vAWQ
products-business-intelligence-chart-years--many-years-narrow--light:
@@ -6831,9 +6843,9 @@ snapshots:
products-business-intelligence-worksheet-exploration--table-conditional-formatting--light:
hash: v1.k794b7964.351c0fda7bf0696591ba8fae59fee71acf2a28865cfc5ce637468823c8303fdd.h8tIQMd2l9RRcDLLWKJ9e7fOe_vtc4lvbO0Ak93-5WI
products-business-intelligence-worksheets--worksheets--dark:
- hash: v1.k794b7964.d1df9387de5567d9926e1a4f1af6432e787451bd86b2791c80ead800a38f0bc0.oy5LT9ZePUH1pJcr6VUR75vT8i76u9g9p6MU3WHzqgY
+ hash: v1.k794b7964.5c549c48bdda54c0e83156cf4c8966be00db5df63f9fea9e5ce33cd6795362c6.mFBUqCDqd9sZIV8zk8ipCmRqrwLL0-qYHdoRXf3s_Sg
products-business-intelligence-worksheets--worksheets--light:
- hash: v1.k794b7964.0654432f426ef88b0ef02fc6e2565d438ac2ca026366683b4f1c06db07148c03.z-7Vqzq0H7LR9bxYgn7nLIKxX45E_4f1U9INfUp67wg
+ hash: v1.k794b7964.11735ab4f2ae078466c442dd98cac171f7a3b7323bd0abe19e6bbe39accf2aad.e18DKhym2YOvkIka0-Q7spLyWgPZrCQE3jibpbLYCwY
products-dashboards--dashboard-states--dark:
hash: v1.k794b7964.cc591635f83447f7bcfb802062302b8b1bbcd51826110b12fa0f68d4830dcfd3.CIgt_KxCyQRgbn7DPF4MDXc5JBlSxbaCPS0Snyx3cRs
products-dashboards--dashboard-states--light:
diff --git a/products/business_intelligence/frontend/BICatalogMetricPicker.stories.tsx b/products/business_intelligence/frontend/BICatalogMetricPicker.stories.tsx
new file mode 100644
index 000000000000..efd24c54883c
--- /dev/null
+++ b/products/business_intelligence/frontend/BICatalogMetricPicker.stories.tsx
@@ -0,0 +1,69 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { waitFor, within } from '@testing-library/dom'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { expect, userEvent } from 'storybook/test'
+
+import { BICatalogMetricPicker } from './BICatalogMetricPicker'
+import { biCatalogPickerLogic } from './biCatalogPickerLogic'
+
+const meta: Meta<typeof BICatalogMetricPicker> = {
+ title: 'Products/Business intelligence/Catalog metric picker',
+ component: BICatalogMetricPicker,
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/': ({ request }) => ({
+ count: 3,
+ next: null,
+ results: [
+ {
+ id: 'revenue',
+ name: 'revenue',
+ description: 'Revenue from completed purchases, in USD.',
+ status: 'approved',
+ is_drifted: false,
+ definition: { kind: 'HogQLQuery', query: 'SELECT 42 AS revenue' },
+ },
+ {
+ id: 'purchases',
+ name: 'purchases',
+ description: 'Completed purchases per day.',
+ status: 'proposed',
+ is_drifted: true,
+ definition: { kind: 'HogQLQuery', query: 'SELECT 7 AS purchases' },
+ },
+ {
+ id: 'signups',
+ name: 'signups',
+ description: 'New signups per week.',
+ status: 'proposed',
+ is_drifted: false,
+ definition: { kind: 'TrendsQuery' },
+ },
+ ].filter((metric) => metric.name.includes(new URL(request.url).searchParams.get('search') ?? '')),
+ }),
+ },
+ }),
+ ],
+ play: async ({ canvasElement }) => {
+ await userEvent.click(await within(canvasElement).findByRole('button', { name: 'Use a catalog metric' }))
+ await waitFor(() => expect(biCatalogPickerLogic.values.metricsLoading).toBe(false))
+ },
+}
+export default meta
+type Story = StoryObj<typeof meta>
+export const Metrics: Story = {}
+export const Empty: Story = {
+ decorators: [
+ mswDecorator({
+ get: { '/api/projects/:team_id/data_catalog/metrics/': { count: 0, results: [], next: null } },
+ }),
+ ],
+}
+export const Error: Story = {
+ decorators: [
+ mswDecorator({ get: { '/api/projects/:team_id/data_catalog/metrics/': [500, { detail: 'Unavailable' }] } }),
+ ],
+}
diff --git a/products/business_intelligence/frontend/BICatalogMetricPicker.tsx b/products/business_intelligence/frontend/BICatalogMetricPicker.tsx
new file mode 100644
index 000000000000..1ceefe66a50e
--- /dev/null
+++ b/products/business_intelligence/frontend/BICatalogMetricPicker.tsx
@@ -0,0 +1,113 @@
+import { useActions, useValues } from 'kea'
+import { combineUrl } from 'kea-router'
+
+import { LemonBanner, LemonButton, LemonInput, LemonModal, LemonTag, Spinner } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { catalogMetricWorksheet } from './biCatalog'
+import { biCatalogPickerLogic } from './biCatalogPickerLogic'
+
+export function BICatalogMetricPicker(): JSX.Element {
+ const { isOpen, search, page, metrics, metricsLoading, error } = useValues(biCatalogPickerLogic)
+ const { open, close, setSearch, setPage, loadMetrics } = useActions(biCatalogPickerLogic)
+ return (
+ <>
+ <LemonButton type="secondary" size="small" onClick={open}>
+ Use a catalog metric
+ </LemonButton>
+ <LemonModal isOpen={isOpen} onClose={close} title="Use a catalog metric" width={640}>
+ <div className="flex flex-col gap-3">
+ <p className="m-0 text-secondary">
+ Open a SQL copy in a new worksheet. Catalog changes won't update the copy.
+ </p>
+ <LemonInput
+ type="search"
+ aria-label="Search catalog metrics"
+ placeholder="Search catalog metrics"
+ value={search}
+ onChange={setSearch}
+ />
+ {error ? (
+ <LemonBanner type="error">
+ Couldn't load catalog metrics.{' '}
+ <LemonButton size="xsmall" loading={metricsLoading} onClick={() => loadMetrics()}>
+ Retry
+ </LemonButton>
+ </LemonBanner>
+ ) : metricsLoading ? (
+ <Spinner />
+ ) : metrics?.results.length ? (
+ <div className="flex max-h-96 flex-col gap-3 overflow-y-auto">
+ {metrics.results.map((metric) => (
+ <div key={metric.id} className="flex min-w-0 flex-col gap-1 rounded border p-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="min-w-0 break-all font-semibold">
+ {metric.display_name || metric.name}
+ </span>
+ <LemonTag
+ type={
+ metric.status === 'approved' && !metric.is_drifted
+ ? 'success'
+ : 'warning'
+ }
+ >
+ {metric.is_drifted
+ ? 'Drifted'
+ : metric.status === 'approved'
+ ? 'Approved'
+ : 'Proposed'}
+ </LemonTag>
+ </div>
+ <p className="m-0 break-words text-secondary">{metric.description}</p>
+ <div className="flex flex-wrap gap-2">
+ <LemonButton
+ size="xsmall"
+ type="primary"
+ disabledReason={
+ catalogMetricWorksheet(metric)
+ ? undefined
+ : 'BI supports SQL metric definitions. View this metric in the catalog.'
+ }
+ to={combineUrl(urls.businessIntelligenceNew(), { metric: metric.name }).url}
+ onClick={close}
+ >
+ Open copy in BI
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ to={urls.dataCatalogMetric(metric.name)}
+ onClick={close}
+ >
+ View in catalog
+ </LemonButton>
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="m-0 text-secondary">No catalog metrics found.</p>
+ )}
+ <div className="flex gap-2">
+ <LemonButton
+ size="small"
+ disabledReason={page === 0 || metricsLoading ? 'No previous page available' : undefined}
+ onClick={() => setPage(page - 1)}
+ >
+ Previous
+ </LemonButton>
+ <LemonButton
+ size="small"
+ disabledReason={
+ !metrics?.next || metricsLoading || error ? 'No next page available' : undefined
+ }
+ onClick={() => setPage(page + 1)}
+ >
+ Next
+ </LemonButton>
+ </div>
+ </div>
+ </LemonModal>
+ </>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIStarters.tsx b/products/business_intelligence/frontend/BIStarters.tsx
index 88020599d48b..ed565efec0c7 100644
--- a/products/business_intelligence/frontend/BIStarters.tsx
+++ b/products/business_intelligence/frontend/BIStarters.tsx
@@ -2,6 +2,7 @@ import { useValues } from 'kea'
import { LemonButton, LemonTag } from '@posthog/lemon-ui'
+import { BICatalogMetricPicker } from './BICatalogMetricPicker'
import { captureBIWorksheetAction } from './biEditorAnalytics'
import { DEFAULT_BI_CONFIG } from './biEditorTypes'
import { BI_QUESTION_STARTERS, starterWorksheetUrl } from './biQuestionStarters'
@@ -13,6 +14,7 @@ export function BIStarters(): JSX.Element {
<section className="flex flex-col gap-2" aria-label="Worksheet starting points">
<h3 className="m-0">Start with a question</h3>
<div className="flex flex-wrap gap-2">
+ <BICatalogMetricPicker />
{sources.map((source) => {
const config = { ...DEFAULT_BI_CONFIG, source: { table: source.target_name } }
return (
diff --git a/products/business_intelligence/frontend/biCatalogPickerLogic.test.ts b/products/business_intelligence/frontend/biCatalogPickerLogic.test.ts
new file mode 100644
index 000000000000..29d1ffba9971
--- /dev/null
+++ b/products/business_intelligence/frontend/biCatalogPickerLogic.test.ts
@@ -0,0 +1,80 @@
+import { waitFor } from '@testing-library/dom'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import * as api from 'products/data_catalog/frontend/generated/api'
+
+import { biCatalogPickerLogic } from './biCatalogPickerLogic'
+
+beforeEach(() => initKeaTests())
+afterEach(() => jest.restoreAllMocks())
+
+it('does not let a superseded request failure hide the new search results', async () => {
+ let rejectOld!: (error: Error) => void
+ const result = { results: [], count: 0, next: null }
+ const list = jest
+ .spyOn(api, 'dataCatalogMetricsList')
+ .mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ rejectOld = reject
+ })
+ )
+ .mockResolvedValueOnce(result)
+ const logic = biCatalogPickerLogic()
+ logic.mount()
+ try {
+ logic.actions.open()
+ await waitFor(() => expect(list).toHaveBeenCalledTimes(1))
+ logic.actions.setSearch('new search')
+ await waitFor(() => expect(logic.values.metrics).toEqual(result))
+ await expectLogic(logic, () => rejectOld(new Error('Old request failed'))).toFinishAllListeners()
+ expect(logic.values.error).toBe(false)
+ expect(logic.values.metrics).toEqual(result)
+ } finally {
+ logic.unmount()
+ }
+})
+
+it('searches across pages and resets to the first page for a new search', async () => {
+ const requests: URLSearchParams[] = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/': ({ request }) => {
+ requests.push(new URL(request.url).searchParams)
+ return { results: [{ id: 'example', name: 'revenue' }], next: 'next', count: 21 }
+ },
+ },
+ })
+ const logic = biCatalogPickerLogic()
+ logic.mount()
+ await expectLogic(logic, () => logic.actions.open()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.setPage(1)).toFinishAllListeners()
+ expect(requests.at(-1)?.get('offset')).toBe('20')
+ await expectLogic(logic, () => logic.actions.setSearch(' revenue ')).toFinishAllListeners()
+ expect(requests.at(-1)?.get('offset')).toBe('0')
+ expect(requests.at(-1)?.get('search')).toBe('revenue')
+ expect(logic.values.metrics?.results[0].name).toBe('revenue')
+ logic.unmount()
+})
+
+it('keeps failures distinct from an empty result and allows retry', async () => {
+ let failed = true
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/': () =>
+ failed ? [500, { detail: 'Unavailable' }] : { results: [], count: 0, next: null },
+ },
+ })
+ const logic = biCatalogPickerLogic()
+ logic.mount()
+ await expectLogic(logic, () => logic.actions.open()).toFinishAllListeners()
+ expect(logic.values.error).toBe(true)
+ failed = false
+ await expectLogic(logic, () => logic.actions.loadMetrics()).toFinishAllListeners()
+ expect(logic.values.error).toBe(false)
+ expect(logic.values.metrics?.results).toEqual([])
+ logic.unmount()
+})
diff --git a/products/business_intelligence/frontend/biCatalogPickerLogic.ts b/products/business_intelligence/frontend/biCatalogPickerLogic.ts
new file mode 100644
index 000000000000..c65e2ed14fc1
--- /dev/null
+++ b/products/business_intelligence/frontend/biCatalogPickerLogic.ts
@@ -0,0 +1,94 @@
+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import * as api from 'products/data_catalog/frontend/generated/api'
+
+import type { PaginatedDataCatalogMetricListApi } from '../../data_catalog/frontend/generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biCatalogPickerLogicValues {
+ error: boolean
+ isOpen: boolean
+ metrics: Awaited<ReturnType<typeof api.dataCatalogMetricsList>> | null
+ metricsLoading: boolean
+ page: number
+ search: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biCatalogPickerLogicActions {
+ close: () => {
+ value: true
+ }
+ loadMetrics: (_: void) => void
+ loadMetricsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMetricsSuccess: (
+ metrics: PaginatedDataCatalogMetricListApi,
+ payload?: void
+ ) => {
+ metrics: PaginatedDataCatalogMetricListApi
+ payload?: void
+ }
+ open: () => {
+ value: true
+ }
+ setPage: (page: number) => {
+ page: number
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+}
+
+export type biCatalogPickerLogicType = MakeLogicType<biCatalogPickerLogicValues, biCatalogPickerLogicActions>
+
+export const biCatalogPickerLogic = kea<biCatalogPickerLogicType>([
+ path(['products', 'business_intelligence', 'biCatalogPickerLogic']),
+ actions({
+ open: true,
+ close: true,
+ setSearch: (search: string) => ({ search }),
+ setPage: (page: number) => ({ page }),
+ }),
+ reducers({
+ isOpen: [false, { open: () => true, close: () => false }],
+ search: ['', { setSearch: (_, { search }) => search, open: () => '' }],
+ page: [0, { setPage: (_, { page }) => page, setSearch: () => 0, open: () => 0 }],
+ error: [false, { loadMetrics: () => false, loadMetricsFailure: () => true }],
+ }),
+ loaders(({ values }) => ({
+ metrics: [
+ null as Awaited<ReturnType<typeof api.dataCatalogMetricsList>> | null,
+ {
+ loadMetrics: async (_: void, breakpoint) => {
+ await breakpoint(250)
+ const response = await api
+ .dataCatalogMetricsList(String(teamLogic.values.currentTeamId), {
+ search: values.search.trim() || undefined,
+ limit: 20,
+ offset: values.page * 20,
+ })
+ .catch((error) => {
+ breakpoint()
+ throw error
+ })
+ breakpoint()
+ return response
+ },
+ },
+ ],
+ })),
+ listeners(({ actions }) => ({
+ open: () => actions.loadMetrics(),
+ setSearch: () => actions.loadMetrics(),
+ setPage: () => actions.loadMetrics(),
+ })),
+])