:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(bi): confirm catalog metric overwrites (#124959)
Marius Andra58dcdb2928b0
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex 10a1b600ec36..2f4b3c54375a 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -414,7 +414,7 @@ BI chart settings preserve custom scatter axes and implicit count formatting. NuCatalog SQL metrics can open as BI query snapshots. Opening a metric shows a loading state until its definition is ready, or an error if it cannot load. Press **Run** to query the snapshot. Their dates, grouping, and bound values come from the metric definition; shelf edits, worksheet date filters, pivots, and result drilling are unavailable. For snapshots with bound string, number, or boolean values, **Edit parameters** changes those values for the worksheet without changing the SQL or catalog definition. Number parameters require a finite number. Other parameter types remain unchanged. Apply follows the worksheet auto-update setting; with auto-update off, press **Run**. Changing the chart changes the presentation of those results. Saved snapshots do not follow later catalog edits.-After running a worksheet, **Propose as catalog metric** sends its resolved SQL and date window through catalog review. A pending or failed query cannot be proposed. The catalog requires explicit confirmation to overwrite an existing metric; the BI dialog currently reports the name conflict without offering that confirmation. Direct-connection worksheets cannot be proposed as catalog metrics.+After running a worksheet, **Propose as catalog metric** sends its resolved SQL and date window through catalog review. A pending or failed query cannot be proposed. When the name exists, confirm **Overwrite** to replace its definition for review. Cancel keeps the entered values so you can choose a different name. An overwritten metric remains proposed. Direct-connection worksheets cannot be proposed as catalog metrics.The worksheet library offers editable question starters for daily events, daily distinct people, events ranked by distinct people, and page views by referring domain. Each uses the last seven days of event data and opens as an unsaved worksheet; press **Run** to query it. The page-view starter requires captured `$pageview` events with `$referring_domain` for a useful breakdown. The worksheet library also suggests up to three certified sources. Metric suggestions were removed in [#120111](https://github.com/PostHog/posthog/pull/120111); SQL metrics remain accessible through **Explore in BI** in the catalog. Source context keeps certification visible and groups descriptions and relationship review status under **Catalog details**, collapsed by default to leave room for fields. Neutral catalog buttons show an external-link icon to indicate that they leave the worksheet. Relationship proposals open the catalog with the source prefilled; they become usable joins only after approval. Optional catalog suggestions do not prevent opening the worksheet library when the catalog is unavailable. Browser Back returns from a starter to the worksheet library; confirming discarded edits does not replace that history entry with an empty worksheet.@@ -434,7 +434,7 @@ Implementation audit, October 28, 2026. These are proposed integration contracts### BI-owned integration work-- [ ] Adopt the catalog overwrite-confirmation flow for worksheet metric proposals. Preserve entered values on cancel, allow retry, and keep overwritten metrics proposed.+- [x] Adopt the catalog overwrite-confirmation flow for worksheet metric proposals. Preserve entered values on cancel, allow retry, and keep overwritten metrics proposed.- [ ] Show catalog trust context when exploring a metric: approval and drift status, unit, owner, and stable identity. Distinguish the copied definition from current catalog state; never imply a snapshot follows catalog changes.- [ ] Add deliberate, searchable metric discovery in BI using the existing catalog search API. Handle 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.diff --git a/products/business_intelligence/frontend/biMetricProposalLogic.test.ts b/products/business_intelligence/frontend/biMetricProposalLogic.test.tsindex 293c78d94205..1a4b020d9c01 100644--- a/products/business_intelligence/frontend/biMetricProposalLogic.test.ts+++ b/products/business_intelligence/frontend/biMetricProposalLogic.test.ts@@ -5,11 +5,136 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import * as overwriteDialog from 'products/data_catalog/frontend/openOverwriteMetricDialog'+import { DEFAULT_BI_CONFIG } from './biEditorTypes'import { biMetricProposalLogic } from './biMetricProposalLogic'afterEach(() => jest.restoreAllMocks())+it.each(['overwrite', 'cancel', 'navigate'] as const)(+ 'handles a metric name conflict with %s without losing the form or overwriting implicitly',+ async (choice) => {+ initKeaTests()+ const requests: Record<string, unknown>[] = []+ useMocks({+ post: {+ '/api/projects/:team_id/data_catalog/metrics/': async ({ request }) => {+ const body = (await request.json()) as Record<string, unknown>+ requests.push(body)+ return body.overwrite+ ? [201, { ...body, id: 'existing-metric', status: 'proposed' }]+ : [+ 409,+ {+ code: 'metric_name_taken',+ detail: 'Name already exists',+ extra: { existing_metric: { name: 'purchases', status: 'approved' } },+ },+ ]+ },+ },+ })+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '')+ const open = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => undefined)+ const confirm = jest.spyOn(overwriteDialog, 'openOverwriteMetricDialog').mockImplementation((dialog) => {+ if (choice === 'overwrite') {+ dialog.onOverwrite()+ } else if (choice === 'cancel') {+ dialog.onCancel?.()+ } else {+ open.mock.calls[0][0].onAfterClose?.()+ }+ })+ const logic = biMetricProposalLogic({+ tabId: 'proposal-conflict',+ name: 'Purchases',+ config: DEFAULT_BI_CONFIG,+ snapshot: 'SELECT 7',+ })+ const unmount = logic.mount()+ try {+ logic.actions.proposeMetric()+ const form = open.mock.calls[0][0]+ const fields = {+ ...form.initialValues,+ name: 'purchases',+ description: 'Completed purchases.',+ unit: 'orders',+ }+ if (choice === 'overwrite') {+ await form.onSubmit(fields)+ expect(requests).toHaveLength(2)+ expect(requests[1]).toEqual({ ...requests[0], overwrite: true })+ expect(requests[1]).toMatchObject({+ created_source: 'user',+ unit: 'orders',+ definition: { kind: 'HogQLQuery', query: 'SELECT 7' },+ })+ } else {+ await expect(form.onSubmit(fields)).rejects.toBeDefined()+ expect(requests).toHaveLength(1)+ confirm.mockImplementation((dialog) => dialog.onOverwrite())+ await form.onSubmit(fields)+ expect(requests).toHaveLength(choice === 'navigate' ? 1 : 3)+ }+ expect(confirm).toHaveBeenCalledWith(+ expect.objectContaining({ existing: { name: 'purchases', status: 'approved' } })+ )+ expect(toast).not.toHaveBeenCalled()+ } finally {+ unmount()+ }+ }+)++it('does not open an overwrite prompt when a conflict arrives after the form closes', async () => {+ initKeaTests()+ let releaseRequest!: () => void+ const pending = new Promise<void>((resolve) => {+ releaseRequest = resolve+ })+ const create = jest.fn(async () => {+ await pending+ return [+ 409,+ {+ code: 'metric_name_taken',+ detail: 'Name already exists',+ extra: { existing_metric: { name: 'purchases', status: 'approved' } },+ },+ ]+ })+ useMocks({ post: { '/api/projects/:team_id/data_catalog/metrics/': create } })+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '')+ const open = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => undefined)+ const confirm = jest.spyOn(overwriteDialog, 'openOverwriteMetricDialog')+ const logic = biMetricProposalLogic({+ tabId: 'closed-proposal',+ name: 'Purchases',+ config: DEFAULT_BI_CONFIG,+ snapshot: 'SELECT 7',+ })+ const unmount = logic.mount()+ try {+ logic.actions.proposeMetric()+ const form = open.mock.calls[0][0]+ const submission = form.onSubmit({+ ...form.initialValues,+ name: 'purchases',+ description: 'Completed purchases.',+ })+ form.onAfterClose?.()+ releaseRequest()+ await expect(submission).rejects.toBeDefined()+ expect(create).toHaveBeenCalledTimes(1)+ expect(confirm).not.toHaveBeenCalled()+ expect(toast).not.toHaveBeenCalled()+ } finally {+ unmount()+ }+})+it('shows a failed proposal and allows retrying the same form', async () => {initKeaTests()let attempts = 0diff --git a/products/business_intelligence/frontend/biMetricProposalLogic.tsx b/products/business_intelligence/frontend/biMetricProposalLogic.tsxindex a5fdd368f6df..d25ad9f15d0d 100644--- a/products/business_intelligence/frontend/biMetricProposalLogic.tsx+++ b/products/business_intelligence/frontend/biMetricProposalLogic.tsx@@ -5,15 +5,20 @@ import { LemonDialog, LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'import { ApiError } from 'lib/api'import { LemonField } from 'lib/lemon-ui/LemonField'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { BIConfig } from '~/queries/schema/schema-business-intelligence'import { NodeKind } from '~/queries/schema/schema-general'-import { METRIC_FIELD_COPY, validateMetricDescription, validateMetricName } from 'products/data_catalog/frontend/common'-import { dataCatalogMetricsCreate } from 'products/data_catalog/frontend/generated/api'+import {+ existingMetricFromNameConflict,+ METRIC_FIELD_COPY,+ validateMetricDescription,+ validateMetricName,+} from 'products/data_catalog/frontend/common'+import { createMetricAsUser } from 'products/data_catalog/frontend/createMetricAsUser'import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'+import { openOverwriteMetricDialog } from 'products/data_catalog/frontend/openOverwriteMetricDialog'import { captureBIEditorQuerySaved, captureBIWorksheetAction } from './biEditorAnalytics'import { BIEditorView } from './biEditorTypes'@@ -57,10 +62,16 @@ export const biMetricProposalLogic = kea<biMetricProposalLogicType>([const snapshot = props.snapshotconst config = props.configlet submission: Promise<void> | null = null+ let formClosed = false+ let cancelConfirmation: (() => void) | undefinedLemonDialog.openForm({title: 'Propose as catalog metric',description:- 'Saves this query with the date window and filters from its last run. Shelves and worksheet history are not part of the metric. An existing metric name updates that definition. Changes go through catalog review.',+ 'Saves this query with the date window and filters from its last run. Shelves and worksheet history are not part of the metric. If the name already exists, you can confirm an overwrite. Changes go through catalog review.',+ onAfterClose: () => {+ formClosed = true+ cancelConfirmation?.()+ },shouldAwaitSubmit: true,primaryButtonProps: { children: 'Propose metric' },initialValues: { name: '', display_name: props.name, description: '', unit: '' },@@ -90,17 +101,46 @@ export const biMetricProposalLogic = kea<biMetricProposalLogicType>([!value?.trim() ? 'Add a description' : validateMetricDescription(value.trim()),},onSubmit: async (fields) => {+ if (formClosed) {+ return+ }if (submission) {return submission}+ let canceled = falsesubmission = (async () => {- const metric = await dataCatalogMetricsCreate(String(teamLogic.values.currentTeamId), {+ const request = {name: fields.name.trim(),display_name: (fields.display_name ?? '').trim(),description: fields.description.trim(),unit: (fields.unit ?? '').trim(),definition: { kind: NodeKind.HogQLQuery, query: snapshot },+ }+ const created = await createMetricAsUser(request, false).catch(async (error) => {+ if (formClosed) {+ canceled = true+ throw error+ }+ const existing = existingMetricFromNameConflict(error)+ if (!existing) {+ throw error+ }+ const confirmed = await new Promise<boolean>((resolve) => {+ cancelConfirmation = () => resolve(false)+ openOverwriteMetricDialog({+ existing,+ onOverwrite: () => resolve(true),+ onCancel: cancelConfirmation,+ })+ })+ cancelConfirmation = undefined+ if (!confirmed || formClosed) {+ canceled = true+ throw error+ }+ return createMetricAsUser({ ...request, overwrite: true }, false)})+ const metric = created.metricmetricsLogic.findMounted()?.actions.loadMetrics()captureBIEditorQuerySaved({ editorView: BIEditorView.BI, config }, 'metric', 'create')captureBIWorksheetAction('catalog_metric_proposed', config)@@ -111,11 +151,13 @@ export const biMetricProposalLogic = kea<biMetricProposalLogicType>([)})().catch((error) => {- lemonToast.error(- error instanceof ApiError && error.detail- ? error.detail- : 'Could not propose the metric. Try again.'- )+ if (!canceled) {+ lemonToast.error(+ error instanceof ApiError && error.detail+ ? error.detail+ : 'Could not propose the metric. Try again.'+ )+ }throw error}).finally(() => {