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(data-catalog): add metric SQL checks tab (#96583)

Thiago Salvatored22d76c37e0e
diff --git a/docs/internal/data-quality-checks.md b/docs/internal/data-quality-checks.md
index b2d7a7a887ff..d9926d1e6d05 100644
--- a/docs/internal/data-quality-checks.md
+++ b/docs/internal/data-quality-checks.md
@@ -57,3 +57,5 @@ Temporal owns the interval, pause state, and next execution time. The schedule e
Scheduled executions skip an occurrence when the previous scheduled workflow is still running. Temporal catches up missed occurrences within 15 minutes and does not pause a schedule after a failed run. Manual runs keep their existing behavior. A scheduled activity rechecks schedule existence and pause state before selecting current enabled checks. An executing check can finish after the schedule is paused. Feature flags, subject existence, and execution permissions are checked in activities.
A reconciler runs every 15 minutes, processing bounded pages of checks and product-filtered Temporal schedules. It repairs missing schedules without changing existing intervals or pause states, and deletes schedules whose metrics no longer exist. Deleting or disabling all checks retains the metric's schedule preferences and executes no check queries. Deleted metrics stop producing check queries immediately, even if schedule cleanup needs a retry.
+
+In the metric Tests tab, a failed schedule edit refreshes the persisted state and offers Reload before another edit. Schedule controls stay disabled while a request is pending or its outcome is uncertain.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 147aff962192..b730cab3207e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2284,6 +2284,26 @@ snapshots:
hash: v1.k794b7964.88c3253cfe129808e538e59d6eb8eb8fa948540042edd8248e9836cccce1a4af.RnBgBRDh8HKCK7PYoGDeuXTEbHHl5vnlNpU9IGLwFyk
customer-analytics-google-account-backfill--invalid-range--light:
hash: v1.k794b7964.7eb703bdf24bb2b8adcb1f8d90097dec56b85e0e0b6778e0ea0c68a9c6d9fbb0.W0aCVMrWUlFruWBqwJYpotdaFJ3BfR9P16qCdJn5jBc
+ data-catalog-metric-tests--empty--dark:
+ hash: v1.k794b7964.8c5bed6e45ecc0ce83e4fcb37057c6d87aad0a974e8ed035b9fc9e67a8c1dbd9.jNr2vi0P9-nEfiRddJJjwFg4ZekchSpeyXxdxNfAF1E
+ data-catalog-metric-tests--empty--light:
+ hash: v1.k794b7964.b61938eeec6c181dfa050f12aaa37dc28886fb46c05f44a166bd561a11e2bbeb.7FGTvZJQ_iQjTcZhVgp1_aPfdNLp44ci8ekVdwJhOnQ
+ data-catalog-metric-tests--narrow--dark:
+ hash: v1.k794b7964.d50892989be22e09d9f3c359e9cb103ac6e114962f0e5880227e7609e1bcfa6c.fo2ci86vxhqiY9M38jTh2o5FDYfZRVUR1c4DBzAMLDY
+ data-catalog-metric-tests--narrow--light:
+ hash: v1.k794b7964.5c3ea3639e9b94b99e126c1abcb7b1e3a3e4a4e6a47be4e96a5b41439a78a168.2Im9zIVH4nxRFBuQ85boAvduBL9OO0-B1RsOeb-T9Ew
+ data-catalog-metric-tests--scheduled--dark:
+ hash: v1.k794b7964.9bef386d6e9f5d180e1b2d4b5d0e6102fe89c762a7c072f01bc15fde7bf48822.KWnM7bOkYeokuww7iiq7dzouT0ap4H31-nVXPzHyyvU
+ data-catalog-metric-tests--scheduled--light:
+ hash: v1.k794b7964.79c70c6686bde7329b41b0bd75ee7cc686f4ca29a228267e099883bba29d4c34.WmwUmOEhHrBrfYBE7RAgFDVncjFTUP9FbqMXBIndH24
+ data-catalog-metric-tests--unsupported--dark:
+ hash: v1.k794b7964.7115929e94c0ba820dac20a4dab696f15e2cb0e612412b58ad690d67d31ba492.SMCtOwtSj6eBt2XXEVskBE-TRKLhc9HHwI9omv89eHs
+ data-catalog-metric-tests--unsupported--light:
+ hash: v1.k794b7964.ad9a5d7d21f92578fdfb8e2a50f1e11f57398eaf5b1b96241fc5d4ac09b22882.v1PBeMuXRe8sB14acADHS32KwpKXYIL0jW1DYk9a5Tw
+ data-catalog-metric-tests--unsupported-with-checks--dark:
+ hash: v1.k794b7964.3f134e3ce25e5070006cb36e69e4d2fba535b95516be1287f6571275970002fa.XEAgwRGf86ilBY4t6jX0KgGm6b9BHon8bcQwFzMSUBU
+ data-catalog-metric-tests--unsupported-with-checks--light:
+ hash: v1.k794b7964.64e9162a5dd7bc47a1667f13d8c77b4d1f00c6e15c70169ab4d4ffc588dd2112.j2HS8sjcKIg0QXaZ9PLel28BVD4vayBEBRzrHVO-dlI
data-warehouse-destinationlist--both-selected--dark:
hash: v1.k794b7964.5da0169833ea8b87e6d903cb4fc0f4d629a1b1db09149c5fb7c450ef312641a0.MH4OyaTjM18a4cpxtpCHPVm1QWWajZL5cz4NlzbJag0
data-warehouse-destinationlist--both-selected--light:
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 5a89a8804229..72dab55eb508 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1190,7 +1190,8 @@ export const productUrls = {
`/dashboard/${id}/subscriptions/${subscriptionId}`,
sharedDashboard: (shareToken: string): string => `/shared_dashboard/${shareToken}`,
dataCatalog: (tab?: string): string => `/data-catalog${tab ? `?tab=${tab}` : ''}`,
- dataCatalogMetric: (name: string): string => `/data-catalog/metrics/${name}`,
+ dataCatalogMetric: (name: string, tab?: 'definition' | 'tests'): string =>
+ `/data-catalog/metrics/${name}${tab === 'tests' ? '?tab=tests' : ''}`,
dataOps: (tab?: string): string => {
const params = new URLSearchParams()
if (tab) {
diff --git a/products/data_catalog/frontend/DataCatalogMetricScene.tsx b/products/data_catalog/frontend/DataCatalogMetricScene.tsx
index 537e2048975e..ea9c9d55ce7d 100644
--- a/products/data_catalog/frontend/DataCatalogMetricScene.tsx
+++ b/products/data_catalog/frontend/DataCatalogMetricScene.tsx
@@ -20,6 +20,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
@@ -50,8 +51,11 @@ import {
dataCatalogMetricSceneLogic,
DataCatalogMetricSceneLogicProps,
definitionField,
+ MetricSceneTab,
} from './dataCatalogMetricSceneLogic'
import type { DataCatalogMetricApi } from './generated/api.schemas'
+import { MetricTestsTab } from './tabs/MetricTestsTab'
+import { MetricTestsTabLabel } from './tabs/MetricTestsTabLabel'
export const scene: SceneExport<DataCatalogMetricSceneLogicProps> = {
component: DataCatalogMetricScene,
@@ -71,9 +75,23 @@ interface MetricAction {
const DRIFT_APPROVE_DISABLED = 'This metric has drifted from its source insight. Refresh it first.'
+function tabPanelClassName(tab: MetricSceneTab, activeTab: MetricSceneTab): string {
+ return tab === activeTab ? 'flex flex-col gap-y-4' : 'hidden'
+}
+
export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicProps): JSX.Element {
- const { metric, metricLoading, mutating, runResult, runResultLoading, editingDefinition, draftMarkdown } =
- useValues(dataCatalogMetricSceneLogic)
+ const {
+ metric,
+ metricLoading,
+ mutating,
+ runResult,
+ runResultLoading,
+ editingDefinition,
+ draftMarkdown,
+ activeTab,
+ mountedTabs,
+ metricChecksEnabled,
+ } = useValues(dataCatalogMetricSceneLogic)
const {
approveMetric,
refreshMetricFromInsight,
@@ -84,6 +102,7 @@ export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicProp
setEditingDefinition,
setDraftMarkdown,
startEditingMarkdown,
+ setActiveTab,
} = useActions(dataCatalogMetricSceneLogic)
const { featureFlags } = useValues(featureFlagLogic)
const sceneMenuBarEnabled = !!featureFlags[FEATURE_FLAGS.SCENE_MENU_BAR]
@@ -339,27 +358,49 @@ export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicProp
</LemonBanner>
)}
- <MetricMetadata metric={metric} onSaveUnit={(unit) => confirmAndUpdate({ unit })} />
-
- <MetricDefinition
- metric={metric}
- editingDefinition={editingDefinition}
- draftMarkdown={draftMarkdown}
- saving={mutating}
- runResult={runResult}
- runResultLoading={runResultLoading}
- onDraftMarkdown={setDraftMarkdown}
- onEdit={setEditingDefinition}
- onStartEditingMarkdown={startEditingMarkdown}
- onSaveMarkdown={(markdown) =>
- confirmAndUpdate({ definition: { kind: 'MarkdownDefinition', markdown } })
- }
- onRun={loadRunResult}
- onRunWithAI={runMarkdownMetricWithAI}
- runWithAIDisabledReason={
- isMaxAvailable ? undefined : 'PostHog AI is not available on this instance'
- }
+ <LemonTabs
+ activeKey={activeTab}
+ onChange={setActiveTab}
+ tabs={[
+ { key: 'definition', label: 'Definition' },
+ metricChecksEnabled && {
+ key: 'tests',
+ label: <MetricTestsTabLabel metricId={metric.id} />,
+ },
+ ]}
/>
+
+ {mountedTabs.includes('definition') && (
+ <div className={tabPanelClassName('definition', activeTab)}>
+ <MetricMetadata metric={metric} onSaveUnit={(unit) => confirmAndUpdate({ unit })} />
+
+ <MetricDefinition
+ metric={metric}
+ editingDefinition={editingDefinition}
+ draftMarkdown={draftMarkdown}
+ saving={mutating}
+ runResult={runResult}
+ runResultLoading={runResultLoading}
+ onDraftMarkdown={setDraftMarkdown}
+ onEdit={setEditingDefinition}
+ onStartEditingMarkdown={startEditingMarkdown}
+ onSaveMarkdown={(markdown) =>
+ confirmAndUpdate({ definition: { kind: 'MarkdownDefinition', markdown } })
+ }
+ onRun={loadRunResult}
+ onRunWithAI={runMarkdownMetricWithAI}
+ runWithAIDisabledReason={
+ isMaxAvailable ? undefined : 'PostHog AI is not available on this instance'
+ }
+ />
+ </div>
+ )}
+
+ {metricChecksEnabled && mountedTabs.includes('tests') && (
+ <div className={tabPanelClassName('tests', activeTab)}>
+ <MetricTestsTab />
+ </div>
+ )}
</SceneContent>
<ScenePanel>
diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts
index 42364e77df8c..0b39e33eced8 100644
--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts
+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts
@@ -1,7 +1,9 @@
import { router } from 'kea-router'
import { ApiConfig, ApiError } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
@@ -71,6 +73,9 @@ describe('dataCatalogMetricSceneLogic', () => {
initKeaTests()
logic = dataCatalogMetricSceneLogic({ name: 'weekly_active_users' })
logic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.DATA_QUALITY_CHECKS], {
+ [FEATURE_FLAGS.DATA_QUALITY_CHECKS]: true,
+ })
await expectLogic(logic).toDispatchActions(['loadMetricSuccess'])
})
@@ -78,6 +83,42 @@ describe('dataCatalogMetricSceneLogic', () => {
;(ApiConfig.getCurrentTeamId as jest.Mock).mockReturnValue(1)
})
+ it('synchronizes the Tests tab with navigation and preserves it on rename', async () => {
+ router.actions.push(urls.dataCatalogMetric('weekly_active_users'), { tab: 'tests' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.activeTab).toBe('tests')
+ expect(logic.values.mountedTabs).toEqual(['tests'])
+ logic.actions.setActiveTab('definition')
+ expect(router.values.searchParams.tab).toBeUndefined()
+ expect(logic.values.mountedTabs).toEqual(['tests', 'definition'])
+ logic.actions.setActiveTab('tests')
+ expect(router.values.searchParams.tab).toBe('tests')
+ ;(dataCatalogMetricsPartialUpdate as jest.Mock).mockResolvedValue(buildMetric({ name: 'wau' }))
+ logic.actions.renameMetric('wau')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(router.values.searchParams.tab).toBe('tests')
+ })
+
+ // The metric check endpoints are gated on the same flag, so a link to the tab from a project
+ // outside the rollout has to land on Definition. Otherwise the panel mounts against endpoints
+ // that reject every request.
+ it('refuses the Tests tab while the data quality flag is off', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ router.actions.push(urls.dataCatalogMetric('weekly_active_users'), { tab: 'tests' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.metricChecksEnabled).toBe(false)
+ expect(logic.values.activeTab).toBe('definition')
+ expect(router.values.searchParams.tab).toBeUndefined()
+ })
+
+ it.each(['HogQLQuery', 'TrendsQuery', 'FunnelsQuery', 'EventsNode', 'MarkdownDefinition', null])(
+ 'allows check authoring only for a HogQL definition (%s)',
+ (definition_kind) => {
+ logic.actions.setMetric(buildMetric({ definition_kind }))
+ expect(logic.values.supportsMetricChecks).toBe(definition_kind === 'HogQLQuery')
+ }
+ )
+
it('saving an approved metric edit reflects the proposed status from the response', async () => {
;(dataCatalogMetricsPartialUpdate as jest.Mock).mockResolvedValue(
buildMetric({ status: 'proposed', definition: { kind: 'HogQLQuery', query: 'SELECT 2' } })
diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx
index ea5f4bbba25f..3e5c8555c922 100644
--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx
+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx
@@ -13,10 +13,12 @@ import {
selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
-import { router, urlToAction } from 'kea-router'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import { ApiConfig, ApiError } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
import { Breadcrumb } from '~/types'
@@ -41,6 +43,8 @@ export interface DataCatalogMetricSceneLogicProps {
name: string
}
+export type MetricSceneTab = 'definition' | 'tests'
+
function projectId(): string {
return String(ApiConfig.getCurrentTeamId())
}
@@ -81,16 +85,22 @@ function rendersMarkdownEditor(metric: DataCatalogMetricApi | null): boolean {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataCatalogMetricSceneLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ activeTab: MetricSceneTab
breadcrumbs: Breadcrumb[]
draftMarkdown: string
draftSql: string
editingDefinition: boolean
metric: DataCatalogMetricApi | null
+ metricChecksEnabled: boolean
metricLoading: boolean
+ mountedTabs: MetricSceneTab[]
mutating: boolean
pendingDefinitionEdit: boolean
runResult: DataCatalogMetricRunApi | null
runResultLoading: boolean
+ supportsMetricChecks: boolean
+ visitedTabs: MetricSceneTab[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -146,6 +156,9 @@ export interface dataCatalogMetricSceneLogicActions {
renamedExternally: (name: string) => {
name: string
}
+ setActiveTab: (activeTab: MetricSceneTab) => {
+ activeTab: MetricSceneTab
+ }
setDraftMarkdown: (draftMarkdown: string) => {
draftMarkdown: string
}
@@ -194,6 +207,9 @@ export interface dataCatalogMetricSceneLogicActions {
export interface dataCatalogMetricSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ mountedTabs: (activeTab: MetricSceneTab, visitedTabs: MetricSceneTab[]) => MetricSceneTab[]
+ metricChecksEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ supportsMetricChecks: (metric: DataCatalogMetricApi | null) => boolean
breadcrumbs: (metric: DataCatalogMetricApi | null, arg: any) => Breadcrumb[]
}
}
@@ -209,8 +225,12 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(
props({ name: '' } as DataCatalogMetricSceneLogicProps),
key((props) => props.name),
path((key) => ['products', 'data_catalog', 'frontend', 'dataCatalogMetricSceneLogic', key]),
- connect([dataCatalogAgentSyncLogic]),
+ connect(() => ({
+ logic: [dataCatalogAgentSyncLogic],
+ values: [featureFlagLogic, ['featureFlags']],
+ })),
actions({
+ setActiveTab: (activeTab: MetricSceneTab) => ({ activeTab }),
// Declared here as well as by the loader: the loader takes a breakpoint, so without this the
// generated action would require a payload every call site has to pass.
loadMetric: true,
@@ -258,6 +278,14 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(
],
})),
reducers({
+ activeTab: ['definition' as MetricSceneTab, { setActiveTab: (_, { activeTab }) => activeTab }],
+ visitedTabs: [
+ [] as MetricSceneTab[],
+ {
+ setActiveTab: (state: MetricSceneTab[], { activeTab }: { activeTab: MetricSceneTab }) =>
+ state.includes(activeTab) ? state : [...state, activeTab],
+ },
+ ],
mutating: [
false,
{
@@ -291,6 +319,21 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(
],
}),
selectors({
+ mountedTabs: [
+ (s) => [s.activeTab, s.visitedTabs],
+ (activeTab: MetricSceneTab, visitedTabs: MetricSceneTab[]): MetricSceneTab[] =>
+ visitedTabs.includes(activeTab) ? visitedTabs : [...visitedTabs, activeTab],
+ ],
+ // The metric check endpoints are gated on the same flag, so a project outside the rollout
+ // must not reach the Tests tab: every request it makes is rejected.
+ metricChecksEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.DATA_QUALITY_CHECKS],
+ ],
+ supportsMetricChecks: [
+ (s) => [s.metric],
+ (metric: DataCatalogMetricApi | null): boolean => metric?.definition_kind === 'HogQLQuery',
+ ],
breadcrumbs: [
(s) => [s.metric, (_, props) => props.name],
(metric: DataCatalogMetricApi | null, name: string): Breadcrumb[] => [
@@ -425,7 +468,7 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(
await dataCatalogMetricsPartialUpdate(projectId(), props.name, { name })
lemonToast.success('Metric renamed')
// The logic is keyed by name, so navigating remounts a fresh instance at the new URL.
- router.actions.replace(urls.dataCatalogMetric(name))
+ router.actions.replace(urls.dataCatalogMetric(name, values.activeTab))
} catch (error) {
lemonToast.error(apiErrorDetail(error) || 'Could not rename the metric. Try again.')
actions.setMutating(false)
@@ -435,7 +478,7 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(
if (values.editingDefinition) {
pendingDraftByName.set(pendingDraftKey(name), values.draftMarkdown)
}
- router.actions.replace(urls.dataCatalogMetric(name))
+ router.actions.replace(urls.dataCatalogMetric(name, values.activeTab))
},
deleteMetric: async () => {
if (values.mutating || isInvalidMetricName(props.name)) {
@@ -452,8 +495,23 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(
}
},
})),
- urlToAction(({ actions }) => ({
- [urls.dataCatalogMetric(':name')]: (_, searchParams) => {
+ actionToUrl(({ props }) => ({
+ setActiveTab: ({ activeTab }) => urls.dataCatalogMetric(props.name, activeTab),
+ })),
+ urlToAction(({ actions, values, props }) => ({
+ [urls.dataCatalogMetric(':name')]: ({ name }, searchParams) => {
+ if (name !== props.name) {
+ return
+ }
+ const requestedTab = searchParams.tab === 'tests' ? 'tests' : 'definition'
+ const activeTab = requestedTab === 'tests' && !values.metricChecksEnabled ? 'definition' : requestedTab
+ if (activeTab !== requestedTab) {
+ // Drop the param so a refresh or a back navigation does not ask for the tab again.
+ router.actions.replace(urls.dataCatalogMetric(props.name, activeTab))
+ }
+ if (activeTab !== values.activeTab) {
+ actions.setActiveTab(activeTab)
+ }
if (searchParams.edit === 'definition') {
actions.setPendingDefinitionEdit(true)
// Consume the param so refresh or back does not reopen the editor.
diff --git a/products/data_catalog/frontend/tabs/MetricTestsTab.stories.tsx b/products/data_catalog/frontend/tabs/MetricTestsTab.stories.tsx
new file mode 100644
index 000000000000..a474e762d064
--- /dev/null
+++ b/products/data_catalog/frontend/tabs/MetricTestsTab.stories.tsx
@@ -0,0 +1,92 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { dataCatalogMetricSceneLogic } from '../dataCatalogMetricSceneLogic'
+import { MetricTestsTab } from './MetricTestsTab'
+
+interface StoryProps {
+ definitionKind: string | null
+ hasCheck: boolean
+}
+
+const meta: Meta<StoryProps> = {
+ title: 'Data catalog/Metric tests',
+ args: { definitionKind: 'HogQLQuery', hasCheck: false },
+ parameters: { mockDate: '2026-09-04', viewMode: 'story' },
+ render: ({ definitionKind, hasCheck }) => {
+ useStorybookMocks({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/signups/': {
+ id: 'metric-1',
+ name: 'signups',
+ definition_kind: definitionKind,
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/': {
+ results: hasCheck
+ ? [
+ {
+ id: 'check-1',
+ name: 'daily_signups',
+ check_type: 'custom_sql',
+ column_name: '',
+ enabled: true,
+ severity: 'error',
+ last_status: 'failed',
+ config: { query: 'SELECT * FROM {metric} WHERE signups < 100' },
+ tags: [],
+ },
+ ]
+ : [],
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/health/': {
+ health: hasCheck ? 'failing' : 'unknown',
+ checks_total: hasCheck ? 1 : 0,
+ checks_failing: hasCheck ? 1 : 0,
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/check_types/': [
+ {
+ check_type: 'custom_sql',
+ description: 'Return one row per failure.',
+ requires_column: false,
+ config_schema: {},
+ },
+ ],
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/check_suite_runs/': { results: [] },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/schedule/': {
+ id: 'schedule-1',
+ enabled: true,
+ interval: '24hour',
+ next_run_at: '2026-09-05T00:00:00Z',
+ last_run_at: null,
+ last_suite_run: null,
+ },
+ },
+ })
+ return (
+ <BindLogic logic={dataCatalogMetricSceneLogic} props={{ name: 'signups' }}>
+ <div className="max-w-2xl">
+ <MetricTestsTab />
+ </div>
+ </BindLogic>
+ )
+ },
+}
+
+export default meta
+type Story = StoryObj<StoryProps>
+export const Empty: Story = {}
+export const Scheduled: Story = { args: { hasCheck: true } }
+export const Unsupported: Story = { args: { definitionKind: 'MarkdownDefinition' } }
+export const UnsupportedWithChecks: Story = { args: { definitionKind: 'MarkdownDefinition', hasCheck: true } }
+export const Narrow: Story = {
+ args: { hasCheck: true },
+ decorators: [
+ (Story) => (
+ <div className="w-128">
+ <Story />
+ </div>
+ ),
+ ],
+}
diff --git a/products/data_catalog/frontend/tabs/MetricTestsTab.test.tsx b/products/data_catalog/frontend/tabs/MetricTestsTab.test.tsx
new file mode 100644
index 000000000000..147628462de7
--- /dev/null
+++ b/products/data_catalog/frontend/tabs/MetricTestsTab.test.tsx
@@ -0,0 +1,105 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { BindLogic } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { expectLogic } from '~/test/keaTestUtils'
+
+import { dataCatalogMetricSceneLogic } from '../dataCatalogMetricSceneLogic'
+import { MetricTestsTab } from './MetricTestsTab'
+
+describe('MetricTestsTab', () => {
+ afterEach(cleanup)
+ it.each(['HogQLQuery', 'MarkdownDefinition'])('offers the check editor only for SQL metrics (%s)', async (kind) => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/signups/': {
+ id: 'metric-1',
+ name: 'signups',
+ definition_kind: kind,
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/': { results: [] },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/health/': {
+ health: 'unknown',
+ checks_total: 0,
+ checks_failing: 0,
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/check_suite_runs/': { results: [] },
+ },
+ })
+ initKeaTests()
+ const logic = dataCatalogMetricSceneLogic({ name: 'signups' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadMetricSuccess'])
+ render(
+ <BindLogic logic={dataCatalogMetricSceneLogic} props={{ name: 'signups' }}>
+ <MetricTestsTab />
+ </BindLogic>
+ )
+ if (kind === 'HogQLQuery') {
+ expect(await screen.findByText('Add your first check')).toBeInTheDocument()
+ expect(screen.getByText(/queries \{metric\}/)).toBeInTheDocument()
+ expect(screen.queryByText('Run automatically')).not.toBeInTheDocument()
+ } else {
+ expect(await screen.findByText(/Tests are available for SQL metrics only/)).toBeInTheDocument()
+ expect(screen.queryByText('New check')).not.toBeInTheDocument()
+ }
+ logic.unmount()
+ })
+
+ it('lists the checks a metric kept after its definition stopped being SQL', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_catalog/metrics/signups/': {
+ id: 'metric-1',
+ name: 'signups',
+ definition_kind: 'MarkdownDefinition',
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/': {
+ results: [
+ {
+ id: 'check-1',
+ name: 'Signups are positive',
+ check_type: 'custom_sql',
+ enabled: true,
+ severity: 'error',
+ last_status: 'errored',
+ config: {},
+ tags: [],
+ },
+ ],
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/health/': {
+ health: 'failing',
+ checks_total: 1,
+ checks_failing: 1,
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/schedule/': {
+ id: 'schedule-1',
+ enabled: true,
+ interval: '24hour',
+ next_run_at: null,
+ last_run_at: null,
+ last_suite_run: null,
+ },
+ '/api/projects/:team_id/data_catalog/metrics/metric-1/check_suite_runs/': { results: [] },
+ },
+ })
+ initKeaTests()
+ const logic = dataCatalogMetricSceneLogic({ name: 'signups' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadMetricSuccess'])
+ render(
+ <BindLogic logic={dataCatalogMetricSceneLogic} props={{ name: 'signups' }}>
+ <MetricTestsTab />
+ </BindLogic>
+ )
+ expect(await screen.findByText('Signups are positive')).toBeInTheDocument()
+ expect(screen.getByText(/definition is not SQL/)).toBeInTheDocument()
+ expect(screen.getByText('Run automatically')).toBeInTheDocument()
+ expect(screen.getByText('New check').closest('button')).toHaveAttribute('aria-disabled', 'true')
+ logic.unmount()
+ })
+})
diff --git a/products/data_catalog/frontend/tabs/MetricTestsTab.tsx b/products/data_catalog/frontend/tabs/MetricTestsTab.tsx
new file mode 100644
index 000000000000..ff2c11c1e4fe
--- /dev/null
+++ b/products/data_catalog/frontend/tabs/MetricTestsTab.tsx
@@ -0,0 +1,50 @@
+import { useValues } from 'kea'
+
+import { LemonBanner, Spinner } from '@posthog/lemon-ui'
+
+import { dataQualityChecksLogic } from 'products/data_quality/frontend/dataQualityChecksLogic'
+import { MetricChecksPanel } from 'products/data_quality/frontend/MetricChecksPanel'
+
+import { dataCatalogMetricSceneLogic } from '../dataCatalogMetricSceneLogic'
+
+const NEW_CHECK_NEEDS_SQL_REASON = 'Tests are available for SQL metrics only'
+
+export function MetricTestsTab(): JSX.Element | null {
+ const { metric, supportsMetricChecks } = useValues(dataCatalogMetricSceneLogic)
+
+ if (!metric) {
+ return null
+ }
+ if (!supportsMetricChecks) {
+ return <UnsupportedDefinitionTests metricId={metric.id} />
+ }
+
+ return <MetricChecksPanel metricId={metric.id} />
+}
+
+function UnsupportedDefinitionTests({ metricId }: { metricId: string }): JSX.Element {
+ const { checks, checksLoaded, checksLoadError } = useValues(
+ dataQualityChecksLogic({ subjectType: 'metric', subjectId: metricId })
+ )
+
+ if (!checksLoaded && !checksLoadError) {
+ return <Spinner />
+ }
+ if (checks.length === 0) {
+ return (
+ <LemonBanner type="info">
+ Tests are available for SQL metrics only. Save a HogQL query as this metric's definition to add checks.
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <>
+ <LemonBanner type="warning">
+ This metric's definition is not SQL, so these checks fail on every run. Turn them off or delete them, or
+ save a HogQL query as the definition.
+ </LemonBanner>
+ <MetricChecksPanel metricId={metricId} newCheckDisabledReason={NEW_CHECK_NEEDS_SQL_REASON} />
+ </>
+ )
+}
diff --git a/products/data_catalog/frontend/tabs/MetricTestsTabLabel.tsx b/products/data_catalog/frontend/tabs/MetricTestsTabLabel.tsx
new file mode 100644
index 000000000000..1f5ab7d94b9f
--- /dev/null
+++ b/products/data_catalog/frontend/tabs/MetricTestsTabLabel.tsx
@@ -0,0 +1,16 @@
+import { useValues } from 'kea'
+
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { dataQualityChecksLogic } from 'products/data_quality/frontend/dataQualityChecksLogic'
+
+export function MetricTestsTabLabel({ metricId }: { metricId: string }): JSX.Element {
+ const { health } = useValues(dataQualityChecksLogic({ subjectType: 'metric', subjectId: metricId }))
+ const failing = health?.checks_failing ?? 0
+
+ return (
+ <span className="flex items-center gap-1">
+ Tests{failing > 0 && <LemonTag type="danger">{failing} failing</LemonTag>}
+ </span>
+ )
+}
diff --git a/products/data_catalog/manifest.tsx b/products/data_catalog/manifest.tsx
index 4cf93e08a2b1..064caf0a5e00 100644
--- a/products/data_catalog/manifest.tsx
+++ b/products/data_catalog/manifest.tsx
@@ -28,7 +28,8 @@ export const manifest: ProductManifest = {
redirects: {},
urls: {
dataCatalog: (tab?: string): string => `/data-catalog${tab ? `?tab=${tab}` : ''}`,
- dataCatalogMetric: (name: string): string => `/data-catalog/metrics/${name}`,
+ dataCatalogMetric: (name: string, tab?: 'definition' | 'tests'): string =>
+ `/data-catalog/metrics/${name}${tab === 'tests' ? '?tab=tests' : ''}`,
},
fileSystemTypes: {},
treeItemsNew: [],
diff --git a/products/data_quality/frontend/CheckEditorModal.tsx b/products/data_quality/frontend/CheckEditorModal.tsx
index c5c4a969a8ef..52f68de42f51 100644
--- a/products/data_quality/frontend/CheckEditorModal.tsx
+++ b/products/data_quality/frontend/CheckEditorModal.tsx
@@ -273,6 +273,7 @@ function CustomSqlField(): JSX.Element {
customSqlPreviewVerdict,
customSqlQueryKey,
customSqlSourceQuery,
+ isMetricSubject,
} = useValues(dataQualityCheckEditorLogic)
const { runCustomSqlPreview, setCustomSqlEditorError, setCustomSqlValidationLoading } =
useActions(dataQualityCheckEditorLogic)
@@ -293,7 +294,11 @@ function CustomSqlField(): JSX.Element {
<LemonField
name="customSql"
label="Query"
- help="Return one row per failure. The check passes when the query returns nothing."
+ help={
+ isMetricSubject
+ ? 'Query the saved metric output through {metric} exactly once. Return one row per failure; no rows means the check passes. Save the check, then run it to see the result.'
+ : 'Return one row per failure. The check passes when the query returns nothing.'
+ }
>
{({ value, onChange }) => (
<div className="flex flex-col gap-2">
@@ -303,32 +308,35 @@ function CustomSqlField(): JSX.Element {
onChange={(query) => onChange(query ?? '')}
queryKey={customSqlQueryKey}
sourceQuery={customSqlSourceQuery}
- onError={setCustomSqlEditorError}
- onMetadataLoading={setCustomSqlValidationLoading}
- onPressCmdEnter={() => runCustomSqlPreview(undefined)}
+ metadataQuery={isMetricSubject ? '' : undefined}
+ onError={isMetricSubject ? undefined : setCustomSqlEditorError}
+ onMetadataLoading={isMetricSubject ? undefined : setCustomSqlValidationLoading}
+ onPressCmdEnter={isMetricSubject ? undefined : () => runCustomSqlPreview(undefined)}
autoFocus
minHeight="8rem"
maxHeight="40vh"
/>
- <div className="flex flex-col items-end gap-1">
- <LemonButton
- type="secondary"
- size="small"
- loading={customSqlPreviewLoading}
- disabledReason={
- !value?.trim()
- ? 'Write a query before testing it.'
- : (customSqlEditorError ?? undefined)
- }
- onClick={runCustomSqlPreview}
- data-attr="data-quality-check-test-query"
- >
- Test query
- </LemonButton>
- {customSqlPreviewStale && (
- <span className="text-secondary text-xs">The query changed since the last test.</span>
- )}
- </div>
+ {!isMetricSubject && (
+ <div className="flex flex-col items-end gap-1">
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={customSqlPreviewLoading}
+ disabledReason={
+ !value?.trim()
+ ? 'Write a query before testing it.'
+ : (customSqlEditorError ?? undefined)
+ }
+ onClick={runCustomSqlPreview}
+ data-attr="data-quality-check-test-query"
+ >
+ Test query
+ </LemonButton>
+ {customSqlPreviewStale && (
+ <span className="text-secondary text-xs">The query changed since the last test.</span>
+ )}
+ </div>
+ )}
{customSqlPreviewError ? (
<LemonBanner type="error">{customSqlPreviewError}</LemonBanner>
) : !customSqlPreviewLoading && customSqlPreview && customSqlPreviewVerdict ? (
diff --git a/products/data_quality/frontend/CheckRunsTable.test.tsx b/products/data_quality/frontend/CheckRunsTable.test.tsx
new file mode 100644
index 000000000000..8804c0cb08d8
--- /dev/null
+++ b/products/data_quality/frontend/CheckRunsTable.test.tsx
@@ -0,0 +1,71 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import { CheckRunsTable } from './CheckRunsTable'
+import type { DataQualityCheckRunApi } from './generated/api.schemas'
+
+const PASSING_METRIC_RUN: DataQualityCheckRunApi = {
+ id: 'pass',
+ quality_check: 'check-1',
+ check_name: 'Signups stay positive',
+ suite_run: 'suite-1',
+ subject_type: 'metric',
+ subject_uuid: '018f2a1c-0000-7000-8000-000000000001',
+ subject_name: 'signups',
+ check_type: 'custom_sql',
+ column_name: '',
+ check_config: null,
+ check_severity: 'error',
+ status: 'passed',
+ failed_row_count: 0,
+ observed_value: 0,
+ compiled_query: 'SELECT count() FROM signups',
+ error: '',
+ duration_ms: 20,
+ started_at: null,
+ finished_at: null,
+ created_at: '2026-09-01T00:00:00Z',
+}
+
+function metricRun(overrides: Partial<DataQualityCheckRunApi>): DataQualityCheckRunApi {
+ return { ...PASSING_METRIC_RUN, ...overrides }
+}
+
+describe('CheckRunsTable', () => {
+ afterEach(cleanup)
+ it('shows metric failures and execution errors without an observed metric value', () => {
+ initKeaTests()
+ render(
+ <CheckRunsTable
+ subjectType="metric"
+ runs={[
+ PASSING_METRIC_RUN,
+ metricRun({
+ id: 'fail',
+ status: 'failed',
+ failed_row_count: 7,
+ observed_value: 7,
+ duration_ms: 30,
+ }),
+ metricRun({
+ id: 'error',
+ status: 'errored',
+ failed_row_count: null,
+ observed_value: null,
+ duration_ms: 40,
+ error: 'Unknown column signups',
+ }),
+ ]}
+ />
+ )
+ expect(screen.getByText('passed')).toBeInTheDocument()
+ expect(screen.getByText('failed')).toBeInTheDocument()
+ expect(screen.getByText('errored')).toBeInTheDocument()
+ expect(screen.getByText('7')).toBeInTheDocument()
+ expect(screen.getByText('Unknown column signups')).toBeInTheDocument()
+ expect(screen.queryByText('Observed value')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/data_quality/frontend/CheckRunsTable.tsx b/products/data_quality/frontend/CheckRunsTable.tsx
index e8aadb2b38f1..5efb55127633 100644
--- a/products/data_quality/frontend/CheckRunsTable.tsx
+++ b/products/data_quality/frontend/CheckRunsTable.tsx
@@ -5,6 +5,7 @@ import { LemonTableColumn } from 'lib/lemon-ui/LemonTable'
import { humanFriendlyDuration } from 'lib/utils/durations'
import { humanFriendlyNumber } from 'lib/utils/numbers'
+import type { DataQualitySubjectType } from './checksApi'
import { CHECK_STATUS_TAG_TYPES, byStatusAttention, checkRunDisplayName } from './checksConstants'
import type { DataQualityCheckRunApi } from './generated/api.schemas'
@@ -61,9 +62,12 @@ interface CheckRunsTableProps {
runs: DataQualityCheckRunApi[]
loading?: boolean
showCheck?: boolean
+ subjectType?: DataQualitySubjectType
}
-export function CheckRunsTable({ runs, loading, showCheck }: CheckRunsTableProps): JSX.Element {
+export function CheckRunsTable({ runs, loading, showCheck, subjectType }: CheckRunsTableProps): JSX.Element {
+ const outcomeColumns =
+ subjectType === 'metric' ? OUTCOME_COLUMNS.filter((column) => column.key !== 'observed_value') : OUTCOME_COLUMNS
return (
<LemonTable
size="small"
@@ -71,7 +75,7 @@ export function CheckRunsTable({ runs, loading, showCheck }: CheckRunsTableProps
loading={loading}
nouns={['run', 'runs']}
emptyState="No runs yet"
- columns={showCheck ? [CHECK_COLUMN, ...OUTCOME_COLUMNS] : OUTCOME_COLUMNS}
+ columns={showCheck ? [CHECK_COLUMN, ...outcomeColumns] : outcomeColumns}
/>
)
}
diff --git a/products/data_quality/frontend/ChecksTable.tsx b/products/data_quality/frontend/ChecksTable.tsx
index d99d25a3d664..b74e0cd018a7 100644
--- a/products/data_quality/frontend/ChecksTable.tsx
+++ b/products/data_quality/frontend/ChecksTable.tsx
@@ -47,6 +47,7 @@ export function ChecksTable({ columns, ...props }: ChecksTableProps): JSX.Elemen
<div className="flex flex-col gap-2 py-2">
{check.description && <p className="mb-0 text-secondary">{check.description}</p>}
<CheckRunsTable
+ subjectType={props.subjectType}
runs={checkRunsByCheckId[check.id] ?? []}
loading={pendingCheckActions.loadingRuns[check.id]}
/>
diff --git a/products/data_quality/frontend/DataQualityChecksPanel.tsx b/products/data_quality/frontend/DataQualityChecksPanel.tsx
index 8d4efee2ca88..3cdd65e065bb 100644
--- a/products/data_quality/frontend/DataQualityChecksPanel.tsx
+++ b/products/data_quality/frontend/DataQualityChecksPanel.tsx
@@ -19,6 +19,7 @@ interface DataQualityChecksPanelProps extends DataQualityChecksLogicProps {
dataLastSyncedAt?: string | null
/** Uses "Checks" where the surrounding surface already names Data quality. */
hideTitle?: boolean
+ newCheckDisabledReason?: string
notice?: ReactNode
}
@@ -26,6 +27,7 @@ export function DataQualityChecksPanel({
columns,
dataLastSyncedAt,
hideTitle,
+ newCheckDisabledReason,
notice,
...logicProps
}: DataQualityChecksPanelProps): JSX.Element | null {
@@ -34,6 +36,8 @@ export function DataQualityChecksPanel({
health,
checks,
checksLoading,
+ checksLoadError,
+ checksLoaded,
enabledChecksCount,
isSuiteRunning,
pollTimedOut,
@@ -55,14 +59,24 @@ export function DataQualityChecksPanel({
const addCheck = (): void => openEditor(null, logicProps, columnNames)
if (accessDenied) {
- return null
+ return logicProps.subjectType === 'metric' ? (
+ <p className="text-secondary">You don't have access to the tests for this metric.</p>
+ ) : null
+ }
+
+ if (checksLoadError && !checksLoaded) {
+ return (
+ <LemonBanner type="error" action={{ children: 'Retry', onClick: loadChecks }}>
+ Could not load the checks. Try again.
+ </LemonBanner>
+ )
}
return (
<BindLogic logic={dataQualityCheckEditorLogic} props={editorProps}>
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-2 flex-wrap">
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 flex-wrap">
<h3 className="mb-0 text-lg font-semibold">{hideTitle ? 'Checks' : 'Data quality'}</h3>
{health && (
<LemonTag type={HEALTH_TAG_TYPES[health.health] ?? 'default'}>
@@ -78,7 +92,7 @@ export function DataQualityChecksPanel({
<span className="text-secondary text-sm">Run checks to see health</span>
)}
</div>
- <div className="flex items-center gap-2">
+ <div className="flex items-center gap-2 flex-wrap">
<LemonButton
type="secondary"
size="small"
@@ -95,7 +109,13 @@ export function DataQualityChecksPanel({
>
Run all checks
</LemonButton>
- <LemonButton type="primary" size="small" onClick={addCheck} data-attr="data-quality-new-check">
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={addCheck}
+ disabledReason={newCheckDisabledReason}
+ data-attr="data-quality-new-check"
+ >
New check
</LemonButton>
</div>
@@ -110,6 +130,11 @@ export function DataQualityChecksPanel({
</p>
)}
+ {checksLoadError && (
+ <LemonBanner type="warning" action={{ children: 'Retry', onClick: loadChecks }}>
+ Could not refresh the checks. Showing the latest available results.
+ </LemonBanner>
+ )}
{isSuiteRunning && (
<LemonBanner type="info" icon={<Spinner />}>
Running checks...
@@ -131,7 +156,11 @@ export function DataQualityChecksPanel({
)}
{!checksLoading && checks.length === 0 ? (
- <NoChecksYet onAddCheck={addCheck} />
+ <NoChecksYet
+ onAddCheck={addCheck}
+ isMetric={logicProps.subjectType === 'metric'}
+ disabledReason={newCheckDisabledReason}
+ />
) : (
<ChecksTable {...logicProps} columns={columnNames} />
)}
@@ -144,14 +173,30 @@ export function DataQualityChecksPanel({
)
}
-function NoChecksYet({ onAddCheck }: { onAddCheck: () => void }): JSX.Element {
+function NoChecksYet({
+ onAddCheck,
+ isMetric,
+ disabledReason,
+}: {
+ onAddCheck: () => void
+ isMetric: boolean
+ disabledReason?: string
+}): JSX.Element {
return (
<div className="border rounded p-4 flex flex-col items-start gap-2">
<h4 className="mb-0">No checks yet</h4>
<p className="mb-0 text-secondary">
- Checks verify this data automatically after each sync or materialization.
+ {isMetric
+ ? 'Write a custom SQL check that queries {metric} and returns one row per failure. Checks run daily after you add the first check.'
+ : 'Checks verify this data automatically after each sync or materialization.'}
</p>
- <LemonButton type="primary" size="small" onClick={onAddCheck} data-attr="data-quality-first-check">
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={onAddCheck}
+ disabledReason={disabledReason}
+ data-attr="data-quality-first-check"
+ >
Add your first check
</LemonButton>
</div>
diff --git a/products/data_quality/frontend/DataQualitySchedule.tsx b/products/data_quality/frontend/DataQualitySchedule.tsx
new file mode 100644
index 000000000000..21d7233eb28c
--- /dev/null
+++ b/products/data_quality/frontend/DataQualitySchedule.tsx
@@ -0,0 +1,78 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonSelect, LemonSwitch, Spinner } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+
+import { DataQualityScheduleLogicProps, dataQualityScheduleLogic } from './dataQualityScheduleLogic'
+import { DataQualityScheduleIntervalEnumApi } from './generated/api.schemas'
+
+export function DataQualitySchedule(props: DataQualityScheduleLogicProps): JSX.Element {
+ const { schedule, scheduleLoading, scheduleError } = useValues(dataQualityScheduleLogic(props))
+ const { loadSchedule, updateSchedule } = useActions(dataQualityScheduleLogic(props))
+
+ if (!schedule) {
+ return scheduleError ? (
+ <LemonBanner type="error" action={{ children: 'Retry', onClick: loadSchedule }}>
+ Could not load the check schedule. Try again.
+ </LemonBanner>
+ ) : (
+ <Spinner />
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center flex-wrap gap-2">
+ <LemonSwitch
+ checked={schedule.enabled}
+ onChange={(enabled) => updateSchedule({ enabled })}
+ disabled={scheduleLoading || !!scheduleError?.uncertain}
+ label="Run automatically"
+ data-attr="data-quality-schedule-enabled"
+ />
+ <LemonSelect
+ value={schedule.interval}
+ disabledReason={
+ scheduleLoading
+ ? 'Saving schedule'
+ : scheduleError?.uncertain
+ ? 'Reload the schedule to try again'
+ : undefined
+ }
+ onChange={(interval) => updateSchedule({ interval })}
+ size="small"
+ data-attr="data-quality-schedule-interval"
+ options={[
+ { value: DataQualityScheduleIntervalEnumApi['1hour'], label: 'Every hour' },
+ { value: DataQualityScheduleIntervalEnumApi['6hour'], label: 'Every 6 hours' },
+ { value: DataQualityScheduleIntervalEnumApi['12hour'], label: 'Every 12 hours' },
+ { value: DataQualityScheduleIntervalEnumApi['24hour'], label: 'Daily' },
+ { value: DataQualityScheduleIntervalEnumApi['7day'], label: 'Weekly' },
+ ]}
+ />
+ {scheduleLoading ? (
+ <Spinner />
+ ) : (
+ schedule.enabled &&
+ schedule.next_run_at && (
+ <span className="text-secondary text-sm">
+ Next run <TZLabel time={schedule.next_run_at} />
+ </span>
+ )
+ )}
+ </div>
+ {scheduleError &&
+ (scheduleError.uncertain ? (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Reload', onClick: loadSchedule, loading: scheduleLoading }}
+ >
+ Could not confirm the schedule update. Reload it before trying again.
+ </LemonBanner>
+ ) : (
+ <LemonBanner type="error">{scheduleError.message}</LemonBanner>
+ ))}
+ </div>
+ )
+}
diff --git a/products/data_quality/frontend/MetricChecksPanel.tsx b/products/data_quality/frontend/MetricChecksPanel.tsx
new file mode 100644
index 000000000000..02323beea839
--- /dev/null
+++ b/products/data_quality/frontend/MetricChecksPanel.tsx
@@ -0,0 +1,25 @@
+import { useValues } from 'kea'
+
+import { dataQualityChecksLogic } from './dataQualityChecksLogic'
+import { DataQualityChecksPanel } from './DataQualityChecksPanel'
+import { DataQualitySchedule } from './DataQualitySchedule'
+
+interface MetricChecksPanelProps {
+ metricId: string
+ newCheckDisabledReason?: string
+}
+
+export function MetricChecksPanel({ metricId, newCheckDisabledReason }: MetricChecksPanelProps): JSX.Element | null {
+ const { checks } = useValues(dataQualityChecksLogic({ subjectType: 'metric', subjectId: metricId }))
+
+ return (
+ <DataQualityChecksPanel
+ subjectType="metric"
+ subjectId={metricId}
+ columns={[]}
+ hideTitle
+ newCheckDisabledReason={newCheckDisabledReason}
+ notice={checks.length > 0 ? <DataQualitySchedule metricId={metricId} /> : undefined}
+ />
+ )
+}
diff --git a/products/data_quality/frontend/SuiteRunsHistory.tsx b/products/data_quality/frontend/SuiteRunsHistory.tsx
index d9ce34b700a0..29071aa34766 100644
--- a/products/data_quality/frontend/SuiteRunsHistory.tsx
+++ b/products/data_quality/frontend/SuiteRunsHistory.tsx
@@ -50,6 +50,7 @@ export function SuiteRunsHistory(props: DataQualityChecksLogicProps): JSX.Elemen
onRowExpand: (suiteRun) => loadSuiteRunCheckRuns(suiteRun.id),
expandedRowRender: (suiteRun) => (
<CheckRunsTable
+ subjectType={props.subjectType}
runs={suiteRunCheckRunsBySuiteRunId[suiteRun.id] ?? []}
loading={pendingCheckActions.loadingSuiteRunRuns[suiteRun.id]}
showCheck
diff --git a/products/data_quality/frontend/checksConstants.ts b/products/data_quality/frontend/checksConstants.ts
index 233bf0262769..69108c5f2654 100644
--- a/products/data_quality/frontend/checksConstants.ts
+++ b/products/data_quality/frontend/checksConstants.ts
@@ -67,6 +67,7 @@ export const HEALTH_LABELS: Record<string, string> = {
export const SUBJECT_TYPE_TAGS: Record<string, { label: string; type: LemonTagType }> = {
table: { label: 'Table', type: 'default' },
view: { label: 'View', type: 'primary' },
+ metric: { label: 'Metric', type: 'option' },
}
export const SEVERITY_TAG_TYPES: Record<string, LemonTagType> = {
diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts
index f4cd2abddbbd..c71ae58491a7 100644
--- a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts
+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts
@@ -10,6 +10,9 @@ import { expectLogic } from '~/test/keaTestUtils'
import { DataQualitySubjectRef } from './checksApi'
import { DataQualityCheckEditorLogicProps, dataQualityCheckEditorLogic } from './dataQualityCheckEditorLogic'
import {
+ dataCatalogMetricsChecksCheckTypesList,
+ dataCatalogMetricsChecksCreate,
+ dataCatalogMetricsChecksPartialUpdate,
warehouseSavedQueriesChecksCheckTypesList,
warehouseSavedQueriesChecksCreate,
warehouseSavedQueriesChecksPartialUpdate,
@@ -80,6 +83,9 @@ jest.mock('scenes/data-management/database/databaseTableListLogic', () => {
})
jest.mock('./generated/api', () => ({
+ dataCatalogMetricsChecksCheckTypesList: jest.fn(),
+ dataCatalogMetricsChecksCreate: jest.fn(),
+ dataCatalogMetricsChecksPartialUpdate: jest.fn(),
warehouseSavedQueriesChecksCreate: jest.fn(),
warehouseSavedQueriesChecksPartialUpdate: jest.fn(),
warehouseSavedQueriesChecksCheckTypesList: jest.fn(),
@@ -162,6 +168,76 @@ describe('dataQualityCheckEditorLogic', () => {
logic?.unmount()
})
+ it('authors metric SQL with a relation placeholder, no column, and no raw query execution', async () => {
+ ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(
+ CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql')
+ )
+ ;(dataCatalogMetricsChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ check_type: 'custom_sql' }))
+ await mountLogic()
+ logic.actions.openEditor(null, { subjectType: 'metric', subjectId: 'metric-1' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.checkForm).toMatchObject({
+ checkType: 'custom_sql',
+ columnName: '',
+ customSql: 'SELECT *\nFROM {metric}\nWHERE <failure condition>',
+ })
+ expect(logic.values.checkTypes.map((type) => type.check_type)).toEqual(['custom_sql'])
+ expect(logic.values.requiresColumn).toBe(false)
+ expect(logic.values.needsWarehouseCatalog).toBe(false)
+ expect(logic.values.isMetricSubject).toBe(true)
+ logic.actions.setCheckFormValue('customSql', 'SELECT * FROM {metric} WHERE signups < 100')
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(dataCatalogMetricsChecksCreate).toHaveBeenCalledWith(
+ '1',
+ 'metric-1',
+ expect.objectContaining({
+ check_type: 'custom_sql',
+ column_name: '',
+ config: { query: 'SELECT * FROM {metric} WHERE signups < 100' },
+ })
+ )
+ expect(performQuery).not.toHaveBeenCalled()
+ })
+
+ it('does not let a late table catalog replace the metric-only check types', async () => {
+ let resolveTableCatalog: (catalog: typeof CHECK_TYPE_CATALOG) => void = () => {}
+ ;(warehouseTablesChecksCheckTypesList as jest.Mock).mockReturnValue(
+ new Promise((resolve) => {
+ resolveTableCatalog = resolve
+ })
+ )
+ ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(
+ CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql')
+ )
+ await mountLogic()
+ logic.actions.openEditor(null, { subjectType: 'table', subjectId: 'table-1' }, COLUMNS)
+ logic.actions.openEditor(null, { subjectType: 'metric', subjectId: 'metric-1' })
+ await expectLogic(logic).toDispatchActions(['loadCheckTypesSuccess'])
+ resolveTableCatalog(CHECK_TYPE_CATALOG)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.checkTypes.map((type) => type.check_type)).toEqual(['custom_sql'])
+ })
+
+ it('discards an in-flight table preview when opening a metric check', async () => {
+ let resolvePreview: (response: { columns: string[]; results: unknown[][] }) => void = () => {}
+ ;(performQuery as jest.Mock).mockReturnValue(
+ new Promise((resolve) => {
+ resolvePreview = resolve
+ })
+ )
+ ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(
+ CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql')
+ )
+ await mountLogic()
+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT 1' })
+ logic.actions.runCustomSqlPreview(undefined)
+ logic.actions.openEditor(null, { subjectType: 'metric', subjectId: 'metric-1' })
+ resolvePreview({ columns: ['value'], results: [[1]] })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.customSqlPreview).toBeNull()
+ })
+
it.each<[string, Record<string, unknown>, Record<string, unknown>]>([
['not_null', { checkType: 'not_null', columnName: 'customer_id' }, { column_name: 'customer_id', config: {} }],
['unique', { checkType: 'unique', columnName: 'customer_id' }, { column_name: 'customer_id', config: {} }],
@@ -237,6 +313,38 @@ describe('dataQualityCheckEditorLogic', () => {
})
})
+ it('leaves an unchanged assertion out of a metadata-only edit', async () => {
+ // The backend revalidates the definition whenever a request carries one, which a metric that
+ // moved off its HogQL definition fails. Renaming its check must not go down that path.
+ ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(
+ CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql')
+ )
+ ;(dataCatalogMetricsChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())
+ await mountLogic()
+ logic.actions.openEditor(
+ buildCheck({
+ check_type: CheckTypeEnumApi.CustomSql,
+ column_name: '',
+ config: { query: 'SELECT 1 FROM {metric}' },
+ name: 'signup_floor',
+ }),
+ { subjectType: 'metric', subjectId: 'metric-1' }
+ )
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setCheckFormValues({ name: 'signups_floor', description: 'renamed' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataCatalogMetricsChecksPartialUpdate).toHaveBeenCalledWith('1', 'metric-1', 'check-1', {
+ severity: 'error',
+ name: 'signups_floor',
+ description: 'renamed',
+ tags: [],
+ })
+ })
+
it('does not submit before the check-type catalog arrives', async () => {
// Enter can submit while the catalog request is still pending. Without it there is no column
// requirement to validate against, so the payload would omit column_name and be rejected.
@@ -666,6 +774,26 @@ describe('dataQualityCheckEditorLogic', () => {
expect(logic.values.checkTypes).toEqual(CHECK_TYPE_CATALOG)
})
+ it('drops a superseded check type request so a late failure keeps the newer catalog', async () => {
+ let failFirst: (error: unknown) => void = () => {}
+ ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock)
+ .mockImplementationOnce(() => new Promise((_resolve, reject) => (failFirst = reject)))
+ .mockResolvedValueOnce(CHECK_TYPE_CATALOG)
+ await mountLogic()
+
+ // The first request stays in flight while a subject change supersedes it.
+ logic.actions.openEditor(null, VIEW_SUBJECT, COLUMNS)
+ await expectLogic(logic, () =>
+ logic.actions.setSubject({ subjectType: 'view', subjectId: 'view-2' })
+ ).toDispatchActions(['loadCheckTypesSuccess'])
+
+ failFirst(new Error('down'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.checkTypesError).toBe(false)
+ expect(logic.values.checkTypes).toEqual(CHECK_TYPE_CATALOG)
+ })
+
it('closes an untouched draft without asking', async () => {
await mountLogic()
await openWith(buildCheck())
diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.ts
index 0755f26c15cd..9fd5579403db 100644
--- a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts
+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.ts
@@ -6,6 +6,7 @@ import { loaders } from 'kea-loaders'
import { ApiError } from 'lib/api'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { objectsEqual } from 'lib/utils/objects'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { performQuery } from '~/queries/query'
@@ -26,6 +27,8 @@ import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi, SubjectTypeEnumApi }
const CHECK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/
+export const METRIC_CHECK_QUERY_TEMPLATE = 'SELECT *\nFROM {metric}\nWHERE <failure condition>'
+
/** Stable code the API returns when another active check already asserts the same thing. */
const DUPLICATE_DEFINITION_CODE = 'duplicate_definition'
@@ -138,9 +141,26 @@ export function checkCreatePayload(form: CheckFormValues, requiresColumn: boolea
}
}
-export function checkEditPayload(form: CheckFormValues, requiresColumn: boolean): CheckEditPayload {
+/** Whether the form asserts something other than what the stored check already asserts. */
+function assertionChanged(definition: CheckDefinitionPayload, check: DataQualityCheckApi): boolean {
+ return (
+ definition.check_type !== check.check_type ||
+ definition.column_name !== (check.column_name ?? '') ||
+ !objectsEqual(definition.config, check.config ?? {})
+ )
+}
+
+export function checkEditPayload(
+ form: CheckFormValues,
+ requiresColumn: boolean,
+ editingCheck: DataQualityCheckApi
+): CheckEditPayload {
+ const definition = definitionPayload(form, requiresColumn)
return {
- ...definitionPayload(form, requiresColumn),
+ // The backend revalidates the definition whenever the request carries one, and a subject that
+ // stopped supporting its check fails that. Send it only when the assertion actually changed,
+ // so renaming a check or lowering its severity stays possible.
+ ...(assertionChanged(definition, editingCheck) ? definition : {}),
severity: form.severity,
// Sent even when blank, unlike create: an edit is how metadata gets cleared.
name: form.name,
@@ -263,6 +283,7 @@ export interface dataQualityCheckEditorLogicValues {
editingCheck: DataQualityCheckApi | null
isCheckFormSubmitting: boolean
isCheckFormValid: boolean
+ isMetricSubject: boolean
isOpen: boolean
needsWarehouseCatalog: boolean
openedWithoutSubject: boolean
@@ -291,7 +312,9 @@ export interface dataQualityCheckEditorLogicActions {
closeEditor: () => {
value: true
}
- loadCheckTypes: () => any
+ loadCheckTypes: () => {
+ value: true
+ }
loadCheckTypesFailure: (
error: string,
errorObject?: any
@@ -301,10 +324,14 @@ export interface dataQualityCheckEditorLogicActions {
}
loadCheckTypesSuccess: (
checkTypes: DataQualityCheckTypeApi[],
- payload?: any
+ payload?: {
+ value: true
+ }
) => {
checkTypes: DataQualityCheckTypeApi[]
- payload?: any
+ payload?: {
+ value: true
+ }
}
loadWarehouseCatalog: () => {
value: true
@@ -333,10 +360,10 @@ export interface dataQualityCheckEditorLogicActions {
errorObject?: any
}
runCustomSqlPreviewSuccess: (
- customSqlPreview: CustomSqlPreview,
+ customSqlPreview: CustomSqlPreview | null,
payload?: any
) => {
- customSqlPreview: CustomSqlPreview
+ customSqlPreview: CustomSqlPreview | null
payload?: any
}
setCheckFormManualErrors: (errors: Record<string, any>) => {
@@ -389,6 +416,7 @@ export interface dataQualityCheckEditorLogicActions {
export interface dataQualityCheckEditorLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ isMetricSubject: (subject: DataQualitySubjectRef | null) => boolean
checkTypeByName: (checkTypes: DataQualityCheckTypeApi[]) => {
[k: string]: DataQualityCheckTypeApi
}
@@ -442,6 +470,7 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
values: [databaseTableListLogic, ['views', 'dataWarehouseTables', 'databaseLoading', 'databaseLoadError']],
})),
actions({
+ loadCheckTypes: true,
openEditor: (
check: DataQualityCheckApi | null,
subject: DataQualitySubjectRef | null,
@@ -463,14 +492,26 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
checkTypes: [
[] as DataQualityCheckTypeApi[],
{
- loadCheckTypes: async () =>
- values.subject ? await checksApi.checkTypes(values.subject) : values.checkTypes,
+ loadCheckTypes: async (_, breakpoint) => {
+ let checkTypes: DataQualityCheckTypeApi[]
+ try {
+ checkTypes = values.subject ? await checksApi.checkTypes(values.subject) : []
+ } catch (error) {
+ // A subject change starts a second request. Drop a superseded one so its late
+ // failure cannot report the catalog as unavailable while the newer one runs.
+ breakpoint()
+ throw error
+ }
+ breakpoint()
+ return checkTypes
+ },
},
],
customSqlPreview: [
null as CustomSqlPreview | null,
{
- runCustomSqlPreview: async (_, breakpoint): Promise<CustomSqlPreview> => {
+ runCustomSqlPreview: async (_, breakpoint): Promise<CustomSqlPreview | null> => {
+ const subject = values.subject
const sql = values.checkForm.customSql.trim()
// Force a fresh calculation: the scheduled check run always reads current data, so the
// preview must not serve a cached result that could report a different verdict.
@@ -485,10 +526,16 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
// Cmd+Enter can start a second preview while one is in flight. Drop a superseded
// request so its late failure cannot replace the newer result with a stale error.
breakpoint()
+ if (values.subject !== subject) {
+ return null
+ }
throw error
}
// Same guard on the success path: a superseded result must not overwrite the newer one.
breakpoint()
+ if (values.subject !== subject) {
+ return null
+ }
return {
sql,
columns: response.columns ?? [],
@@ -546,6 +593,7 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
checkTypes: [
[] as DataQualityCheckTypeApi[],
{
+ openEditor: () => [],
setSubject: () => [],
},
],
@@ -608,6 +656,10 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
],
})),
selectors({
+ isMetricSubject: [
+ (s) => [s.subject],
+ (subject: DataQualitySubjectRef | null): boolean => subject?.subjectType === 'metric',
+ ],
checkTypeByName: [
(s) => [s.checkTypes],
(checkTypes: DataQualityCheckTypeApi[]) =>
@@ -646,12 +698,19 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
checkForm: {
defaults: EMPTY_CHECK_FORM,
errors: [
- (s: any) => [s.checkForm, s.checkTypeByName, s.customSqlEditorError, s.customSqlValidationLoading],
+ (s: any) => [
+ s.checkForm,
+ s.checkTypeByName,
+ s.customSqlEditorError,
+ s.customSqlValidationLoading,
+ s.isMetricSubject,
+ ],
(
form: CheckFormValues,
checkTypeByName: Record<string, DataQualityCheckTypeApi>,
customSqlEditorError: string | null,
- customSqlValidationLoading: boolean
+ customSqlValidationLoading: boolean,
+ isMetricSubject: boolean
) => ({
name:
form.name && !CHECK_NAME_PATTERN.test(form.name)
@@ -692,9 +751,11 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
form.checkType === CheckTypeEnumApi.CustomSql
? !form.customSql.trim()
? 'Write the query that selects the failing rows.'
- : customSqlValidationLoading
+ : !isMetricSubject && customSqlValidationLoading
? 'Checking query...'
- : (customSqlEditorError ?? undefined)
+ : !isMetricSubject
+ ? (customSqlEditorError ?? undefined)
+ : undefined
: undefined,
}),
],
@@ -716,7 +777,7 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
? await checksApi.partialUpdate(
values.subject,
editing.id,
- checkEditPayload(form, values.requiresColumn)
+ checkEditPayload(form, values.requiresColumn, editing)
)
: await checksApi.create(values.subject, checkCreatePayload(form, values.requiresColumn))
// Defaults come from the saved row before closing, so a clean form never trips
@@ -785,11 +846,19 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
}
return {
- openEditor: ({ check }) => {
- actions.resetCheckForm(check ? checkToForm(check) : EMPTY_CHECK_FORM)
- if (!values.checkTypes.length) {
- actions.loadCheckTypes()
- }
+ openEditor: ({ check, subject }) => {
+ actions.resetCheckForm(
+ check
+ ? checkToForm(check)
+ : subject?.subjectType === 'metric'
+ ? {
+ ...EMPTY_CHECK_FORM,
+ checkType: CheckTypeEnumApi.CustomSql,
+ customSql: METRIC_CHECK_QUERY_TEMPLATE,
+ }
+ : EMPTY_CHECK_FORM
+ )
+ actions.loadCheckTypes()
ensureWarehouseCatalog()
},
setSubject: () => {
diff --git a/products/data_quality/frontend/dataQualityChecksLogic.test.ts b/products/data_quality/frontend/dataQualityChecksLogic.test.ts
index ea93701d9cb3..0738a8936281 100644
--- a/products/data_quality/frontend/dataQualityChecksLogic.test.ts
+++ b/products/data_quality/frontend/dataQualityChecksLogic.test.ts
@@ -6,6 +6,9 @@ import { expectLogic } from '~/test/keaTestUtils'
import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'
import {
+ dataCatalogMetricsChecksList,
+ dataCatalogMetricsChecksHealthRetrieve,
+ dataCatalogMetricsCheckSuiteRunsList,
warehouseSavedQueriesCheckSuiteRunsCheckRunsList,
warehouseSavedQueriesCheckSuiteRunsList,
warehouseSavedQueriesCheckSuiteRunsRetrieve,
@@ -49,6 +52,9 @@ jest.mock('scenes/data-management/database/databaseTableListLogic', () => ({
}))
jest.mock('./generated/api', () => ({
+ dataCatalogMetricsChecksList: jest.fn(),
+ dataCatalogMetricsChecksHealthRetrieve: jest.fn(),
+ dataCatalogMetricsCheckSuiteRunsList: jest.fn(),
warehouseSavedQueriesChecksList: jest.fn(),
warehouseSavedQueriesChecksCreate: jest.fn(),
warehouseSavedQueriesChecksPartialUpdate: jest.fn(),
@@ -137,6 +143,13 @@ describe('dataQualityChecksLogic', () => {
})
;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })
;(warehouseTablesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })
+ ;(dataCatalogMetricsChecksList as jest.Mock).mockResolvedValue({ results: [] })
+ ;(dataCatalogMetricsChecksHealthRetrieve as jest.Mock).mockResolvedValue({
+ health: 'unknown',
+ checks_total: 0,
+ checks_failing: 0,
+ })
+ ;(dataCatalogMetricsCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })
})
afterEach(() => {
@@ -146,6 +159,11 @@ describe('dataQualityChecksLogic', () => {
})
it.each<[DataQualityChecksLogicProps, jest.Mock, jest.Mock]>([
+ [
+ { subjectType: 'metric', subjectId: 'metric-1' },
+ dataCatalogMetricsChecksList as jest.Mock,
+ warehouseTablesChecksList as jest.Mock,
+ ],
[VIEW_PROPS, warehouseSavedQueriesChecksList as jest.Mock, warehouseTablesChecksList as jest.Mock],
[
{ subjectType: 'table', subjectId: 'table-1' },
@@ -159,6 +177,28 @@ describe('dataQualityChecksLogic', () => {
expect(notExpected).not.toHaveBeenCalled()
})
+ it('keeps a failed metric check load distinct from an empty result and can retry', async () => {
+ ;(dataCatalogMetricsChecksList as jest.Mock).mockRejectedValueOnce(new Error('Service unavailable'))
+ await mountLogic({ subjectType: 'metric', subjectId: 'metric-1' })
+ expect(logic.values.checksLoadError).toBe('Service unavailable')
+ expect(logic.values.checksLoaded).toBe(false)
+ logic.actions.loadChecks()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.checksLoadError).toBeNull()
+ expect(logic.values.checksLoaded).toBe(true)
+ })
+
+ it('keeps the loaded checks when a later refresh fails', async () => {
+ await mountLogic()
+ ;(warehouseSavedQueriesChecksList as jest.Mock).mockRejectedValueOnce(new Error('Service unavailable'))
+ logic.actions.loadChecks()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.checksLoadError).toBe('Service unavailable')
+ expect(logic.values.checksLoaded).toBe(true)
+ expect(logic.values.checks).toHaveLength(1)
+ })
+
it('fails closed without a toast when the subject is forbidden', async () => {
;(warehouseSavedQueriesChecksList as jest.Mock).mockRejectedValue(forbidden())
@@ -414,6 +454,32 @@ describe('dataQualityChecksLogic', () => {
expect(logic.values.isSuiteRunning).toBe(true)
})
+ it('adopts the run the first metric check schedules once the worker writes it', async () => {
+ await mountLogic({ subjectType: 'metric', subjectId: 'metric-1' })
+ expect(logic.values.checks).toEqual([])
+
+ jest.useFakeTimers()
+ logic.actions.upsertCheck(buildCheck())
+ await drainListeners()
+ expect(logic.values.isSuiteRunning).toBe(false)
+
+ ;(dataCatalogMetricsCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [buildSuiteRun()] })
+ await advancePoll(2000)
+
+ expect(logic.values.isSuiteRunning).toBe(true)
+ })
+
+ it('does not look for a scheduled run after a first check on a warehouse subject', async () => {
+ await mountLogic({ subjectType: 'table', subjectId: 'table-1' })
+ const listCallsAfterMount = (warehouseTablesCheckSuiteRunsList as jest.Mock).mock.calls.length
+
+ jest.useFakeTimers()
+ logic.actions.upsertCheck(buildCheck())
+ await advancePoll(2000)
+
+ expect((warehouseTablesCheckSuiteRunsList as jest.Mock).mock.calls.length).toEqual(listCallsAfterMount)
+ })
+
// kea-test-utils waits on real timers, so the polling tests settle listeners by draining
// microtasks instead: every step in the poll chain resolves an already-resolved mock.
async function drainListeners(): Promise<void> {
diff --git a/products/data_quality/frontend/dataQualityChecksLogic.ts b/products/data_quality/frontend/dataQualityChecksLogic.ts
index 329e7aa71dd7..425e1404a71a 100644
--- a/products/data_quality/frontend/dataQualityChecksLogic.ts
+++ b/products/data_quality/frontend/dataQualityChecksLogic.ts
@@ -17,6 +17,8 @@ import { isTerminalSuiteRun, suiteRunOutcome, suiteRunPollListeners, suiteRunSum
const CHECKS_LIMIT = 100
const SUITE_RUNS_LIMIT = 20
+const FIRST_METRIC_CHECK_ADOPTION_ATTEMPTS = 5
+const FIRST_METRIC_CHECK_ADOPTION_DELAY_MS = 2000
export type CheckPendingKind = 'running' | 'deleting' | 'toggling' | 'loadingRuns' | 'loadingSuiteRunRuns'
@@ -57,6 +59,8 @@ export interface dataQualityChecksLogicValues {
activeSuiteRun: DataQualitySuiteRunApi | null
checkRunsByCheckId: Record<string, DataQualityCheckRunApi[]>
checks: DataQualityCheckApi[]
+ checksLoadError: string | null
+ checksLoaded: boolean
checksLoading: boolean
enabledChecksCount: number
health: DataQualitySubjectHealthApi | null
@@ -259,6 +263,21 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([
],
})),
reducers({
+ checksLoadError: [
+ null as string | null,
+ {
+ loadChecks: () => null,
+ loadChecksFailure: (_, { error }) => error,
+ },
+ ],
+ // A refresh runs after every suite run, so a later failure must not take the last good
+ // list off the screen: the panel keeps it and warns instead.
+ checksLoaded: [
+ false,
+ {
+ loadChecksSuccess: () => true,
+ },
+ ],
checks: {
upsertCheck: (state: DataQualityCheckApi[], { check }: { check: DataQualityCheckApi }) =>
state.some((existing) => existing.id === check.id)
@@ -346,7 +365,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([
),
],
}),
- listeners(({ props, values, actions, cache }) => {
+ listeners(({ props, values, actions, cache, selectors }) => {
// Assigned one by one rather than spread: kea-typegen walks this object literal and crashes
// on a spread element, which has no property name.
const poll = suiteRunPollListeners({
@@ -500,13 +519,30 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([
lemonToast.success(suiteRunSummary(suiteRun))
}
},
+ upsertCheck: (_, __, ___, previousState) => {
+ if (props.subjectType !== 'metric' || selectors.checks(previousState, props).length > 0) {
+ return
+ }
+ cache.scheduledRunAttemptsLeft = FIRST_METRIC_CHECK_ADOPTION_ATTEMPTS
+ actions.loadSuiteRuns()
+ },
// A suite started elsewhere, or before this panel opened, is the newest row of the
// history this logic already loads. Reading it from there costs no extra request.
loadSuiteRunsSuccess: ({ suiteRuns }) => {
const [newest] = suiteRuns
if (newest && !isTerminalSuiteRun(newest) && !values.activeSuiteRun) {
+ cache.scheduledRunAttemptsLeft = 0
actions.setActiveSuiteRun(newest)
+ return
+ }
+ if (values.activeSuiteRun || !cache.scheduledRunAttemptsLeft) {
+ return
}
+ cache.scheduledRunAttemptsLeft -= 1
+ cache.disposables.add(() => {
+ const timeoutId = setTimeout(() => actions.loadSuiteRuns(), FIRST_METRIC_CHECK_ADOPTION_DELAY_MS)
+ return () => clearTimeout(timeoutId)
+ }, 'adoptScheduledRun')
},
loadSuiteRunsFailure: ({ errorObject }) => {
if (isForbidden(errorObject)) {
diff --git a/products/data_quality/frontend/dataQualityScheduleLogic.test.ts b/products/data_quality/frontend/dataQualityScheduleLogic.test.ts
new file mode 100644
index 000000000000..a4604fe02fa9
--- /dev/null
+++ b/products/data_quality/frontend/dataQualityScheduleLogic.test.ts
@@ -0,0 +1,108 @@
+import { ApiError } from 'lib/api'
+
+import { silenceKeaLoadersErrors, resumeKeaLoadersErrors } from '~/initKea'
+import { initKeaTests } from '~/test/init'
+import { expectLogic } from '~/test/keaTestUtils'
+
+import { dataQualityScheduleLogic } from './dataQualityScheduleLogic'
+import {
+ dataCatalogMetricsChecksScheduleRetrieve,
+ dataCatalogMetricsChecksSchedulePartialUpdate,
+} from './generated/api'
+
+jest.mock('./generated/api', () => ({
+ dataCatalogMetricsChecksScheduleRetrieve: jest.fn(),
+ dataCatalogMetricsChecksSchedulePartialUpdate: jest.fn(),
+}))
+
+const SCHEDULE = {
+ id: 'schedule-1',
+ enabled: true,
+ interval: '24hour',
+ next_run_at: '2026-09-05T00:00:00Z',
+ last_run_at: null,
+ last_suite_run: null,
+}
+
+describe('dataQualityScheduleLogic', () => {
+ let logic: ReturnType<typeof dataQualityScheduleLogic.build>
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ silenceKeaLoadersErrors()
+ ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock).mockResolvedValue(SCHEDULE)
+ logic = dataQualityScheduleLogic({ metricId: 'metric-1' })
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ resumeKeaLoadersErrors()
+ })
+
+ it('loads the metric schedule and saves only the changed setting', async () => {
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.schedule).toEqual(SCHEDULE)
+ ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockResolvedValue({
+ ...SCHEDULE,
+ interval: '6hour',
+ })
+ logic.actions.updateSchedule({ interval: '6hour' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(dataCatalogMetricsChecksSchedulePartialUpdate).toHaveBeenCalledWith('997', 'metric-1', {
+ interval: '6hour',
+ })
+ expect(logic.values.schedule).toMatchObject({ interval: '6hour', enabled: true })
+ })
+
+ it('keeps the persisted schedule visible after a rejected edit and can retry', async () => {
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(new Error('Could not save'))
+ logic.actions.updateSchedule({ enabled: false })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.schedule?.enabled).toBe(true)
+ expect(logic.values.scheduleError).toBeTruthy()
+ expect(logic.values.scheduleLoading).toBe(false)
+ ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockResolvedValue({ ...SCHEDULE, enabled: false })
+ logic.actions.updateSchedule({ enabled: false })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.schedule?.enabled).toBe(false)
+ expect(logic.values.scheduleError).toBeNull()
+ })
+ it('refetches persisted state when an edit response is lost', async () => {
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(new Error('Connection lost'))
+ ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock).mockResolvedValue({
+ ...SCHEDULE,
+ enabled: false,
+ next_run_at: null,
+ })
+ logic.actions.updateSchedule({ enabled: false })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.schedule?.enabled).toBe(false)
+ expect(logic.values.scheduleError?.uncertain).toBe(true)
+ expect(logic.values.scheduleLoading).toBe(false)
+ })
+
+ it('reports a denied edit without refetching the schedule', async () => {
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock).mockClear()
+ ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(
+ new ApiError('Forbidden', 403, undefined, {
+ detail: 'You do not have permission to perform this action.',
+ })
+ )
+ logic.actions.updateSchedule({ enabled: false })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(dataCatalogMetricsChecksScheduleRetrieve).not.toHaveBeenCalled()
+ expect(logic.values.scheduleError).toEqual({
+ message: 'You do not have permission to perform this action.',
+ uncertain: false,
+ })
+ expect(logic.values.schedule?.enabled).toBe(true)
+ })
+})
diff --git a/products/data_quality/frontend/dataQualityScheduleLogic.ts b/products/data_quality/frontend/dataQualityScheduleLogic.ts
new file mode 100644
index 000000000000..371c1a50ad2d
--- /dev/null
+++ b/products/data_quality/frontend/dataQualityScheduleLogic.ts
@@ -0,0 +1,130 @@
+import { LogicWrapper, MakeLogicType, afterMount, kea, key, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig, ApiError } from 'lib/api'
+
+import { apiErrorDetail } from './checksApi'
+import * as api from './generated/api'
+import type { DataQualityCheckScheduleApi, PatchedDataQualityCheckScheduleUpdateApi } from './generated/api.schemas'
+
+export interface DataQualityScheduleLogicProps {
+ metricId: string
+}
+
+export interface DataQualityScheduleError {
+ message: string
+ uncertain: boolean
+}
+
+const REJECTED_SCHEDULE_MESSAGE = 'Could not save the schedule. Try again.'
+
+function isDefinitiveRejection(error: unknown): boolean {
+ return error instanceof ApiError && error.status !== undefined && error.status < 500
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityScheduleLogicValues {
+ schedule: DataQualityCheckScheduleApi | null
+ scheduleError: DataQualityScheduleError | null
+ scheduleLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityScheduleLogicActions {
+ loadSchedule: () => any
+ loadScheduleFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadScheduleSuccess: (
+ schedule: DataQualityCheckScheduleApi,
+ payload?: any
+ ) => {
+ schedule: DataQualityCheckScheduleApi
+ payload?: any
+ }
+ updateSchedule: (patch: PatchedDataQualityCheckScheduleUpdateApi) => PatchedDataQualityCheckScheduleUpdateApi
+ updateScheduleFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ updateScheduleSuccess: (
+ schedule: DataQualityCheckScheduleApi,
+ payload?: PatchedDataQualityCheckScheduleUpdateApi
+ ) => {
+ schedule: DataQualityCheckScheduleApi
+ payload?: PatchedDataQualityCheckScheduleUpdateApi
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityScheduleLogicMeta {
+ key: string
+}
+
+export type dataQualityScheduleLogicType = MakeLogicType<
+ dataQualityScheduleLogicValues,
+ dataQualityScheduleLogicActions,
+ DataQualityScheduleLogicProps,
+ dataQualityScheduleLogicMeta
+>
+
+export const dataQualityScheduleLogic: LogicWrapper<dataQualityScheduleLogicType> = kea<dataQualityScheduleLogicType>([
+ props({} as DataQualityScheduleLogicProps),
+ key((props) => props.metricId),
+ path((key) => ['products', 'data_quality', 'frontend', 'dataQualityScheduleLogic', key]),
+ loaders(({ props, actions }) => ({
+ schedule: [
+ null as DataQualityCheckScheduleApi | null,
+ {
+ loadSchedule: async () =>
+ api.dataCatalogMetricsChecksScheduleRetrieve(String(ApiConfig.getCurrentTeamId()), props.metricId),
+ updateSchedule: async (patch: PatchedDataQualityCheckScheduleUpdateApi) => {
+ try {
+ return await api.dataCatalogMetricsChecksSchedulePartialUpdate(
+ String(ApiConfig.getCurrentTeamId()),
+ props.metricId,
+ patch
+ )
+ } catch (error) {
+ if (isDefinitiveRejection(error)) {
+ throw error
+ }
+ try {
+ actions.loadScheduleSuccess(
+ await api.dataCatalogMetricsChecksScheduleRetrieve(
+ String(ApiConfig.getCurrentTeamId()),
+ props.metricId
+ )
+ )
+ } catch {
+ // The edit can have committed even when neither response reaches us.
+ }
+ throw error
+ }
+ },
+ },
+ ],
+ })),
+ reducers({
+ scheduleError: [
+ null as DataQualityScheduleError | null,
+ {
+ loadSchedule: () => null,
+ updateSchedule: () => null,
+ loadScheduleFailure: (_, { error }) => ({ message: error, uncertain: true }),
+ updateScheduleFailure: (_, { error, errorObject }) => ({
+ message: apiErrorDetail(errorObject) ?? error ?? REJECTED_SCHEDULE_MESSAGE,
+ uncertain: !isDefinitiveRejection(errorObject),
+ }),
+ },
+ ],
+ }),
+ afterMount(({ actions }) => actions.loadSchedule()),
+])
diff --git a/products/data_quality/frontend/overview/DataQualityOverview.tsx b/products/data_quality/frontend/overview/DataQualityOverview.tsx
index 6accdab52c5a..6a299e5135c7 100644
--- a/products/data_quality/frontend/overview/DataQualityOverview.tsx
+++ b/products/data_quality/frontend/overview/DataQualityOverview.tsx
@@ -371,6 +371,7 @@ function SubjectChecks({ group }: { group: SubjectGroup }): JSX.Element {
<div className="flex flex-col gap-2 py-2">
{check.description && <p className="mb-0 text-secondary">{check.description}</p>}
<CheckRunsTable
+ subjectType={check.subject_type}
runs={checkRunsByCheckId[check.id] ?? []}
loading={runsLoadingByCheckId[check.id]}
/>
diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts
index d8ade838a639..92785682ee2b 100644
--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts
+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts
@@ -283,7 +283,7 @@ describe('dataQualityOverviewLogic', () => {
it('summarises a project that has failing checks', async () => {
await mountLogic()
- expect(logic.values.overviewSummary).toEqual('1 of 3 checks failing, across 1 tables and views.')
+ expect(logic.values.overviewSummary).toEqual('1 of 3 checks failing, across 1 tables, views, and metrics.')
})
it('counts a subject whose only failure is warning-only among the failing subjects', async () => {
@@ -300,7 +300,7 @@ describe('dataQualityOverviewLogic', () => {
expect(logic.values.failingCheckCount).toEqual(1)
expect(logic.values.failingSubjectCount).toEqual(1)
- expect(logic.values.overviewSummary).toEqual('1 of 1 checks failing, across 1 tables and views.')
+ expect(logic.values.overviewSummary).toEqual('1 of 1 checks failing, across 1 tables, views, and metrics.')
})
it.each<[string, (string | null)[], string]>([
@@ -517,6 +517,12 @@ describe('dataQualityOverviewLogic', () => {
it.each<[string, Partial<DataQualityOverviewCheckApi>, string | null]>([
['a view on a DAG node', { subject_type: 'view', subject_node_id: 'node-1' }, '/models/node-1/tests'],
['a view on no DAG', { subject_type: 'view', subject_node_id: null }, null],
+ [
+ 'a metric',
+ { subject_type: 'metric', subject_metric_name: 'weekly_signups' },
+ '/data-catalog/metrics/weekly_signups?tab=tests',
+ ],
+ ['a deleted metric', { subject_type: 'metric', subject_metric_name: null }, null],
[
'a synced table',
{ subject_type: 'table', subject_source_id: 'source-1', subject_schema_id: 'schema-1' },
@@ -530,7 +536,7 @@ describe('dataQualityOverviewLogic', () => {
[
'a metric on its catalog page',
{ subject_type: 'metric', subject_uuid: 'uuid-metric', subject_metric_name: 'signups' },
- '/data-catalog/metrics/signups',
+ '/data-catalog/metrics/signups?tab=tests',
],
[
'a metric whose name did not come through',
diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts
index 0ef86e851ab1..05f6dfa92bfc 100644
--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts
+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts
@@ -77,12 +77,12 @@ function subjectRefOf(check: DataQualityOverviewCheckApi): DataQualitySubjectRef
/** Where the subject's own page lives, or null when it has none and the name renders as text. */
export function subjectDetailUrl(check: DataQualityOverviewCheckApi): string | null {
- if (check.subject_type === 'view') {
- return check.subject_node_id ? urls.nodeDetail(check.subject_node_id, 'tests') : null
- }
if (check.subject_type === 'metric') {
// The catalog addresses a metric by name, so a row that came without one has no route.
- return check.subject_metric_name ? urls.dataCatalogMetric(check.subject_metric_name) : null
+ return check.subject_metric_name ? urls.dataCatalogMetric(check.subject_metric_name, 'tests') : null
+ }
+ if (check.subject_type === 'view') {
+ return check.subject_node_id ? urls.nodeDetail(check.subject_node_id, 'tests') : null
}
if (check.subject_source_id && check.subject_schema_id) {
return urls.dataWarehouseSourceSchema(check.subject_source_id, check.subject_schema_id)
@@ -522,7 +522,7 @@ export const dataQualityOverviewLogic = kea<dataQualityOverviewLogicType>([
return null
}
if (failingCheckCount > 0) {
- return `${failingCheckCount} of ${checks.length} checks failing, across ${failingSubjectCount} tables and views.`
+ return `${failingCheckCount} of ${checks.length} checks failing, across ${failingSubjectCount} tables, views, and metrics.`
}
const passed = checks.filter((check) => check.last_status === 'passed').length
if (passed === checks.length) {