: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
feat(data-quality): add checks management UI for views and tables (#83391)
Thiago Salvatore90817692129f
diff --git a/frontend/package.json b/frontend/package.jsonindex 442c1f3ce0ac..f024e98f3eee 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -99,6 +99,7 @@"@posthog/products-dashboards": "workspace:*","@posthog/products-data-catalog": "workspace:*","@posthog/products-data-modeling": "workspace:*",+ "@posthog/products-data-quality": "workspace:*","@posthog/products-data-tools": "workspace:*","@posthog/products-data-warehouse": "workspace:*","@posthog/products-early-access-features": "workspace:*",diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex e0c37fcaa37f..0780f3e12305 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -297,6 +297,7 @@ export const FEATURE_FLAGS = {DATA_MODELING_MULTI_DAG: 'data-modeling-multi-dag', // owner: #team-data-modelingDATA_MODELING_SUSPEND_FAILING_NODES: 'data-modeling-suspend-failing-nodes', // owner: #team-data-modelingDATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modeling+ DATA_QUALITY_CHECKS: 'data-quality-checks', // owner: #team-data-modelingDATA_WAREHOUSE_COLUMN_STATISTICS: 'data-warehouse-column-statistics', // owner: #team-warehouse-sourcesDATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sourcesDATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2: 'dwh-custom-source-oauth2', // owner: #team-warehouse-sourcesdiff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsxindex 0d1caf7a8e72..7c8a49fc1c80 100644--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx@@ -18,6 +18,7 @@ import { DataModelingNode, DataWarehouseSavedQuery } from '~/types'import { LineageGraph } from 'products/data_modeling/frontend/lineage/LineageGraph'import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'+import { DataQualityChecksPanel } from 'products/data_quality/frontend/DataQualityChecksPanel'import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'import { sqlEditorLogic } from '../sqlEditorLogic'@@ -68,7 +69,16 @@ export function QueryInfo({ tabId, view }: QueryInfoProps): JSX.Element {<div className="overflow-auto" data-attr="sql-editor-sidebar-query-info-pane"><div className="flex flex-col flex-1 gap-4">{targetView ? (- <MaterializationStatusPanel viewId={targetView.id} />+ <>+ <MaterializationStatusPanel viewId={targetView.id} />+ {featureFlags[FEATURE_FLAGS.DATA_QUALITY_CHECKS] && (+ <DataQualityChecksPanel+ subjectType="view"+ subjectId={targetView.id}+ columns={targetView.columns ?? []}+ />+ )}+ </>) : (<div><div className="flex flex-row items-center gap-2">diff --git a/frontend/src/scenes/models/NodeDetailScene.tsx b/frontend/src/scenes/models/NodeDetailScene.tsxindex 10b36e09c616..e781f6ea5f4e 100644--- a/frontend/src/scenes/models/NodeDetailScene.tsx+++ b/frontend/src/scenes/models/NodeDetailScene.tsx@@ -1,6 +1,8 @@import { useValues } from 'kea'import { AccessDenied } from 'lib/components/AccessDenied'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { userHasAccess } from 'lib/utils/accessControlUtils'import { SceneExport } from 'scenes/sceneTypes'@@ -8,6 +10,8 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { DataQualityChecksPanel } from 'products/data_quality/frontend/DataQualityChecksPanel'+import { NodeDetailDetails } from './NodeDetailDetails'import { NodeDetailHeader } from './NodeDetailHeader'import { NodeDetailMaterialization } from './NodeDetailMaterialization'@@ -24,7 +28,8 @@ export const scene: SceneExport<NodeDetailSceneLogicProps> = {}export function NodeDetailScene({ id }: NodeDetailSceneLogicProps): JSX.Element {- const { node, nodeLoading, hasMaterialization } = useValues(nodeDetailSceneLogic({ id }))+ const { node, nodeLoading, hasMaterialization, savedQuery } = useValues(nodeDetailSceneLogic({ id }))+ const { featureFlags } = useValues(featureFlagLogic)if (!userHasAccess(AccessControlResourceType.WarehouseObjects, AccessControlLevel.Viewer)) {return (@@ -39,6 +44,14 @@ export function NodeDetailScene({ id }: NodeDetailSceneLogicProps): JSX.Element{!nodeLoading && node && node.type !== 'table' && <NodeDetailQuery id={id} />}<NodeDetailLineage id={id} />{hasMaterialization && <NodeDetailMaterialization id={id} />}+ {featureFlags[FEATURE_FLAGS.DATA_QUALITY_CHECKS] && node?.saved_query_id && (+ <DataQualityChecksPanel+ subjectType="view"+ subjectId={node.saved_query_id}+ columns={savedQuery?.columns ?? []}+ showGateToggle={!!savedQuery?.is_materialized}+ />+ )}</SceneContent>)}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 37f734621d50..aa113893bfdb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -689,6 +689,9 @@ importers:'@posthog/products-data-modeling':specifier: workspace:*version: link:../products/data_modeling+ '@posthog/products-data-quality':+ specifier: workspace:*+ version: link:../products/data_quality'@posthog/products-data-tools':specifier: workspace:*version: link:../products/data_tools@@ -2967,7 +2970,36 @@ importers:specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])- products/data_quality: {}+ products/data_quality:+ dependencies:+ '@posthog/icons':+ specifier: 'catalog:'+ '@types/react':+ specifier: 18.3.27+ version: 18.3.27+ clsx:+ specifier: '*'+ version: 2.1.1+ kea:+ specifier: 'catalog:'+ version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])+ kea-forms:+ specifier: 'catalog:'+ version: 3.2.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ kea-loaders:+ specifier: 'catalog:'+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ react:+ specifier: 18.3.1+ version: 18.3.1+ devDependencies:+ '@testing-library/jest-dom':+ specifier: ^5.17.0+ version: 5.17.0+ '@testing-library/react':+ specifier: ^14.3.1+ version: 14.3.1(@types/[email protected])([email protected]([email protected]))([email protected])products/data_tools: {}@@ -25530,7 +25562,7 @@ snapshots:'@base-ui/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:- '@babel/runtime': 7.29.2+ '@babel/runtime': 7.29.7'@floating-ui/utils': 0.2.11react: 18.3.1react-dom: 18.3.1([email protected])@@ -25910,7 +25942,7 @@ snapshots:'@daily-co/[email protected]':dependencies:- '@babel/runtime': 7.29.2+ '@babel/runtime': 7.29.7'@sentry/browser': 8.55.2bowser: 2.11.0dequal: 2.0.3@@ -31995,12 +32027,12 @@ snapshots:'@testing-library/[email protected]':dependencies:'@adobe/css-tools': 4.5.0- '@babel/runtime': 7.29.2+ '@babel/runtime': 7.29.7'@types/testing-library__jest-dom': 5.14.5aria-query: 5.3.0chalk: 3.0.0css.escape: 1.5.1- dom-accessibility-api: 0.5.14+ dom-accessibility-api: 0.5.16lodash: 4.18.1redent: 3.0.0@@ -32015,7 +32047,7 @@ snapshots:'@testing-library/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:- '@babel/runtime': 7.29.2+ '@babel/runtime': 7.29.7'@testing-library/dom': 9.3.4'@types/react-dom': 18.3.7(@types/[email protected])react: 18.3.1@@ -43062,7 +43094,7 @@ snapshots:dependencies:- '@babel/runtime': 7.29.2+ '@babel/runtime': 7.29.7react: 18.3.1use-composed-ref: 1.3.0([email protected])use-latest: 1.2.1(@types/[email protected])([email protected])@@ -43189,7 +43221,7 @@ snapshots:dependencies:- '@babel/runtime': 7.29.2+ '@babel/runtime': 7.29.7dependencies:diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.pyindex 3ff9898e48ab..fa90c034f098 100644--- a/products/data_quality/backend/presentation/serializers.py+++ b/products/data_quality/backend/presentation/serializers.py@@ -234,8 +234,8 @@ class DataQualitySuiteRunSerializer(serializers.ModelSerializer):)trigger = serializers.CharField(read_only=True, help_text="manual, materialization, or source_sync.")subject_type = serializers.SerializerMethodField(- help_text="'table' or 'view' when the run targets exactly one subject; null for a "- "check-scoped or multi-subject run."+ help_text="'table' or 'view' when the run targets exactly one subject, including a run of a "+ "single check on that subject; null for a run spanning several subjects.")@extend_schema_field(serializers.CharField(allow_null=True))diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex df98494dba3c..bdba0209e806 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -232,7 +232,15 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse# (relationships target, custom_sql table), so gate on every subject it references too.check = self.get_object()self._require_referenced_subject_access(check.check_type, check.config)- suite_run = api.start_check_suite(team=self.team, user=cast(User, request.user), check_ids=[str(check.id)])+ # The subject is stamped alongside check_ids so the handle stays reachable through this+ # subject's nested suite-run routes, which filter on it. check_ids still decides what runs.+ suite_run = api.start_check_suite(+ team=self.team,+ user=cast(User, request.user),+ subject_type=self.subject_type,+ subject_uuids=[self.subject_uuid],+ check_ids=[str(check.id)],+ )return Response(DataQualitySuiteRunSerializer(suite_run).data)@extend_schema(diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex 9fbf2b47790f..62dbeec0008b 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -346,6 +346,11 @@ class TestDataQualityCheckAPI(APIBaseTest):suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=response.json()["id"])assert suite_run.status == "running"assert response.json()["workflow_id"] == suite_run.workflow_id+ # The handle is only pollable if it carries the subject: the nested routes filter on it.+ polled = self.client.get(f"{self._suite_runs_url()}/{suite_run.id}/")+ assert polled.status_code == status.HTTP_200_OK+ listed = self.client.get(f"{self._suite_runs_url()}/")+ assert str(suite_run.id) in {row["id"] for row in listed.json()["results"]}def test_run_all_records_the_subject_on_the_report(self) -> None:self._create_check()diff --git a/products/data_quality/frontend/CheckFormModal.tsx b/products/data_quality/frontend/CheckFormModal.tsxnew file mode 100644index 000000000000..e81ab9475488--- /dev/null+++ b/products/data_quality/frontend/CheckFormModal.tsx@@ -0,0 +1,253 @@+import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'++import {+ LemonButton,+ LemonInput,+ LemonInputSelect,+ LemonModal,+ LemonSegmentedButton,+ LemonSelect,+ LemonTextArea,+} from '@posthog/lemon-ui'++import { LemonField } from 'lib/lemon-ui/LemonField'+import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'++import { DatabaseSchemaField } from '~/queries/schema/schema-general'++import { checkTypeLabel } from './checksConstants'+import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'+import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi, SubjectTypeEnumApi } from './generated/api.schemas'++const EDIT_LOCK_REASON = "A check's assertion can't be edited. Create a new check instead."++interface CheckFormModalProps extends DataQualityChecksLogicProps {+ columns: DatabaseSchemaField[]+}++export function CheckFormModal({ columns, ...logicProps }: CheckFormModalProps): JSX.Element {+ const logic = dataQualityChecksLogic(logicProps)+ const { checkModalOpen, editingCheck, checkForm, checkTypes, checkTypeByName, isCheckFormSubmitting, serverError } =+ useValues(logic)+ const { closeCheckModal, submitCheckForm, setCheckFormValues } = useActions(logic)++ const isEditing = !!editingCheck+ const editLockReason = isEditing ? EDIT_LOCK_REASON : undefined+ const requiresColumn = !!checkTypeByName[checkForm.checkType]?.requires_column++ return (+ <LemonModal+ isOpen={checkModalOpen}+ onClose={closeCheckModal}+ title={isEditing ? 'Edit check' : 'New check'}+ width={640}+ footer={+ <div className="flex flex-col items-end gap-2 w-full">+ {serverError && <span className="text-danger text-sm">{serverError}</span>}+ <div className="flex gap-2">+ <LemonButton type="secondary" onClick={closeCheckModal}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={submitCheckForm}+ loading={isCheckFormSubmitting}+ data-attr="data-quality-check-save"+ >+ Save check+ </LemonButton>+ </div>+ </div>+ }+ >+ <Form logic={dataQualityChecksLogic} props={logicProps} formKey="checkForm" className="flex flex-col gap-3">+ <LemonField name="checkType" label="Check type">+ <LemonSelect+ disabledReason={editLockReason}+ options={checkTypes.map((checkType) => ({+ value: checkType.check_type as CheckTypeEnumApi,+ label: checkTypeLabel(checkType.check_type),+ labelInMenu: (+ <div className="flex flex-col">+ <span>{checkTypeLabel(checkType.check_type)}</span>+ <span className="text-secondary text-xs">{checkType.description}</span>+ </div>+ ),+ }))}+ onChange={(checkType) =>+ // The config fields belong to the type that was selected, so they can't carry over.+ setCheckFormValues({+ checkType,+ columnName: '',+ acceptedValues: [],+ toSubjectUuid: '',+ toColumn: '',+ rowCountMin: null,+ rowCountMax: null,+ maxAgeMinutes: null,+ customSql: '',+ })+ }+ />+ </LemonField>++ {requiresColumn && (+ <LemonField name="columnName" label="Column">+ <LemonSelect+ disabledReason={editLockReason}+ options={columns.map((column) => ({ value: column.name, label: column.name }))}+ />+ </LemonField>+ )}++ <CheckConfigFields+ checkType={checkForm.checkType}+ disabledReason={editLockReason}+ logicProps={logicProps}+ />++ <LemonField name="name" label="Name" showOptional>+ <LemonInput placeholder="orders_customer_id_not_null" />+ </LemonField>++ <LemonField name="description" label="Description" showOptional>+ <LemonTextArea placeholder="Why this check exists and what a failure means" minRows={2} />+ </LemonField>++ <LemonField name="severity" label="Severity">+ <LemonSegmentedButton+ options={[+ { value: DataQualityCheckSeverityEnumApi.Error, label: 'Error' },+ { value: DataQualityCheckSeverityEnumApi.Warn, label: 'Warning' },+ ]}+ />+ </LemonField>++ <LemonField name="tags" label="Tags" showOptional>+ <LemonInputSelect mode="multiple" allowCustomValues options={[]} placeholder="Add a tag" />+ </LemonField>+ </Form>+ </LemonModal>+ )+}++function CheckConfigFields({+ checkType,+ disabledReason,+ logicProps,+}: {+ checkType: CheckTypeEnumApi+ disabledReason?: string+ logicProps: DataQualityChecksLogicProps+}): JSX.Element | null {+ switch (checkType) {+ case CheckTypeEnumApi.AcceptedValues:+ return (+ <LemonField name="acceptedValues" label="Allowed values">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ options={[]}+ disabled={!!disabledReason}+ placeholder="Add a value"+ />+ </LemonField>+ )+ case CheckTypeEnumApi.Relationships:+ return <RelationshipFields disabledReason={disabledReason} logicProps={logicProps} />+ case CheckTypeEnumApi.RowCount:+ return (+ <div className="flex gap-3">+ <LemonField name="rowCountMin" label="Minimum rows" showOptional className="flex-1">+ <LemonInput type="number" min={0} disabled={!!disabledReason} />+ </LemonField>+ <LemonField name="rowCountMax" label="Maximum rows" showOptional className="flex-1">+ <LemonInput type="number" min={0} disabled={!!disabledReason} />+ </LemonField>+ </div>+ )+ case CheckTypeEnumApi.Freshness:+ return (+ <LemonField+ name="maxAgeMinutes"+ label="Maximum age in minutes"+ help="The check fails when the newest value in the column is older than this."+ >+ <LemonInput type="number" min={1} disabled={!!disabledReason} />+ </LemonField>+ )+ case CheckTypeEnumApi.CustomSql:+ return (+ <LemonField+ name="customSql"+ label="Query"+ help="Return one row per failure. The check passes when the query returns nothing."+ >+ {({ value, onChange }) => (+ <CodeEditorResizeable+ language="hogQL"+ value={value ?? ''}+ onChange={(query) => onChange(query ?? '')}+ minHeight="8rem"+ maxHeight="40vh"+ options={{ readOnly: !!disabledReason }}+ />+ )}+ </LemonField>+ )+ default:+ return null+ }+}++function RelationshipFields({+ disabledReason,+ logicProps,+}: {+ disabledReason?: string+ logicProps: DataQualityChecksLogicProps+}): JSX.Element {+ const { checkForm } = useValues(dataQualityChecksLogic(logicProps))+ const { setCheckFormValues } = useActions(dataQualityChecksLogic(logicProps))+ const { dataWarehouseTables, views } = useValues(databaseTableListLogic)++ // Only warehouse subjects carry the uuid a relationships check references; PostHog-native and+ // system tables have no check subject to point at.+ const subjects = [+ ...views.map((view) => ({ id: view.id, name: view.name, type: SubjectTypeEnumApi.View, fields: view.fields })),+ ...dataWarehouseTables.map((table) => ({+ id: table.id,+ name: table.name,+ type: SubjectTypeEnumApi.Table,+ fields: table.fields,+ })),+ ].filter((subject) => !!subject.id)++ const selected = subjects.find((subject) => subject.id === checkForm.toSubjectUuid)++ return (+ <>+ <LemonField name="toSubjectUuid" label="References table or view">+ <LemonSelect+ disabledReason={disabledReason}+ options={subjects.map((subject) => ({ value: subject.id, label: subject.name }))}+ onChange={(toSubjectUuid) =>+ setCheckFormValues({+ toSubjectUuid,+ toSubjectType: subjects.find((subject) => subject.id === toSubjectUuid)?.type,+ toColumn: '',+ })+ }+ />+ </LemonField>+ <LemonField name="toColumn" label="References column">+ <LemonSelect+ disabledReason={disabledReason ?? (selected ? undefined : 'Pick a table or view first')}+ options={Object.keys(selected?.fields ?? {}).map((field) => ({ value: field, label: field }))}+ />+ </LemonField>+ </>+ )+}diff --git a/products/data_quality/frontend/CheckRunsTable.tsx b/products/data_quality/frontend/CheckRunsTable.tsxnew file mode 100644index 000000000000..4285676d6ef3--- /dev/null+++ b/products/data_quality/frontend/CheckRunsTable.tsx@@ -0,0 +1,87 @@+import { LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { TZLabel } from 'lib/components/TZLabel'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { urls } from 'scenes/urls'++import { CHECK_STATUS_TAG_TYPES } from './checksConstants'+import type { DataQualityCheckRunApi } from './generated/api.schemas'++interface CheckRunsTableProps {+ runs: DataQualityCheckRunApi[]+ loading?: boolean+}++export function CheckRunsTable({ runs, loading }: CheckRunsTableProps): JSX.Element {+ return (+ <LemonTable+ size="small"+ dataSource={runs}+ loading={loading}+ nouns={['run', 'runs']}+ emptyState="No runs yet"+ expandable={{+ expandedRowRender: (run) => <CheckRunQuery run={run} />,+ }}+ columns={[+ {+ title: 'Status',+ key: 'status',+ render: (_, run) => (+ <LemonTag type={CHECK_STATUS_TAG_TYPES[run.status] ?? 'default'}>{run.status}</LemonTag>+ ),+ },+ {+ title: 'Started',+ key: 'started_at',+ render: (_, run) => (run.started_at ? <TZLabel time={run.started_at} /> : '-'),+ },+ {+ title: 'Duration',+ key: 'duration_ms',+ render: (_, run) =>+ run.duration_ms === null ? '-' : humanFriendlyDuration(run.duration_ms / 1000, { maxUnits: 2 }),+ },+ {+ title: 'Observed value',+ key: 'observed_value',+ render: (_, run) => (run.observed_value === null ? '-' : humanFriendlyNumber(run.observed_value)),+ },+ {+ title: 'Failed rows',+ key: 'failed_row_count',+ render: (_, run) =>+ run.failed_row_count === null ? '-' : humanFriendlyNumber(run.failed_row_count),+ },+ {+ title: 'Error',+ key: 'error',+ render: (_, run) =>+ run.error ? (+ <Tooltip title={run.error}>+ <span className="text-danger truncate max-w-xs inline-block">{run.error}</span>+ </Tooltip>+ ) : (+ '-'+ ),+ },+ ]}+ />+ )+}++function CheckRunQuery({ run }: { run: DataQualityCheckRunApi }): JSX.Element {+ if (!run.compiled_query) {+ return <span className="text-secondary text-xs">Query no longer retained</span>+ }+ return (+ <div className="flex flex-col gap-2 py-2">+ <CodeSnippet language={Language.SQL} compact>+ {run.compiled_query}+ </CodeSnippet>+ <Link to={urls.sqlEditor({ query: run.compiled_query })}>Open in SQL editor</Link>+ </div>+ )+}diff --git a/products/data_quality/frontend/ChecksTable.tsx b/products/data_quality/frontend/ChecksTable.tsxnew file mode 100644index 000000000000..585136f27054--- /dev/null+++ b/products/data_quality/frontend/ChecksTable.tsx@@ -0,0 +1,157 @@+import { useActions, useValues } from 'kea'++import { IconEllipsis } from '@posthog/icons'+import { LemonButton, LemonDialog, LemonMenu, LemonSwitch, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'++import { CheckRunsTable } from './CheckRunsTable'+import { CHECK_STATUS_TAG_TYPES, SEVERITY_TAG_TYPES, checkDisplayName, checkTypeLabel } from './checksConstants'+import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'+import type { DataQualityCheckApi } from './generated/api.schemas'++export function ChecksTable(props: DataQualityChecksLogicProps): JSX.Element {+ const logic = dataQualityChecksLogic(props)+ const { sortedChecks, checksLoading, pendingCheckActions, checkRunsByCheckId } = useValues(logic)+ const { openCheckModal, deleteCheck, toggleCheckEnabled, runCheck, loadCheckRuns } = useActions(logic)++ const confirmDelete = (check: DataQualityCheckApi): void => {+ LemonDialog.open({+ title: 'Delete this check?',+ description: 'Past run history is kept.',+ primaryButton: {+ children: 'Delete',+ status: 'danger',+ onClick: () => deleteCheck(check.id),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ return (+ <LemonTable+ rowKey="id"+ dataSource={sortedChecks}+ loading={checksLoading}+ nouns={['check', 'checks']}+ expandable={{+ onRowExpand: (check) => loadCheckRuns(check.id),+ expandedRowRender: (check) => (+ <div className="flex flex-col gap-2 py-2">+ {check.description && <p className="mb-0 text-secondary">{check.description}</p>}+ <CheckRunsTable+ runs={checkRunsByCheckId[check.id] ?? []}+ loading={pendingCheckActions.loadingRuns[check.id]}+ />+ </div>+ ),+ }}+ columns={[+ {+ title: 'Name',+ key: 'name',+ render: (_, check) => (+ <div className="flex items-center gap-2">+ <Tooltip title={check.description || undefined}>+ <span className="font-semibold">{checkDisplayName(check)}</span>+ </Tooltip>+ {check.created_source === 'ai_generated' && (+ <Tooltip title={aiTooltip(check)}>+ <LemonTag type="completion">AI</LemonTag>+ </Tooltip>+ )}+ {check.owner && <span className="text-secondary text-xs">{check.owner}</span>}+ </div>+ ),+ },+ {+ title: 'Type',+ key: 'check_type',+ render: (_, check) => checkTypeLabel(check.check_type),+ },+ {+ title: 'Column',+ key: 'column_name',+ render: (_, check) => check.column_name || '-',+ },+ {+ title: 'Severity',+ key: 'severity',+ render: (_, check) => (+ <LemonTag type={SEVERITY_TAG_TYPES[check.severity ?? 'error'] ?? 'default'}>+ {check.severity ?? 'error'}+ </LemonTag>+ ),+ },+ {+ title: 'Enabled',+ key: 'enabled',+ render: (_, check) => (+ <LemonSwitch+ checked={check.enabled !== false}+ onChange={(enabled) => toggleCheckEnabled(check.id, enabled)}+ disabled={!!pendingCheckActions.toggling[check.id]}+ aria-label={`Enable check ${checkDisplayName(check)}`}+ />+ ),+ },+ {+ title: 'Last status',+ key: 'last_status',+ render: (_, check) =>+ check.last_status ? (+ <LemonTag type={CHECK_STATUS_TAG_TYPES[check.last_status] ?? 'default'}>+ {check.last_status}+ </LemonTag>+ ) : (+ <LemonTag type="muted">Not run yet</LemonTag>+ ),+ },+ {+ title: 'Last run',+ key: 'last_run_at',+ render: (_, check) => (check.last_run_at ? <TZLabel time={check.last_run_at} /> : '-'),+ },+ {+ key: 'actions',+ width: 0,+ render: (_, check) => (+ <LemonMenu+ items={[+ {+ label: 'Run now',+ onClick: () => runCheck(check.id),+ disabledReason: pendingCheckActions.running[check.id]+ ? 'This check is already starting'+ : undefined,+ },+ { label: 'Edit', onClick: () => openCheckModal(check) },+ {+ label: 'Delete',+ status: 'danger',+ onClick: () => confirmDelete(check),+ disabledReason: pendingCheckActions.deleting[check.id]+ ? 'This check is being deleted'+ : undefined,+ },+ ]}+ >+ <LemonButton+ size="small"+ icon={<IconEllipsis />}+ data-attr="data-quality-check-actions"+ aria-label={`Actions for check ${checkDisplayName(check)}`}+ />+ </LemonMenu>+ ),+ },+ ]}+ />+ )+}++function aiTooltip(check: DataQualityCheckApi): string {+ const confidence =+ check.confidence !== null && check.confidence !== undefined ? `${check.confidence} confidence` : ''+ return [confidence, check.reasoning].filter(Boolean).join('. ') || 'Written by an agent'+}diff --git a/products/data_quality/frontend/DataQualityChecksPanel.tsx b/products/data_quality/frontend/DataQualityChecksPanel.tsxnew file mode 100644index 000000000000..6c476c1e73f1--- /dev/null+++ b/products/data_quality/frontend/DataQualityChecksPanel.tsx@@ -0,0 +1,164 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonSwitch, LemonTag, Spinner } from '@posthog/lemon-ui'++import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'++import { DatabaseSchemaField } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { CheckFormModal } from './CheckFormModal'+import { HEALTH_LABELS, HEALTH_TAG_TYPES } from './checksConstants'+import { ChecksTable } from './ChecksTable'+import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'+import { dataQualityGateLogic } from './dataQualityGateLogic'+import { SuiteRunsHistory } from './SuiteRunsHistory'++interface DataQualityChecksPanelProps extends DataQualityChecksLogicProps {+ columns: DatabaseSchemaField[]+ /** Materialized views only: the gate is a project-wide setting and only bites on materialization. */+ showGateToggle?: boolean+}++export function DataQualityChecksPanel({+ columns,+ showGateToggle,+ ...logicProps+}: DataQualityChecksPanelProps): JSX.Element | null {+ const logic = dataQualityChecksLogic(logicProps)+ const {+ health,+ checks,+ checksLoading,+ enabledChecksCount,+ isSuiteRunning,+ pollTimedOut,+ runAllInFlight,+ accessDenied,+ } = useValues(logic)+ const { openCheckModal, runAll, loadChecks, loadHealth } = useActions(logic)++ if (accessDenied) {+ return null+ }++ return (+ <div className="flex flex-col gap-2 mt-4">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <div className="flex items-center gap-2">+ <h3 className="mb-0 text-lg font-semibold">Data quality</h3>+ {health && (+ <LemonTag type={HEALTH_TAG_TYPES[health.health] ?? 'default'}>+ {HEALTH_LABELS[health.health] ?? health.health}+ </LemonTag>+ )}+ {health && health.checks_total > 0 && (+ <span className="text-secondary text-sm">+ {health.checks_failing} of {health.checks_total} failing+ </span>+ )}+ {health?.health === 'unknown' && (+ <span className="text-secondary text-sm">Run checks to see health</span>+ )}+ </div>+ <div className="flex items-center gap-2">+ <LemonButton+ type="secondary"+ size="small"+ onClick={runAll}+ loading={runAllInFlight || isSuiteRunning}+ disabledReason={+ checksLoading+ ? 'Loading checks'+ : enabledChecksCount === 0+ ? 'No enabled checks to run'+ : undefined+ }+ data-attr="data-quality-run-all"+ >+ Run all checks+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={() => openCheckModal()}+ data-attr="data-quality-new-check"+ >+ New check+ </LemonButton>+ </div>+ </div>++ {isSuiteRunning && (+ <LemonBanner type="info" icon={<Spinner />}>+ Running checks...+ </LemonBanner>+ )}+ {pollTimedOut && (+ <LemonBanner+ type="warning"+ action={{+ children: 'Refresh',+ onClick: () => {+ loadChecks()+ loadHealth()+ },+ }}+ >+ Checks are still running. Check back in a few minutes.+ </LemonBanner>+ )}++ {!checksLoading && checks.length === 0 ? (+ <NoChecksYet onAddCheck={() => openCheckModal()} />+ ) : (+ <ChecksTable {...logicProps} />+ )}++ <SuiteRunsHistory {...logicProps} />++ {showGateToggle && <GateToggle />}++ <CheckFormModal {...logicProps} columns={columns} />+ </div>+ )+}++function NoChecksYet({ onAddCheck }: { onAddCheck: () => void }): 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.+ </p>+ <LemonButton type="primary" size="small" onClick={onAddCheck} data-attr="data-quality-first-check">+ Add your first check+ </LemonButton>+ </div>+ )+}++function GateToggle(): JSX.Element | null {+ const { gateConfig, gateReadable, gateSaving } = useValues(dataQualityGateLogic)+ const { setGateEnabled } = useActions(dataQualityGateLogic)++ if (!gateReadable || !gateConfig) {+ return null+ }++ return (+ <LemonSwitch+ bordered+ checked={gateConfig.gate_materialization_on_checks}+ onChange={setGateEnabled}+ loading={gateSaving}+ disabledReason={getAccessControlDisabledReason(+ AccessControlResourceType.WarehouseObjects,+ AccessControlLevel.Editor+ )}+ label="Block materialization on failing checks"+ tooltip="Applies to all materialized views in this project. When an error-severity check fails, the previous version keeps serving."+ data-attr="data-quality-gate-toggle"+ />+ )+}diff --git a/products/data_quality/frontend/SuiteRunsHistory.tsx b/products/data_quality/frontend/SuiteRunsHistory.tsxnew file mode 100644index 000000000000..ce2fb2da56a9--- /dev/null+++ b/products/data_quality/frontend/SuiteRunsHistory.tsx@@ -0,0 +1,85 @@+import { useActions, useValues } from 'kea'++import { LemonCollapse, LemonTable, LemonTag } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { humanFriendlyDuration } from 'lib/utils/durations'++import { CheckRunsTable } from './CheckRunsTable'+import { SUITE_RUN_STATUS_TAG_TYPES } from './checksConstants'+import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'+import type { DataQualitySuiteRunApi } from './generated/api.schemas'++export function SuiteRunsHistory(props: DataQualityChecksLogicProps): JSX.Element {+ const logic = dataQualityChecksLogic(props)+ const { suiteRuns, suiteRunsLoading, suiteRunCheckRunsBySuiteRunId, pendingCheckActions } = useValues(logic)+ const { loadSuiteRuns, loadSuiteRunCheckRuns } = useActions(logic)++ return (+ <LemonCollapse+ onChange={(key) => key && loadSuiteRuns()}+ panels={[+ {+ key: 'runs',+ header: 'Run history',+ content: (+ <LemonTable+ size="small"+ dataSource={suiteRuns}+ rowKey="id"+ loading={suiteRunsLoading}+ nouns={['run', 'runs']}+ emptyState="No runs yet"+ expandable={{+ onRowExpand: (suiteRun) => loadSuiteRunCheckRuns(suiteRun.id),+ expandedRowRender: (suiteRun) => (+ <CheckRunsTable+ runs={suiteRunCheckRunsBySuiteRunId[suiteRun.id] ?? []}+ loading={pendingCheckActions.loadingSuiteRunRuns[suiteRun.id]}+ />+ ),+ }}+ columns={[+ {+ title: 'Status',+ key: 'status',+ render: (_, suiteRun) => (+ <LemonTag type={SUITE_RUN_STATUS_TAG_TYPES[suiteRun.status] ?? 'default'}>+ {suiteRun.status === 'empty' ? 'No checks matched' : suiteRun.status}+ </LemonTag>+ ),+ },+ { title: 'Trigger', key: 'trigger', render: (_, suiteRun) => suiteRun.trigger },+ {+ title: 'Started',+ key: 'started_at',+ render: (_, suiteRun) =>+ suiteRun.started_at ? <TZLabel time={suiteRun.started_at} /> : '-',+ },+ {+ title: 'Duration',+ key: 'duration',+ render: (_, suiteRun) => suiteRunDuration(suiteRun),+ },+ {+ title: 'Outcome',+ key: 'outcome',+ render: (_, suiteRun) =>+ `${suiteRun.checks_passed} passed, ${suiteRun.checks_failed} failed, ${suiteRun.checks_errored} errored, ${suiteRun.checks_skipped} skipped`,+ },+ ]}+ />+ ),+ },+ ]}+ />+ )+}++function suiteRunDuration(suiteRun: DataQualitySuiteRunApi): string {+ if (!suiteRun.started_at || !suiteRun.finished_at) {+ return '-'+ }+ const seconds = (new Date(suiteRun.finished_at).getTime() - new Date(suiteRun.started_at).getTime()) / 1000+ return humanFriendlyDuration(seconds, { maxUnits: 2 })+}diff --git a/products/data_quality/frontend/checksApi.ts b/products/data_quality/frontend/checksApi.tsnew file mode 100644index 000000000000..f34dae21ffb1--- /dev/null+++ b/products/data_quality/frontend/checksApi.ts@@ -0,0 +1,117 @@+import { ApiConfig } from 'lib/api'++import {+ warehouseSavedQueriesCheckSuiteRunsCheckRunsList,+ warehouseSavedQueriesCheckSuiteRunsList,+ warehouseSavedQueriesCheckSuiteRunsRetrieve,+ warehouseSavedQueriesChecksCheckTypesList,+ warehouseSavedQueriesChecksCreate,+ warehouseSavedQueriesChecksDestroy,+ warehouseSavedQueriesChecksHealthRetrieve,+ warehouseSavedQueriesChecksList,+ warehouseSavedQueriesChecksPartialUpdate,+ warehouseSavedQueriesChecksRunAllCreate,+ warehouseSavedQueriesChecksRunCreate,+ warehouseSavedQueriesChecksRunsList,+ warehouseTablesCheckSuiteRunsCheckRunsList,+ warehouseTablesCheckSuiteRunsList,+ warehouseTablesCheckSuiteRunsRetrieve,+ warehouseTablesChecksCheckTypesList,+ warehouseTablesChecksCreate,+ warehouseTablesChecksDestroy,+ warehouseTablesChecksHealthRetrieve,+ warehouseTablesChecksList,+ warehouseTablesChecksPartialUpdate,+ warehouseTablesChecksRunAllCreate,+ warehouseTablesChecksRunCreate,+ warehouseTablesChecksRunsList,+} from './generated/api'+import type {+ DataQualityCheckApi,+ DataQualityCheckRunApi,+ DataQualityCheckTypeApi,+ DataQualitySubjectHealthApi,+ DataQualitySuiteRunApi,+ PaginatedDataQualityCheckListApi,+ PaginatedDataQualitySuiteRunListApi,+} from './generated/api.schemas'++export type DataQualitySubjectType = 'table' | 'view'++export interface DataQualitySubjectRef {+ subjectType: DataQualitySubjectType+ subjectId: string+}++type CreateBody = Parameters<typeof warehouseSavedQueriesChecksCreate>[2]+type PatchBody = Parameters<typeof warehouseSavedQueriesChecksPartialUpdate>[3]++function projectId(): string {+ return String(ApiConfig.getCurrentTeamId())+}++function isView({ subjectType }: DataQualitySubjectRef): boolean {+ return subjectType === 'view'+}++export const checksApi = {+ list: (ref: DataQualitySubjectRef, limit: number): Promise<PaginatedDataQualityCheckListApi> =>+ isView(ref)+ ? warehouseSavedQueriesChecksList(projectId(), ref.subjectId, { limit })+ : warehouseTablesChecksList(projectId(), ref.subjectId, { limit }),++ create: (ref: DataQualitySubjectRef, body: CreateBody): Promise<DataQualityCheckApi> =>+ isView(ref)+ ? warehouseSavedQueriesChecksCreate(projectId(), ref.subjectId, body)+ : warehouseTablesChecksCreate(projectId(), ref.subjectId, body),++ partialUpdate: (ref: DataQualitySubjectRef, id: string, body: PatchBody): Promise<DataQualityCheckApi> =>+ isView(ref)+ ? warehouseSavedQueriesChecksPartialUpdate(projectId(), ref.subjectId, id, body)+ : warehouseTablesChecksPartialUpdate(projectId(), ref.subjectId, id, body),++ destroy: (ref: DataQualitySubjectRef, id: string): Promise<void> =>+ isView(ref)+ ? warehouseSavedQueriesChecksDestroy(projectId(), ref.subjectId, id)+ : warehouseTablesChecksDestroy(projectId(), ref.subjectId, id),++ run: (ref: DataQualitySubjectRef, id: string): Promise<DataQualitySuiteRunApi> =>+ isView(ref)+ ? warehouseSavedQueriesChecksRunCreate(projectId(), ref.subjectId, id)+ : warehouseTablesChecksRunCreate(projectId(), ref.subjectId, id),++ runAll: (ref: DataQualitySubjectRef): Promise<DataQualitySuiteRunApi> =>+ isView(ref)+ ? warehouseSavedQueriesChecksRunAllCreate(projectId(), ref.subjectId)+ : warehouseTablesChecksRunAllCreate(projectId(), ref.subjectId),++ runs: (ref: DataQualitySubjectRef, id: string): Promise<DataQualityCheckRunApi[]> =>+ isView(ref)+ ? warehouseSavedQueriesChecksRunsList(projectId(), ref.subjectId, id)+ : warehouseTablesChecksRunsList(projectId(), ref.subjectId, id),++ checkTypes: (ref: DataQualitySubjectRef): Promise<DataQualityCheckTypeApi[]> =>+ isView(ref)+ ? warehouseSavedQueriesChecksCheckTypesList(projectId(), ref.subjectId)+ : warehouseTablesChecksCheckTypesList(projectId(), ref.subjectId),++ health: (ref: DataQualitySubjectRef): Promise<DataQualitySubjectHealthApi> =>+ isView(ref)+ ? warehouseSavedQueriesChecksHealthRetrieve(projectId(), ref.subjectId)+ : warehouseTablesChecksHealthRetrieve(projectId(), ref.subjectId),++ suiteRuns: (ref: DataQualitySubjectRef, limit: number): Promise<PaginatedDataQualitySuiteRunListApi> =>+ isView(ref)+ ? warehouseSavedQueriesCheckSuiteRunsList(projectId(), ref.subjectId, { limit })+ : warehouseTablesCheckSuiteRunsList(projectId(), ref.subjectId, { limit }),++ suiteRunRetrieve: (ref: DataQualitySubjectRef, id: string): Promise<DataQualitySuiteRunApi> =>+ isView(ref)+ ? warehouseSavedQueriesCheckSuiteRunsRetrieve(projectId(), ref.subjectId, id)+ : warehouseTablesCheckSuiteRunsRetrieve(projectId(), ref.subjectId, id),++ suiteRunCheckRuns: (ref: DataQualitySubjectRef, id: string): Promise<DataQualityCheckRunApi[]> =>+ isView(ref)+ ? warehouseSavedQueriesCheckSuiteRunsCheckRunsList(projectId(), ref.subjectId, id)+ : warehouseTablesCheckSuiteRunsCheckRunsList(projectId(), ref.subjectId, id),+}diff --git a/products/data_quality/frontend/checksConstants.ts b/products/data_quality/frontend/checksConstants.tsnew file mode 100644index 000000000000..49240158b0db--- /dev/null+++ b/products/data_quality/frontend/checksConstants.ts@@ -0,0 +1,62 @@+import { LemonTagType } from 'lib/lemon-ui/LemonTag'++import { CheckTypeEnumApi } from './generated/api.schemas'+import type { DataQualityCheckApi } from './generated/api.schemas'++export const CHECK_TYPE_LABELS: Record<string, string> = {+ [CheckTypeEnumApi.NotNull]: 'Not null',+ [CheckTypeEnumApi.Unique]: 'Unique',+ [CheckTypeEnumApi.AcceptedValues]: 'Accepted values',+ [CheckTypeEnumApi.Relationships]: 'Relationship',+ [CheckTypeEnumApi.RowCount]: 'Row count',+ [CheckTypeEnumApi.Freshness]: 'Freshness',+ [CheckTypeEnumApi.CustomSql]: 'Custom SQL',+}++export const CHECK_STATUS_TAG_TYPES: Record<string, LemonTagType> = {+ passed: 'success',+ failed: 'danger',+ errored: 'warning',+ skipped: 'muted',+}++export const SUITE_RUN_STATUS_TAG_TYPES: Record<string, LemonTagType> = {+ running: 'primary',+ completed: 'success',+ failed: 'danger',+ empty: 'muted',+}++export const HEALTH_TAG_TYPES: Record<string, LemonTagType> = {+ healthy: 'success',+ warn: 'warning',+ failing: 'danger',+ erroring: 'warning',+ unknown: 'muted',+}++export const HEALTH_LABELS: Record<string, string> = {+ healthy: 'Healthy',+ warn: 'Warning',+ failing: 'Failing',+ erroring: 'Erroring',+ unknown: 'Not run yet',+}++export const SEVERITY_TAG_TYPES: Record<string, LemonTagType> = {+ error: 'danger',+ warn: 'warning',+}++export function checkTypeLabel(checkType: string): string {+ return CHECK_TYPE_LABELS[checkType] ?? checkType+}++/** The check's own name when it has one, otherwise a description of the assertion it makes. */+export function checkDisplayName(check: DataQualityCheckApi): string {+ if (check.name) {+ return check.name+ }+ const label = checkTypeLabel(check.check_type)+ return check.column_name ? `${label} on ${check.column_name}` : label+}diff --git a/products/data_quality/frontend/dataQualityChecksLogic.test.ts b/products/data_quality/frontend/dataQualityChecksLogic.test.tsnew file mode 100644index 000000000000..e51ed4121c16--- /dev/null+++ b/products/data_quality/frontend/dataQualityChecksLogic.test.ts@@ -0,0 +1,584 @@+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'+import {+ warehouseSavedQueriesCheckSuiteRunsCheckRunsList,+ warehouseSavedQueriesCheckSuiteRunsList,+ warehouseSavedQueriesCheckSuiteRunsRetrieve,+ warehouseSavedQueriesChecksCheckTypesList,+ warehouseSavedQueriesChecksCreate,+ warehouseSavedQueriesChecksDestroy,+ warehouseSavedQueriesChecksHealthRetrieve,+ warehouseSavedQueriesChecksList,+ warehouseSavedQueriesChecksPartialUpdate,+ warehouseSavedQueriesChecksRunAllCreate,+ warehouseSavedQueriesChecksRunCreate,+ warehouseTablesCheckSuiteRunsList,+ warehouseTablesChecksHealthRetrieve,+ warehouseTablesChecksList,+} from './generated/api'+import type { DataQualityCheckApi, DataQualitySuiteRunApi } from './generated/api.schemas'+import { CheckTypeEnumApi } from './generated/api.schemas'++jest.mock('lib/api', () => {+ class ApiError extends Error {+ status?: number+ detail: string | null+ constructor(message?: string, status?: number, _headers?: unknown, data?: { detail?: string }) {+ super(message)+ this.status = status+ this.detail = data?.detail ?? null+ }+ }+ return {+ __esModule: true,+ default: {},+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },+ ApiError,+ }+})++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },+}))++jest.mock('scenes/data-management/database/databaseTableListLogic', () => ({+ databaseTableListLogic: { loadDatabase: jest.fn(() => ({ type: 'load database (mock)' })) },+}))++jest.mock('./generated/api', () => ({+ warehouseSavedQueriesChecksList: jest.fn(),+ warehouseSavedQueriesChecksCreate: jest.fn(),+ warehouseSavedQueriesChecksPartialUpdate: jest.fn(),+ warehouseSavedQueriesChecksDestroy: jest.fn(),+ warehouseSavedQueriesChecksRunCreate: jest.fn(),+ warehouseSavedQueriesChecksRunAllCreate: jest.fn(),+ warehouseSavedQueriesChecksRunsList: jest.fn(),+ warehouseSavedQueriesChecksCheckTypesList: jest.fn(),+ warehouseSavedQueriesChecksHealthRetrieve: jest.fn(),+ warehouseSavedQueriesCheckSuiteRunsList: jest.fn(),+ warehouseSavedQueriesCheckSuiteRunsRetrieve: jest.fn(),+ warehouseSavedQueriesCheckSuiteRunsCheckRunsList: jest.fn(),+ warehouseTablesChecksList: jest.fn(),+ warehouseTablesChecksCreate: jest.fn(),+ warehouseTablesChecksPartialUpdate: jest.fn(),+ warehouseTablesChecksDestroy: jest.fn(),+ warehouseTablesChecksRunCreate: jest.fn(),+ warehouseTablesChecksRunAllCreate: jest.fn(),+ warehouseTablesChecksRunsList: jest.fn(),+ warehouseTablesChecksCheckTypesList: jest.fn(),+ warehouseTablesChecksHealthRetrieve: jest.fn(),+ warehouseTablesCheckSuiteRunsList: jest.fn(),+ warehouseTablesCheckSuiteRunsRetrieve: jest.fn(),+ warehouseTablesCheckSuiteRunsCheckRunsList: jest.fn(),+}))++const VIEW_PROPS: DataQualityChecksLogicProps = { subjectType: 'view', subjectId: 'view-1' }++const CHECK_TYPE_CATALOG = [+ { check_type: 'not_null', description: '', requires_column: true, config_schema: {} },+ { check_type: 'unique', description: '', requires_column: true, config_schema: {} },+ { check_type: 'accepted_values', description: '', requires_column: true, config_schema: {} },+ { check_type: 'relationships', description: '', requires_column: true, config_schema: {} },+ { check_type: 'row_count', description: '', requires_column: false, config_schema: {} },+ { check_type: 'freshness', description: '', requires_column: true, config_schema: {} },+ { check_type: 'custom_sql', description: '', requires_column: false, config_schema: {} },+]++function buildCheck(overrides: Partial<DataQualityCheckApi> = {}): DataQualityCheckApi {+ return {+ id: 'check-1',+ check_type: CheckTypeEnumApi.NotNull,+ column_name: 'customer_id',+ enabled: true,+ severity: 'error',+ last_status: '',+ config: {},+ tags: [],+ ...overrides,+ } as DataQualityCheckApi+}++function buildSuiteRun(overrides: Partial<DataQualitySuiteRunApi> = {}): DataQualitySuiteRunApi {+ return {+ id: 'suite-1',+ status: 'running',+ trigger: 'manual',+ checks_passed: 0,+ checks_failed: 0,+ checks_errored: 0,+ checks_skipped: 0,+ error: '',+ ...overrides,+ } as DataQualitySuiteRunApi+}++function forbidden(): Error {+ const { ApiError } = jest.requireMock('lib/api')+ return new ApiError('Forbidden', 403, undefined, { detail: 'nope' })+}++describe('dataQualityChecksLogic', () => {+ let logic: ReturnType<typeof dataQualityChecksLogic.build>++ async function mountLogic(props: DataQualityChecksLogicProps = VIEW_PROPS): Promise<void> {+ initKeaTests()+ logic = dataQualityChecksLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ }++ async function openFormWithCatalog(values: Record<string, unknown>): Promise<void> {+ logic.actions.openCheckModal()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setCheckFormValues(values)+ }++ beforeEach(() => {+ jest.clearAllMocks()+ silenceKeaLoadersErrors()+ ;(warehouseSavedQueriesChecksList as jest.Mock).mockResolvedValue({ results: [buildCheck()] })+ ;(warehouseTablesChecksList as jest.Mock).mockResolvedValue({ results: [] })+ ;(warehouseSavedQueriesChecksHealthRetrieve as jest.Mock).mockResolvedValue({+ health: 'healthy',+ checks_total: 1,+ checks_failing: 0,+ })+ ;(warehouseTablesChecksHealthRetrieve as jest.Mock).mockResolvedValue({+ health: 'unknown',+ checks_total: 0,+ checks_failing: 0,+ })+ ;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })+ ;(warehouseTablesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })+ ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG)+ })++ afterEach(() => {+ jest.useRealTimers()+ resumeKeaLoadersErrors()+ logic?.unmount()+ })++ it.each<[DataQualityChecksLogicProps, jest.Mock, jest.Mock]>([+ [VIEW_PROPS, warehouseSavedQueriesChecksList as jest.Mock, warehouseTablesChecksList as jest.Mock],+ [+ { subjectType: 'table', subjectId: 'table-1' },+ warehouseTablesChecksList as jest.Mock,+ warehouseSavedQueriesChecksList as jest.Mock,+ ],+ ])('routes requests to the %o subject family', async (props, expected, notExpected) => {+ await mountLogic(props)++ expect(expected).toHaveBeenCalledWith('1', props.subjectId, { limit: 100 })+ expect(notExpected).not.toHaveBeenCalled()+ })++ it('fails closed without a toast when the subject is forbidden', async () => {+ ;(warehouseSavedQueriesChecksList as jest.Mock).mockRejectedValue(forbidden())++ await mountLogic()++ expect(logic.values.accessDenied).toBe(true)+ expect(lemonToast.error).not.toHaveBeenCalled()+ })++ 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: {} }],+ [+ 'accepted_values',+ { checkType: 'accepted_values', columnName: 'status', acceptedValues: ['paid'] },+ { column_name: 'status', config: { values: ['paid'] } },+ ],+ [+ 'relationships',+ {+ checkType: 'relationships',+ columnName: 'customer_id',+ toSubjectType: 'view',+ toSubjectUuid: 'view-2',+ toColumn: 'id',+ },+ {+ column_name: 'customer_id',+ config: { to_subject_type: 'view', to_subject_uuid: 'view-2', to_column: 'id' },+ },+ ],+ // row_count is the one type without a column, so column_name must be left out entirely.+ ['row_count', { checkType: 'row_count', rowCountMin: 1 }, { config: { min: 1 } }],+ [+ 'freshness',+ { checkType: 'freshness', columnName: 'created_at', maxAgeMinutes: 60 },+ { column_name: 'created_at', config: { max_age_minutes: 60 } },+ ],+ ['custom_sql', { checkType: 'custom_sql', customSql: 'SELECT 1' }, { config: { query: 'SELECT 1' } }],+ ])('sends only the config %s needs', async (checkType, formValues, expectedBody) => {+ ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ id: 'check-new' }))+ await mountLogic()+ await openFormWithCatalog(formValues)++ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesChecksCreate).toHaveBeenCalledWith('1', 'view-1', {+ check_type: checkType,+ severity: 'error',+ tags: [],+ ...expectedBody,+ })+ })++ it.each<[string, Record<string, unknown>]>([+ ['a name that is not an identifier', { checkType: 'not_null', columnName: 'id', name: '1_bad name' }],+ ['row_count bounds that cross', { checkType: 'row_count', rowCountMin: 10, rowCountMax: 1 }],+ ['a freshness window under a minute', { checkType: 'freshness', columnName: 'created_at', maxAgeMinutes: 0 }],+ ['a missing column', { checkType: 'not_null', columnName: '' }],+ ])('refuses to submit %s', async (_case, formValues) => {+ await mountLogic()+ await openFormWithCatalog(formValues)++ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()+ expect(logic.values.checkModalOpen).toBe(true)+ })++ it('replaces the existing row when the server upserts instead of creating', async () => {+ // A semantically identical create returns the row that already exists, so appending it blindly+ // would show the same check twice.+ ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockResolvedValue(+ buildCheck({ id: 'check-1', description: 'clarified' })+ )+ await mountLogic()+ await openFormWithCatalog({ checkType: 'not_null', columnName: 'customer_id' })++ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.checks.map((check) => check.id)).toEqual(['check-1'])+ expect(logic.values.checks[0].description).toEqual('clarified')+ expect(lemonToast.success).toHaveBeenCalledWith('Check saved', expect.anything())+ })++ it('leaves the assertion out of an edit, since the server rejects changing it', async () => {+ ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck({ name: 'renamed' }))+ await mountLogic()+ logic.actions.openCheckModal(buildCheck())+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setCheckFormValues({ name: 'renamed' })++ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith('1', 'view-1', 'check-1', {+ name: 'renamed',+ description: '',+ severity: 'error',+ tags: [],+ })+ })++ it('clears the name during an edit rather than dropping it', async () => {+ // A blank name is a supported "address by id" state, so the PATCH must carry the empty string+ // instead of omitting the key, which would leave the old name in place.+ ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck({ name: '' }))+ await mountLogic()+ logic.actions.openCheckModal(buildCheck({ name: 'existing_name' }))+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setCheckFormValues({ name: '' })++ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith('1', 'view-1', 'check-1', {+ name: '',+ description: '',+ severity: 'error',+ tags: [],+ })+ })++ it('creates the check once when the form is submitted twice', async () => {+ // Enter submits the form even while the save button is disabled by its loading state.+ ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ id: 'check-new' }))+ await mountLogic()+ await openFormWithCatalog({ checkType: 'not_null', columnName: 'customer_id' })++ logic.actions.submitCheckForm()+ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesChecksCreate).toHaveBeenCalledTimes(1)+ })++ it('keeps the form open with the reason when the server rejects a create', async () => {+ const { ApiError } = jest.requireMock('lib/api')+ ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockRejectedValue(+ new ApiError('Forbidden', 403, undefined, { detail: "You don't have access to a table this check reads." })+ )+ await mountLogic()+ await openFormWithCatalog({ checkType: 'not_null', columnName: 'customer_id' })++ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.serverError).toEqual("You don't have access to a table this check reads.")+ expect(logic.values.checkModalOpen).toBe(true)+ expect(logic.values.isCheckFormSubmitting).toBe(false)+ })++ it('drops the deleted row and refreshes health', async () => {+ ;(warehouseSavedQueriesChecksDestroy as jest.Mock).mockResolvedValue(undefined)+ await mountLogic()++ logic.actions.deleteCheck('check-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.checks).toEqual([])+ expect(warehouseSavedQueriesChecksHealthRetrieve).toHaveBeenCalledTimes(2)+ })++ it('patches only the enabled flag when a check is toggled', async () => {+ ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck({ enabled: false }))+ await mountLogic()++ logic.actions.toggleCheckEnabled('check-1', false)+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith('1', 'view-1', 'check-1', {+ enabled: false,+ })+ expect(logic.values.enabledChecksCount).toEqual(0)+ })++ it('skips polling and refreshes when a run comes back already finished', async () => {+ ;(warehouseSavedQueriesChecksRunCreate as jest.Mock).mockResolvedValue(+ buildSuiteRun({ status: 'completed', checks_passed: 2 })+ )+ await mountLogic()++ logic.actions.runCheck('check-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.isSuiteRunning).toBe(false)+ expect(warehouseSavedQueriesCheckSuiteRunsRetrieve).not.toHaveBeenCalled()+ expect(warehouseSavedQueriesChecksList).toHaveBeenCalledTimes(2)+ // pluralize() joins the count to the noun with a non-breaking space.+ expect(lemonToast.success).toHaveBeenCalledWith('All 2\u00a0checks passed')+ })++ it('reloads the run history after completion when it was opened while empty', async () => {+ // History opened with no prior runs leaves suiteRuns empty, so length is a wrong proxy for+ // "opened". A finished run must still refresh the list rather than stay on "No runs yet".+ ;(warehouseSavedQueriesChecksRunCreate as jest.Mock).mockResolvedValue(+ buildSuiteRun({ status: 'completed', checks_passed: 1 })+ )+ await mountLogic()++ // The user expands the run history while it is still empty.+ logic.actions.loadSuiteRuns()+ await expectLogic(logic).toFinishAllListeners()+ ;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockClear()++ logic.actions.runCheck('check-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(warehouseSavedQueriesCheckSuiteRunsList).toHaveBeenCalledTimes(1)+ })++ it('says nothing ran when run all matches no enabled check', async () => {+ ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun({ status: 'empty' }))+ await mountLogic()++ logic.actions.runAll()+ await expectLogic(logic).toFinishAllListeners()++ expect(lemonToast.info).toHaveBeenCalledWith('No enabled checks to run')+ expect(logic.values.runAllInFlight).toBe(false)+ })++ it('reloads the checks once the polled run finishes', async () => {+ ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock)+ .mockResolvedValueOnce(buildSuiteRun())+ .mockResolvedValue(buildSuiteRun({ status: 'completed', checks_passed: 1, checks_failed: 1 }))+ await mountLogic()++ await startRunUnderFakeTimers()+ expect(logic.values.isSuiteRunning).toBe(true)++ await advancePoll(3000)+ await advancePoll(3000)++ expect(logic.values.isSuiteRunning).toBe(false)+ expect(lemonToast.warning).toHaveBeenCalledWith('1 passed, 1 failed')+ })++ it('ignores a stale poll after a newer run has replaced the active one', async () => {+ // A retrieve can still be in flight when a second run starts. The stale terminal response+ // must not finish the old run and dispose the newer run's poll.+ ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun({ id: 'suite-1' }))+ let resolveRetrieve: (run: DataQualitySuiteRunApi) => void = () => {}+ ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mockReturnValue(+ new Promise<DataQualitySuiteRunApi>((resolve) => {+ resolveRetrieve = resolve+ })+ )+ await mountLogic()++ await startRunUnderFakeTimers()+ // The first poll fires and its retrieve is now pending against suite-1.+ await advancePoll(3000)++ // A newer run replaces the active one while suite-1's retrieve is still in flight.+ logic.actions.setActiveSuiteRun(buildSuiteRun({ id: 'suite-2' }))+ await drainListeners()++ resolveRetrieve(buildSuiteRun({ id: 'suite-1', status: 'completed', checks_passed: 1 }))+ await drainListeners()++ expect(logic.values.activeSuiteRun?.id).toEqual('suite-2')+ expect(logic.values.isSuiteRunning).toBe(true)+ expect(lemonToast.success).not.toHaveBeenCalled()+ })++ it('ignores a suite start that resolves after a newer one', async () => {+ // Two starts can be in flight at once: the pending guard is per check, and "Run all" is not+ // blocked by it. A slower earlier request must not replace the run the panel is tracking.+ let resolveFirst: (run: DataQualitySuiteRunApi) => void = () => {}+ ;(warehouseSavedQueriesChecksRunCreate as jest.Mock)+ .mockReturnValueOnce(+ new Promise<DataQualitySuiteRunApi>((resolve) => {+ resolveFirst = resolve+ })+ )+ .mockResolvedValueOnce(buildSuiteRun({ id: 'suite-second' }))+ await mountLogic()++ logic.actions.runCheck('check-1')+ logic.actions.runCheck('check-2')+ await drainListeners()+ expect(logic.values.activeSuiteRun?.id).toEqual('suite-second')++ resolveFirst(buildSuiteRun({ id: 'suite-first' }))+ await drainListeners()++ expect(logic.values.activeSuiteRun?.id).toEqual('suite-second')+ })++ it('reloads an expanded suite run detail once the run finishes', async () => {+ // A suite adopted mid-flight can be expanded while it is still running, caching partial rows.+ ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock)+ .mockResolvedValueOnce(buildSuiteRun())+ .mockResolvedValue(buildSuiteRun({ status: 'completed', checks_passed: 1 }))+ ;(warehouseSavedQueriesCheckSuiteRunsCheckRunsList as jest.Mock).mockResolvedValue([])+ await mountLogic()++ await startRunUnderFakeTimers()+ logic.actions.loadSuiteRunCheckRuns('suite-1')+ await drainListeners()+ const whileRunning = (warehouseSavedQueriesCheckSuiteRunsCheckRunsList as jest.Mock).mock.calls.length++ await advancePoll(3000)+ await advancePoll(3000)++ expect((warehouseSavedQueriesCheckSuiteRunsCheckRunsList as jest.Mock).mock.calls.length).toBeGreaterThan(+ whileRunning+ )+ })++ it('stops polling a run that never finishes', async () => {+ ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mockResolvedValue(buildSuiteRun())+ await mountLogic()++ await startRunUnderFakeTimers()++ // 3s cadence for the first minute, then 15s: 20 + 56 polls covers the 15 minute cap.+ for (let poll = 0; poll < 80 && !logic.values.pollTimedOut; poll++) {+ await advancePoll(poll < 20 ? 3000 : 15000)+ }++ expect(logic.values.pollTimedOut).toBe(true)+ expect(logic.values.isSuiteRunning).toBe(false)+ const pollsBeforeGivingUp = (warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length+ await advancePoll(15000)+ expect((warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length).toEqual(+ pollsBeforeGivingUp+ )+ })++ it('stops polling a run whose retrieve keeps failing', async () => {+ // A request that keeps rejecting (e.g. a 500 or the flag turned off mid-run) must still honor+ // the 15 minute cap instead of retrying forever and leaving the panel stuck running.+ ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mockRejectedValue(new Error('boom'))+ await mountLogic()++ await startRunUnderFakeTimers()++ // 3s cadence for the first minute, then 15s: 20 + 56 polls covers the 15 minute cap.+ for (let poll = 0; poll < 80 && !logic.values.pollTimedOut; poll++) {+ await advancePoll(poll < 20 ? 3000 : 15000)+ }++ expect(logic.values.pollTimedOut).toBe(true)+ expect(logic.values.isSuiteRunning).toBe(false)+ const pollsBeforeGivingUp = (warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length+ await advancePoll(15000)+ expect((warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length).toEqual(+ pollsBeforeGivingUp+ )+ })++ it('stops polling and denies access when a poll is forbidden', async () => {+ // A permanent 403 mid-run (flag off, or query access revoked) should take the access-denied+ // path at once rather than retrying until the 15 minute cap.+ ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mockRejectedValue(forbidden())+ await mountLogic()++ await startRunUnderFakeTimers()+ await advancePoll(3000)++ expect(logic.values.accessDenied).toBe(true)+ const pollsBeforeDenied = (warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length+ await advancePoll(15000)+ expect((warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length).toEqual(pollsBeforeDenied)+ })++ it('adopts a run that was already in flight on mount', async () => {+ ;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [buildSuiteRun()] })++ await mountLogic()++ expect(warehouseSavedQueriesCheckSuiteRunsList).toHaveBeenCalledWith('1', 'view-1', { limit: 1 })+ expect(logic.values.isSuiteRunning).toBe(true)+ })++ // 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> {+ for (let tick = 0; tick < 20; tick++) {+ await Promise.resolve()+ }+ }++ async function startRunUnderFakeTimers(): Promise<void> {+ jest.useFakeTimers()+ logic.actions.runAll()+ await drainListeners()+ }++ async function advancePoll(ms: number): Promise<void> {+ jest.advanceTimersByTime(ms)+ await drainListeners()+ }+})diff --git a/products/data_quality/frontend/dataQualityChecksLogic.ts b/products/data_quality/frontend/dataQualityChecksLogic.tsnew file mode 100644index 000000000000..d4a0bbc06391--- /dev/null+++ b/products/data_quality/frontend/dataQualityChecksLogic.ts@@ -0,0 +1,901 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'+import { loaders } from 'kea-loaders'++import { ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { pluralize } from 'lib/utils/strings'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'++import { DataQualitySubjectRef, DataQualitySubjectType, checksApi } from './checksApi'+import { checkDisplayName } from './checksConstants'+import type {+ DataQualityCheckApi,+ DataQualityCheckRunApi,+ DataQualityCheckTypeApi,+ DataQualitySubjectHealthApi,+ DataQualitySuiteRunApi,+} from './generated/api.schemas'+import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi, SubjectTypeEnumApi } from './generated/api.schemas'++const CHECKS_LIMIT = 100+const SUITE_RUNS_LIMIT = 20+const FAST_POLL_INTERVAL_MS = 3000+const SLOW_POLL_INTERVAL_MS = 15000+const FAST_POLL_WINDOW_MS = 60_000+const POLL_TIMEOUT_MS = 15 * 60_000+const CHECK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/+const TERMINAL_SUITE_RUN_STATUSES = ['completed', 'failed', 'empty']++export type CheckPendingKind = 'running' | 'deleting' | 'toggling' | 'loadingRuns' | 'loadingSuiteRunRuns'++// Annotated rather than asserted at the use site: the annotation still fails the typecheck if a+// CheckPendingKind is added without seeding its map, and kea-typegen can read the type from here.+// Inlining it with `satisfies` makes typegen infer `{ running: {}, ... }`, which nothing can index.+const EMPTY_PENDING_CHECK_ACTIONS: Record<CheckPendingKind, Record<string, boolean>> = {+ running: {},+ deleting: {},+ toggling: {},+ loadingRuns: {},+ loadingSuiteRunRuns: {},+}++export interface DataQualityChecksLogicProps {+ subjectType: DataQualitySubjectType+ subjectId: string+}++export interface CheckFormValues {+ checkType: CheckTypeEnumApi+ columnName: string+ name: string+ description: string+ severity: DataQualityCheckSeverityEnumApi+ tags: string[]+ acceptedValues: string[]+ toSubjectType: SubjectTypeEnumApi+ toSubjectUuid: string+ toColumn: string+ rowCountMin: number | null+ rowCountMax: number | null+ maxAgeMinutes: number | null+ customSql: string+}++export const EMPTY_CHECK_FORM: CheckFormValues = {+ checkType: CheckTypeEnumApi.NotNull,+ columnName: '',+ name: '',+ description: '',+ severity: DataQualityCheckSeverityEnumApi.Error,+ tags: [],+ acceptedValues: [],+ toSubjectType: SubjectTypeEnumApi.View,+ toSubjectUuid: '',+ toColumn: '',+ rowCountMin: null,+ rowCountMax: null,+ maxAgeMinutes: null,+ customSql: '',+}++export function isTerminalSuiteRun(suiteRun: DataQualitySuiteRunApi | null): boolean {+ return !!suiteRun && TERMINAL_SUITE_RUN_STATUSES.includes(suiteRun.status)+}++function subjectRef(props: DataQualityChecksLogicProps): DataQualitySubjectRef {+ return { subjectType: props.subjectType, subjectId: props.subjectId }+}++function isForbidden(error: unknown): boolean {+ return error instanceof ApiError && error.status === 403+}++function apiErrorDetail(error: unknown): string | null {+ return error instanceof ApiError ? error.detail : null+}++function formToConfig(form: CheckFormValues): Record<string, unknown> {+ switch (form.checkType) {+ case CheckTypeEnumApi.AcceptedValues:+ return { values: form.acceptedValues }+ case CheckTypeEnumApi.Relationships:+ return {+ to_subject_type: form.toSubjectType,+ to_subject_uuid: form.toSubjectUuid,+ to_column: form.toColumn,+ }+ case CheckTypeEnumApi.RowCount: {+ const min = form.rowCountMin ?? null+ const max = form.rowCountMax ?? null+ return { ...(min !== null ? { min } : {}), ...(max !== null ? { max } : {}) }+ }+ case CheckTypeEnumApi.Freshness:+ return { max_age_minutes: form.maxAgeMinutes }+ case CheckTypeEnumApi.CustomSql:+ return { query: form.customSql }+ default:+ return {}+ }+}++function formToCheck(form: CheckFormValues, requiresColumn: boolean): Record<string, unknown> {+ return {+ check_type: form.checkType,+ ...(requiresColumn ? { column_name: form.columnName } : {}),+ config: formToConfig(form),+ severity: form.severity,+ tags: form.tags,+ ...(form.name ? { name: form.name } : {}),+ ...(form.description ? { description: form.description } : {}),+ }+}++function checkToForm(check: DataQualityCheckApi): CheckFormValues {+ const config = check.config ?? {}+ return {+ ...EMPTY_CHECK_FORM,+ checkType: check.check_type,+ columnName: check.column_name ?? '',+ name: check.name ?? '',+ description: check.description ?? '',+ severity: check.severity ?? DataQualityCheckSeverityEnumApi.Error,+ tags: check.tags ?? [],+ acceptedValues: (config.values as string[]) ?? [],+ toSubjectType: (config.to_subject_type as SubjectTypeEnumApi) ?? SubjectTypeEnumApi.View,+ toSubjectUuid: (config.to_subject_uuid as string) ?? '',+ toColumn: (config.to_column as string) ?? '',+ rowCountMin: (config.min as number) ?? null,+ rowCountMax: (config.max as number) ?? null,+ maxAgeMinutes: (config.max_age_minutes as number) ?? null,+ customSql: (config.query as string) ?? '',+ }+}++export function suiteRunSummary(suiteRun: DataQualitySuiteRunApi): string {+ const outcomes: [number, string][] = [+ [suiteRun.checks_passed, 'passed'],+ [suiteRun.checks_failed, 'failed'],+ [suiteRun.checks_errored, 'errored'],+ [suiteRun.checks_skipped, 'skipped'],+ ]+ if (suiteRun.checks_failed === 0 && suiteRun.checks_errored === 0 && suiteRun.checks_passed > 0) {+ return `All ${pluralize(suiteRun.checks_passed, 'check')} passed`+ }+ return outcomes+ .filter(([count]) => count > 0)+ .map(([count, outcome]) => `${count} ${outcome}`)+ .join(', ')+}++function checkSortRank(check: DataQualityCheckApi): number {+ if (check.last_status === 'failed' || check.last_status === 'errored') {+ return 0+ }+ return check.enabled === false ? 2 : 1+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataQualityChecksLogicValues {+ accessDenied: boolean+ activeSuiteRun: DataQualitySuiteRunApi | null+ checkForm: CheckFormValues+ checkFormAllErrors: Record<string, any>+ checkFormChanged: boolean+ checkFormErrors: DeepPartialMap<CheckFormValues, ValidationErrorType>+ checkFormHasErrors: boolean+ checkFormManualErrors: Record<string, any>+ checkFormTouched: boolean+ checkFormTouches: Record<string, boolean>+ checkFormValidationErrors: DeepPartialMap<CheckFormValues, ValidationErrorType>+ checkModalOpen: boolean+ checkRunsByCheckId: Record<string, DataQualityCheckRunApi[]>+ checkTypeByName: {+ [k: string]: DataQualityCheckTypeApi+ }+ checkTypes: DataQualityCheckTypeApi[]+ checkTypesLoading: boolean+ checks: DataQualityCheckApi[]+ checksLoading: boolean+ editingCheck: DataQualityCheckApi | null+ enabledChecksCount: number+ health: DataQualitySubjectHealthApi | null+ healthLoading: boolean+ isCheckFormSubmitting: boolean+ isCheckFormValid: boolean+ isSuiteRunning: boolean+ pendingCheckActions: Record<CheckPendingKind, Record<string, boolean>>+ pollTimedOut: boolean+ runAllInFlight: boolean+ serverError: string | null+ showCheckFormErrors: boolean+ sortedChecks: DataQualityCheckApi[]+ suiteRunCheckRunsBySuiteRunId: Record<string, DataQualityCheckRunApi[]>+ suiteRuns: DataQualitySuiteRunApi[]+ suiteRunsLoading: boolean+ suiteRunsRequested: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataQualityChecksLogicActions {+ loadDatabase: (+ args_0?:+ | {+ force?: boolean+ shallow?: boolean+ }+ | undefined+ ) => {+ force?: boolean+ shallow?: boolean+ } // databaseTableListLogic+ adoptRunningSuiteRun: () => {+ value: true+ }+ closeCheckModal: () => {+ value: true+ }+ deleteCheck: (checkId: string) => {+ checkId: string+ }+ finishSuiteRun: (suiteRun: DataQualitySuiteRunApi) => {+ suiteRun: DataQualitySuiteRunApi+ }+ loadCheckRuns: (checkId: string) => {+ checkId: string+ }+ loadCheckTypes: () => any+ loadCheckTypesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadCheckTypesSuccess: (+ checkTypes: DataQualityCheckTypeApi[],+ payload?: any+ ) => {+ checkTypes: DataQualityCheckTypeApi[]+ payload?: any+ }+ loadChecks: () => any+ loadChecksFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadChecksSuccess: (+ checks: DataQualityCheckApi[],+ payload?: any+ ) => {+ checks: DataQualityCheckApi[]+ payload?: any+ }+ loadHealth: () => any+ loadHealthFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadHealthSuccess: (+ health: DataQualitySubjectHealthApi,+ payload?: any+ ) => {+ health: DataQualitySubjectHealthApi+ payload?: any+ }+ loadSuiteRunCheckRuns: (suiteRunId: string) => {+ suiteRunId: string+ }+ loadSuiteRuns: () => any+ loadSuiteRunsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSuiteRunsSuccess: (+ suiteRuns: DataQualitySuiteRunApi[],+ payload?: any+ ) => {+ suiteRuns: DataQualitySuiteRunApi[]+ payload?: any+ }+ openCheckModal: (check?: DataQualityCheckApi | null) => {+ check: DataQualityCheckApi | null+ }+ pollActiveSuiteRun: () => {+ value: true+ }+ removeCheck: (checkId: string) => {+ checkId: string+ }+ resetCheckForm: (values?: CheckFormValues) => {+ values?: CheckFormValues+ }+ runAll: () => {+ value: true+ }+ runCheck: (checkId: string) => {+ checkId: string+ }+ scheduleSuiteRunPoll: () => {+ value: true+ }+ setAccessDenied: () => {+ value: true+ }+ setActiveSuiteRun: (suiteRun: DataQualitySuiteRunApi | null) => {+ suiteRun: DataQualitySuiteRunApi | null+ }+ setCheckFormManualErrors: (errors: Record<string, any>) => {+ errors: Record<string, any>+ }+ setCheckFormValue: (+ key: FieldName,+ value: any+ ) => {+ name: FieldName+ value: any+ }+ setCheckFormValues: (values: DeepPartial<CheckFormValues>) => {+ values: DeepPartial<CheckFormValues>+ }+ setCheckPending: (+ kind: CheckPendingKind,+ checkId: string,+ pending: boolean+ ) => {+ checkId: string+ kind: CheckPendingKind+ pending: boolean+ }+ setCheckRuns: (+ checkId: string,+ runs: DataQualityCheckRunApi[]+ ) => {+ checkId: string+ runs: DataQualityCheckRunApi[]+ }+ setPollTimedOut: () => {+ value: true+ }+ setRunAllInFlight: (inFlight: boolean) => {+ inFlight: boolean+ }+ setServerError: (serverError: string | null) => {+ serverError: string | null+ }+ setSuiteRunCheckRuns: (+ suiteRunId: string,+ runs: DataQualityCheckRunApi[]+ ) => {+ runs: DataQualityCheckRunApi[]+ suiteRunId: string+ }+ submitCheckForm: () => {+ value: boolean+ }+ submitCheckFormFailure: (+ error: Error,+ errors: Record<string, any>+ ) => {+ error: Error+ errors: Record<string, any>+ }+ submitCheckFormRequest: (checkForm: CheckFormValues) => {+ checkForm: CheckFormValues+ }+ submitCheckFormSuccess: (checkForm: CheckFormValues) => {+ checkForm: CheckFormValues+ }+ toggleCheckEnabled: (+ checkId: string,+ enabled: boolean+ ) => {+ checkId: string+ enabled: boolean+ }+ touchCheckFormField: (key: string) => {+ key: string+ }+ upsertCheck: (check: DataQualityCheckApi) => {+ check: DataQualityCheckApi+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataQualityChecksLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ enabledChecksCount: (checks: DataQualityCheckApi[]) => number+ isSuiteRunning: (activeSuiteRun: DataQualitySuiteRunApi | null, pollTimedOut: boolean) => boolean+ checkTypeByName: (checkTypes: DataQualityCheckTypeApi[]) => {+ [k: string]: DataQualityCheckTypeApi+ }+ sortedChecks: (checks: DataQualityCheckApi[]) => DataQualityCheckApi[]+ }+}++export type dataQualityChecksLogicType = MakeLogicType<+ dataQualityChecksLogicValues,+ dataQualityChecksLogicActions,+ DataQualityChecksLogicProps,+ dataQualityChecksLogicMeta+>++export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([+ props({} as DataQualityChecksLogicProps),+ key((props: DataQualityChecksLogicProps) => `${props.subjectType}:${props.subjectId}`),+ path((key) => ['products', 'data_quality', 'frontend', 'dataQualityChecksLogic', key]),+ connect(() => ({+ actions: [databaseTableListLogic, ['loadDatabase']],+ })),+ actions({+ openCheckModal: (check: DataQualityCheckApi | null = null) => ({ check }),+ closeCheckModal: true,+ setServerError: (serverError: string | null) => ({ serverError }),+ upsertCheck: (check: DataQualityCheckApi) => ({ check }),+ removeCheck: (checkId: string) => ({ checkId }),+ deleteCheck: (checkId: string) => ({ checkId }),+ toggleCheckEnabled: (checkId: string, enabled: boolean) => ({ checkId, enabled }),+ runCheck: (checkId: string) => ({ checkId }),+ runAll: true,+ setRunAllInFlight: (inFlight: boolean) => ({ inFlight }),+ setCheckPending: (kind: CheckPendingKind, checkId: string, pending: boolean) => ({ kind, checkId, pending }),+ setActiveSuiteRun: (suiteRun: DataQualitySuiteRunApi | null) => ({ suiteRun }),+ scheduleSuiteRunPoll: true,+ pollActiveSuiteRun: true,+ finishSuiteRun: (suiteRun: DataQualitySuiteRunApi) => ({ suiteRun }),+ setPollTimedOut: true,+ adoptRunningSuiteRun: true,+ loadCheckRuns: (checkId: string) => ({ checkId }),+ setCheckRuns: (checkId: string, runs: DataQualityCheckRunApi[]) => ({ checkId, runs }),+ loadSuiteRunCheckRuns: (suiteRunId: string) => ({ suiteRunId }),+ setSuiteRunCheckRuns: (suiteRunId: string, runs: DataQualityCheckRunApi[]) => ({ suiteRunId, runs }),+ setAccessDenied: true,+ }),+ loaders(({ props }) => ({+ checks: [+ [] as DataQualityCheckApi[],+ {+ loadChecks: async () => (await checksApi.list(subjectRef(props), CHECKS_LIMIT)).results,+ },+ ],+ health: [+ null as DataQualitySubjectHealthApi | null,+ {+ loadHealth: async () => await checksApi.health(subjectRef(props)),+ },+ ],+ checkTypes: [+ [] as DataQualityCheckTypeApi[],+ {+ loadCheckTypes: async () => await checksApi.checkTypes(subjectRef(props)),+ },+ ],+ suiteRuns: [+ [] as DataQualitySuiteRunApi[],+ {+ loadSuiteRuns: async () => (await checksApi.suiteRuns(subjectRef(props), SUITE_RUNS_LIMIT)).results,+ },+ ],+ })),+ reducers({+ checkModalOpen: [+ false,+ {+ openCheckModal: () => true,+ closeCheckModal: () => false,+ },+ ],+ editingCheck: [+ null as DataQualityCheckApi | null,+ {+ openCheckModal: (_, { check }) => check,+ closeCheckModal: () => null,+ },+ ],+ serverError: [+ null as string | null,+ {+ setServerError: (_, { serverError }) => serverError,+ openCheckModal: () => null,+ closeCheckModal: () => null,+ },+ ],+ checks: {+ upsertCheck: (state: DataQualityCheckApi[], { check }: { check: DataQualityCheckApi }) =>+ state.some((existing) => existing.id === check.id)+ ? state.map((existing) => (existing.id === check.id ? check : existing))+ : [check, ...state],+ removeCheck: (state: DataQualityCheckApi[], { checkId }: { checkId: string }) =>+ state.filter((check) => check.id !== checkId),+ },+ pendingCheckActions: [+ EMPTY_PENDING_CHECK_ACTIONS,+ {+ setCheckPending: (state, { kind, checkId, pending }) => ({+ ...state,+ [kind]: { ...state[kind], [checkId]: pending },+ }),+ },+ ],+ runAllInFlight: [+ false,+ {+ runAll: () => true,+ setRunAllInFlight: (_, { inFlight }) => inFlight,+ },+ ],+ activeSuiteRun: [+ null as DataQualitySuiteRunApi | null,+ {+ setActiveSuiteRun: (_, { suiteRun }) => suiteRun,+ finishSuiteRun: (_, { suiteRun }) => suiteRun,+ },+ ],+ pollTimedOut: [+ false,+ {+ setPollTimedOut: () => true,+ setActiveSuiteRun: () => false,+ },+ ],+ checkRunsByCheckId: [+ {} as Record<string, DataQualityCheckRunApi[]>,+ {+ setCheckRuns: (state, { checkId, runs }) => ({ ...state, [checkId]: runs }),+ },+ ],+ suiteRunCheckRunsBySuiteRunId: [+ {} as Record<string, DataQualityCheckRunApi[]>,+ {+ setSuiteRunCheckRuns: (state, { suiteRunId, runs }) => ({ ...state, [suiteRunId]: runs }),+ },+ ],+ // Tracks whether the run history was ever opened, so completion reloads it even when the+ // first load returned no rows. suiteRuns.length cannot tell "empty" from "never opened".+ suiteRunsRequested: [+ false,+ {+ loadSuiteRuns: () => true,+ },+ ],+ accessDenied: [+ false,+ {+ setAccessDenied: () => true,+ },+ ],+ }),+ selectors({+ enabledChecksCount: [+ (s) => [s.checks],+ (checks: DataQualityCheckApi[]) => checks.filter((check) => check.enabled !== false).length,+ ],+ isSuiteRunning: [+ (s) => [s.activeSuiteRun, s.pollTimedOut],+ (activeSuiteRun: DataQualitySuiteRunApi | null, pollTimedOut: boolean) =>+ !!activeSuiteRun && !isTerminalSuiteRun(activeSuiteRun) && !pollTimedOut,+ ],+ checkTypeByName: [+ (s) => [s.checkTypes],+ (checkTypes: DataQualityCheckTypeApi[]) =>+ Object.fromEntries(checkTypes.map((checkType) => [checkType.check_type, checkType])),+ ],+ sortedChecks: [+ (s) => [s.checks],+ (checks: DataQualityCheckApi[]) =>+ [...checks].sort(+ (left, right) =>+ checkSortRank(left) - checkSortRank(right) ||+ checkDisplayName(left).localeCompare(checkDisplayName(right))+ ),+ ],+ }),+ forms(({ props, values, actions, cache }) => ({+ checkForm: {+ defaults: EMPTY_CHECK_FORM,+ errors: [+ (s: any) => [s.checkForm, s.checkTypeByName],+ (form: CheckFormValues, checkTypeByName: Record<string, DataQualityCheckTypeApi>) => ({+ name:+ form.name && !CHECK_NAME_PATTERN.test(form.name)+ ? 'Use letters, numbers and underscores, starting with a letter.'+ : undefined,+ columnName:+ checkTypeByName[form.checkType]?.requires_column && !form.columnName+ ? 'Pick a column for this check.'+ : undefined,+ acceptedValues:+ form.checkType === CheckTypeEnumApi.AcceptedValues && form.acceptedValues.length === 0+ ? 'Add at least one allowed value.'+ : undefined,+ toSubjectUuid:+ form.checkType === CheckTypeEnumApi.Relationships && !form.toSubjectUuid+ ? 'Pick the table or view this column points at.'+ : undefined,+ toColumn:+ form.checkType === CheckTypeEnumApi.Relationships && !form.toColumn+ ? 'Pick the column holding the referenced values.'+ : undefined,+ rowCountMin:+ form.checkType === CheckTypeEnumApi.RowCount &&+ (form.rowCountMin ?? null) === null &&+ (form.rowCountMax ?? null) === null+ ? 'Set a minimum, a maximum, or both.'+ : undefined,+ rowCountMax:+ form.checkType === CheckTypeEnumApi.RowCount &&+ (form.rowCountMin ?? 0) > (form.rowCountMax ?? Infinity)+ ? 'The maximum has to be at least the minimum.'+ : undefined,+ maxAgeMinutes:+ form.checkType === CheckTypeEnumApi.Freshness && (form.maxAgeMinutes ?? 0) < 1+ ? 'Set an age of at least one minute.'+ : undefined,+ customSql:+ form.checkType === CheckTypeEnumApi.CustomSql && !form.customSql.trim()+ ? 'Write the query that selects the failing rows.'+ : undefined,+ }),+ ],+ submit: async (form: CheckFormValues) => {+ // A form can be submitted with Enter while the request is already in flight, which+ // the button's loading state cannot prevent.+ if (cache.savingCheck) {+ return+ }+ cache.savingCheck = true+ actions.setServerError(null)+ const editing = values.editingCheck+ try {+ const saved = editing+ ? await checksApi.partialUpdate(subjectRef(props), editing.id, {+ name: form.name,+ description: form.description,+ severity: form.severity,+ tags: form.tags,+ })+ : await checksApi.create(+ subjectRef(props),+ formToCheck(form, !!values.checkTypeByName[form.checkType]?.requires_column) as any+ )+ actions.upsertCheck(saved)+ actions.closeCheckModal()+ actions.loadHealth()+ lemonToast.success('Check saved', {+ button: { label: 'Run now', action: () => actions.runCheck(saved.id) },+ })+ } catch (error) {+ actions.setServerError(apiErrorDetail(error) ?? 'Could not save the check. Try again.')+ throw error+ } finally {+ cache.savingCheck = false+ }+ },+ },+ })),+ listeners(({ props, values, actions, cache }) => ({+ loadChecksFailure: ({ errorObject }) => {+ if (isForbidden(errorObject)) {+ actions.setAccessDenied()+ }+ },+ loadHealthFailure: ({ errorObject }) => {+ if (isForbidden(errorObject)) {+ actions.setAccessDenied()+ }+ },+ openCheckModal: ({ check }) => {+ actions.resetCheckForm(check ? checkToForm(check) : EMPTY_CHECK_FORM)+ if (!values.checkTypes.length) {+ actions.loadCheckTypes()+ }+ // The relationships picker offers the project's warehouse subjects.+ actions.loadDatabase()+ },+ deleteCheck: async ({ checkId }) => {+ if (values.pendingCheckActions.deleting[checkId]) {+ return+ }+ actions.setCheckPending('deleting', checkId, true)+ try {+ await checksApi.destroy(subjectRef(props), checkId)+ actions.removeCheck(checkId)+ actions.loadHealth()+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) ?? 'Could not delete the check. Try again.')+ } finally {+ actions.setCheckPending('deleting', checkId, false)+ }+ },+ toggleCheckEnabled: async ({ checkId, enabled }) => {+ if (values.pendingCheckActions.toggling[checkId]) {+ return+ }+ actions.setCheckPending('toggling', checkId, true)+ try {+ actions.upsertCheck(await checksApi.partialUpdate(subjectRef(props), checkId, { enabled }))+ actions.loadHealth()+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) ?? 'Could not update the check. Try again.')+ } finally {+ actions.setCheckPending('toggling', checkId, false)+ }+ },+ loadCheckRuns: async ({ checkId }) => {+ if (values.pendingCheckActions.loadingRuns[checkId]) {+ return+ }+ actions.setCheckPending('loadingRuns', checkId, true)+ try {+ actions.setCheckRuns(checkId, await checksApi.runs(subjectRef(props), checkId))+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) ?? 'Could not load the run history. Try again.')+ } finally {+ actions.setCheckPending('loadingRuns', checkId, false)+ }+ },+ loadSuiteRunCheckRuns: async ({ suiteRunId }) => {+ if (values.pendingCheckActions.loadingSuiteRunRuns[suiteRunId]) {+ return+ }+ actions.setCheckPending('loadingSuiteRunRuns', suiteRunId, true)+ try {+ actions.setSuiteRunCheckRuns(+ suiteRunId,+ await checksApi.suiteRunCheckRuns(subjectRef(props), suiteRunId)+ )+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) ?? 'Could not load the run details. Try again.')+ } finally {+ actions.setCheckPending('loadingSuiteRunRuns', suiteRunId, false)+ }+ },+ runCheck: async ({ checkId }) => {+ if (values.pendingCheckActions.running[checkId]) {+ return+ }+ actions.setCheckPending('running', checkId, true)+ // The pending guard is per check, and "Run all" is not blocked by it either, so two+ // starts can be in flight at once. Only the newest one's run may become active:+ // otherwise a slower earlier request lands last and the panel polls the older run.+ cache.suiteStartToken = (cache.suiteStartToken ?? 0) + 1+ const startToken = cache.suiteStartToken+ try {+ const started = await checksApi.run(subjectRef(props), checkId)+ if (cache.suiteStartToken === startToken) {+ actions.setActiveSuiteRun(started)+ }+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) ?? 'Could not start the check. Try again.')+ } finally {+ actions.setCheckPending('running', checkId, false)+ }+ },+ runAll: async () => {+ cache.suiteStartToken = (cache.suiteStartToken ?? 0) + 1+ const startToken = cache.suiteStartToken+ try {+ const started = await checksApi.runAll(subjectRef(props))+ if (cache.suiteStartToken === startToken) {+ actions.setActiveSuiteRun(started)+ }+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) ?? 'Could not start the checks. Try again.')+ } finally {+ actions.setRunAllInFlight(false)+ }+ },+ setActiveSuiteRun: ({ suiteRun }) => {+ cache.disposables.dispose('suiteRunPoll')+ cache.pollElapsedMs = 0+ if (!suiteRun) {+ return+ }+ if (isTerminalSuiteRun(suiteRun)) {+ actions.finishSuiteRun(suiteRun)+ return+ }+ actions.scheduleSuiteRunPoll()+ },+ scheduleSuiteRunPoll: () => {+ const delay = cache.pollElapsedMs < FAST_POLL_WINDOW_MS ? FAST_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS+ cache.disposables.add(() => {+ const timeoutId = setTimeout(() => {+ cache.pollElapsedMs += delay+ actions.pollActiveSuiteRun()+ }, delay)+ return () => clearTimeout(timeoutId)+ }, 'suiteRunPoll')+ },+ pollActiveSuiteRun: async () => {+ const running = values.activeSuiteRun+ if (!running) {+ return+ }+ let polled: DataQualitySuiteRunApi+ try {+ polled = await checksApi.suiteRunRetrieve(subjectRef(props), running.id)+ } catch (error) {+ // A permanent 403 — the flag turned off mid-run, or query access revoked — takes the+ // panel's access-denied path immediately, like every other request here.+ if (isForbidden(error)) {+ actions.setAccessDenied()+ return+ }+ // Other failures are treated as transient and not worth a toast; the next poll retries+ // until the timeout, so a persistently failing request stops rather than polling forever.+ if (cache.pollElapsedMs >= POLL_TIMEOUT_MS) {+ actions.setPollTimedOut()+ return+ }+ actions.scheduleSuiteRunPoll()+ return+ }+ // A newer run may have started while this retrieve was in flight. A stale terminal+ // response would otherwise finish the old run and dispose the newer run's poll.+ if (cache.disposables.isDisposed || values.activeSuiteRun?.id !== running.id) {+ return+ }+ if (isTerminalSuiteRun(polled)) {+ actions.finishSuiteRun(polled)+ return+ }+ if (cache.pollElapsedMs >= POLL_TIMEOUT_MS) {+ actions.setPollTimedOut()+ return+ }+ actions.scheduleSuiteRunPoll()+ },+ finishSuiteRun: ({ suiteRun }) => {+ cache.disposables.dispose('suiteRunPoll')+ actions.loadChecks()+ actions.loadHealth()+ Object.keys(values.checkRunsByCheckId).forEach((checkId) => actions.loadCheckRuns(checkId))+ // An adopted or MCP-triggered suite can be expanded while it is still running, so its+ // rows are cached mid-flight. Without this they stay stale until it is reopened.+ Object.keys(values.suiteRunCheckRunsBySuiteRunId).forEach((suiteRunId) =>+ actions.loadSuiteRunCheckRuns(suiteRunId)+ )+ if (values.suiteRunsRequested) {+ actions.loadSuiteRuns()+ }+ if (suiteRun.status === 'empty') {+ lemonToast.info('No enabled checks to run')+ } else if (suiteRun.status === 'failed' && !suiteRun.checks_failed) {+ lemonToast.error(suiteRun.error || 'The checks could not be run. Try again.')+ } else if (suiteRun.checks_failed || suiteRun.checks_errored) {+ lemonToast.warning(suiteRunSummary(suiteRun))+ } else {+ lemonToast.success(suiteRunSummary(suiteRun))+ }+ },+ adoptRunningSuiteRun: async () => {+ try {+ const [newest] = (await checksApi.suiteRuns(subjectRef(props), 1)).results+ if (newest && !isTerminalSuiteRun(newest) && !values.activeSuiteRun) {+ actions.setActiveSuiteRun(newest)+ }+ } catch (error) {+ if (isForbidden(error)) {+ actions.setAccessDenied()+ }+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadChecks()+ actions.loadHealth()+ actions.adoptRunningSuiteRun()+ }),+])diff --git a/products/data_quality/frontend/dataQualityGateLogic.test.ts b/products/data_quality/frontend/dataQualityGateLogic.test.tsnew file mode 100644index 000000000000..3508db94be21--- /dev/null+++ b/products/data_quality/frontend/dataQualityGateLogic.test.ts@@ -0,0 +1,108 @@+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { initKeaTests } from '~/test/init'+import { expectLogic } from '~/test/keaTestUtils'++import {+ dataWarehouseDataQualityGatePartialUpdate,+ dataWarehouseDataQualityGateRetrieve,+} from 'products/data_warehouse/frontend/generated/api'++import { dataQualityGateLogic } from './dataQualityGateLogic'++jest.mock('lib/api', () => {+ class ApiError extends Error {+ status?: number+ detail: string | null+ constructor(message?: string, status?: number, _headers?: unknown, data?: { detail?: string }) {+ super(message)+ this.status = status+ this.detail = data?.detail ?? null+ }+ }+ return {+ __esModule: true,+ default: {},+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },+ ApiError,+ }+})++jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },+}))++jest.mock('products/data_warehouse/frontend/generated/api', () => ({+ dataWarehouseDataQualityGateRetrieve: jest.fn(),+ dataWarehouseDataQualityGatePartialUpdate: jest.fn(),+}))++describe('dataQualityGateLogic', () => {+ let logic: ReturnType<typeof dataQualityGateLogic.build>++ async function mountLogic(): Promise<void> {+ initKeaTests()+ logic = dataQualityGateLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ }++ beforeEach(() => {+ jest.clearAllMocks()+ silenceKeaLoadersErrors()+ ;(dataWarehouseDataQualityGateRetrieve as jest.Mock).mockResolvedValue({+ gate_materialization_on_checks: false,+ })+ })++ afterEach(() => {+ resumeKeaLoadersErrors()+ logic?.unmount()+ })++ it('hides the toggle when the setting cannot be read', async () => {+ const { ApiError } = jest.requireMock('lib/api')+ ;(dataWarehouseDataQualityGateRetrieve as jest.Mock).mockRejectedValue(new ApiError('Forbidden', 403))++ await mountLogic()++ expect(logic.values.gateReadable).toBe(false)+ expect(logic.values.gateConfig).toBeNull()+ })++ it('snaps the switch back when the write is refused', async () => {+ const { ApiError } = jest.requireMock('lib/api')+ ;(dataWarehouseDataQualityGatePartialUpdate as jest.Mock).mockRejectedValue(+ new ApiError('Forbidden', 403, undefined, { detail: 'You need editor access.' })+ )+ await mountLogic()++ logic.actions.setGateEnabled(true)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.gateConfig?.gate_materialization_on_checks).toBe(false)+ expect(lemonToast.error).toHaveBeenCalledWith('You need editor access.')+ })++ it('locks the toggle while a write is in flight and adopts the stored value', async () => {+ let resolvePatch!: (value: { gate_materialization_on_checks: boolean }) => void+ ;(dataWarehouseDataQualityGatePartialUpdate as jest.Mock).mockReturnValue(+ new Promise((resolve) => {+ resolvePatch = resolve+ })+ )+ await mountLogic()++ logic.actions.setGateEnabled(true)+ // The switch is disabled via this flag until the PATCH settles, so a second click cannot+ // start an overlapping write.+ expect(logic.values.gateSaving).toBe(true)++ resolvePatch({ gate_materialization_on_checks: true })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.gateSaving).toBe(false)+ expect(logic.values.gateConfig?.gate_materialization_on_checks).toBe(true)+ })+})diff --git a/products/data_quality/frontend/dataQualityGateLogic.ts b/products/data_quality/frontend/dataQualityGateLogic.tsnew file mode 100644index 000000000000..b6f18b0a2b10--- /dev/null+++ b/products/data_quality/frontend/dataQualityGateLogic.ts@@ -0,0 +1,115 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiConfig, ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import {+ dataWarehouseDataQualityGatePartialUpdate,+ dataWarehouseDataQualityGateRetrieve,+} from 'products/data_warehouse/frontend/generated/api'+import type { DataQualityGateConfigApi } from 'products/data_warehouse/frontend/generated/api.schemas'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataQualityGateLogicValues {+ gateConfig: DataQualityGateConfigApi | null+ gateConfigLoading: boolean+ gateReadable: boolean+ gateSaving: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface dataQualityGateLogicActions {+ loadGateConfig: () => any+ loadGateConfigFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadGateConfigSuccess: (+ gateConfig: DataQualityGateConfigApi,+ payload?: any+ ) => {+ gateConfig: DataQualityGateConfigApi+ payload?: any+ }+ setGateEnabled: (enabled: boolean) => {+ enabled: boolean+ }+ setGateReadable: (readable: boolean) => {+ readable: boolean+ }+}++export type dataQualityGateLogicType = MakeLogicType<dataQualityGateLogicValues, dataQualityGateLogicActions>++export const dataQualityGateLogic = kea<dataQualityGateLogicType>([+ path(['products', 'data_quality', 'frontend', 'dataQualityGateLogic']),+ actions({+ setGateEnabled: (enabled: boolean) => ({ enabled }),+ setGateReadable: (readable: boolean) => ({ readable }),+ }),+ loaders(() => ({+ gateConfig: [+ null as DataQualityGateConfigApi | null,+ {+ loadGateConfig: async () =>+ await dataWarehouseDataQualityGateRetrieve(String(ApiConfig.getCurrentTeamId())),+ },+ ],+ })),+ reducers({+ gateConfig: {+ setGateEnabled: (_: DataQualityGateConfigApi | null, { enabled }: { enabled: boolean }) => ({+ gate_materialization_on_checks: enabled,+ }),+ },+ // A viewer, or a token without the warehouse scope, cannot read the setting at all.+ gateReadable: [+ true,+ {+ setGateReadable: (_, { readable }) => readable,+ },+ ],+ // In-flight lock for the PATCH, so the switch cannot start a second overlapping write.+ gateSaving: [+ false,+ {+ setGateEnabled: () => true,+ loadGateConfigSuccess: () => false,+ loadGateConfigFailure: () => false,+ },+ ],+ }),+ listeners(({ actions }) => ({+ loadGateConfigFailure: ({ errorObject }) => {+ if (errorObject instanceof ApiError && errorObject.status === 403) {+ actions.setGateReadable(false)+ }+ },+ setGateEnabled: async ({ enabled }) => {+ try {+ const updated = await dataWarehouseDataQualityGatePartialUpdate(String(ApiConfig.getCurrentTeamId()), {+ gate_materialization_on_checks: enabled,+ })+ // Adopt the value the server stored, and release the in-flight lock, through the+ // loader's own success action so we do not re-enter this listener.+ actions.loadGateConfigSuccess(updated)+ } catch (error) {+ // Re-read the stored value rather than assuming the previous one; this also releases+ // the in-flight lock once the retrieve settles.+ actions.loadGateConfig()+ lemonToast.error(+ (error instanceof ApiError && error.detail) || 'Could not change the setting. Try again.'+ )+ }+ },+ })),+ afterMount(({ actions, values }) => {+ if (!values.gateConfig) {+ actions.loadGateConfig()+ }+ }),+])diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.tsindex e1d2c79023ec..ba4565499a70 100644--- a/products/data_quality/frontend/generated/api.schemas.ts+++ b/products/data_quality/frontend/generated/api.schemas.ts@@ -14,7 +14,7 @@ export interface DataQualitySuiteRunApi {/** running, completed, failed, or empty (nothing matched the trigger). */readonly status: string/**- * 'table' or 'view' when the run targets exactly one subject; null for a check-scoped or multi-subject run.+ * 'table' or 'view' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.* @nullable*/readonly subject_type: string | nulldiff --git a/products/data_quality/package.json b/products/data_quality/package.jsonindex f1bae28c9ced..e9f312755a7f 100644--- a/products/data_quality/package.json+++ b/products/data_quality/package.json@@ -2,5 +2,20 @@"name": "@posthog/products-data-quality","scripts": {"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"+ },+ "dependencies": {+ "kea": "catalog:",+ "kea-forms": "catalog:",+ "kea-loaders": "catalog:"+ },+ "devDependencies": {+ "@testing-library/jest-dom": "^5.17.0",+ "@testing-library/react": "^14.3.1"+ },+ "peerDependencies": {+ "@posthog/icons": "catalog:",+ "@types/react": "*",+ "clsx": "*",+ "react": "*"}}diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsxindex e4198a83034b..13714dc20d30 100644--- a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx+++ b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx@@ -16,6 +16,7 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { ActivityScope } from '~/types'+import { DataQualityChecksPanel } from 'products/data_quality/frontend/DataQualityChecksPanel'import { cleanSourceId } from 'products/data_warehouse/frontend/utils'import { shouldShowManagedSourceMetricsTab, shouldShowManagedSourceSyncsTab } from '../SourceScene/SourceScene'@@ -67,6 +68,8 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Elemeconst showSyncs = shouldShowManagedSourceSyncsTab(source)const showMetrics = shouldShowManagedSourceMetricsTab(source, !!featureFlags[FEATURE_FLAGS.DWH_SOURCE_METRICS])const showDescriptions = !!featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SEMANTIC_ENRICHMENT]+ // The warehouse table only exists once the schema has synced, and checks hang off that table.+ const showDataQuality = !!featureFlags[FEATURE_FLAGS.DATA_QUALITY_CHECKS] && !!schema?.table?.idconst showColumnsSection = supportsColumnSelectionconst visibleSections = SCHEMA_CONFIGURATION_SECTIONS.filter((key) => (key !== 'columns' || showColumnsSection) && (key !== 'descriptions' || showDescriptions)@@ -87,6 +90,13 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Eleme}}, [source, showSyncs, showMetrics, currentTab, setCurrentTab])+ useEffect(() => {+ // Wait for the schema, for the same reason the tab check above waits for the source.+ if (schema && !showDataQuality && currentTab === 'data-quality') {+ setCurrentTab('configuration')+ }+ }, [schema, showDataQuality, currentTab, setCurrentTab])+useEffect(() => {if (!showColumnsSection && currentSection === 'columns') {setCurrentSection('details')@@ -163,6 +173,20 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Eleme})}+ if (showDataQuality && schema.table) {+ tabs.push({+ label: 'Data quality',+ key: 'data-quality',+ content: (+ <DataQualityChecksPanel+ subjectType="table"+ subjectId={schema.table.id}+ columns={schema.table.columns ?? []}+ />+ ),+ })+ }+tabs.push({label: 'History',key: 'history',@@ -170,7 +194,9 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Eleme})const activeTab =- (!showMetrics && currentTab === 'metrics') || (!showSyncs && currentTab === 'syncs')+ (!showMetrics && currentTab === 'metrics') ||+ (!showSyncs && currentTab === 'syncs') ||+ (!showDataQuality && currentTab === 'data-quality')? 'configuration': currentTabdiff --git a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.tsindex 2d412fb19d52..d57b23756ef6 100644--- a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts+++ b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts@@ -23,7 +23,7 @@ import {import { cleanSourceId } from 'products/data_warehouse/frontend/utils'-export const SCHEMA_SCENE_TABS = ['configuration', 'syncs', 'metrics', 'history'] as const+export const SCHEMA_SCENE_TABS = ['configuration', 'syncs', 'metrics', 'data-quality', 'history'] as constexport type SchemaSceneTab = (typeof SCHEMA_SCENE_TABS)[number]export const SCHEMA_CONFIGURATION_SECTIONS = [@@ -84,7 +84,7 @@ export interface schemaSceneLogicActions {section: 'columns' | 'danger-zone' | 'descriptions' | 'details' | 'schedule' | 'sync-method'}_setCurrentTab: (tab: SchemaSceneTab) => {- tab: 'configuration' | 'history' | 'metrics' | 'syncs'+ tab: 'configuration' | 'data-quality' | 'history' | 'metrics' | 'syncs'}cancelSchema: (schema: ExternalDataSourceSchema) => {schema: ExternalDataSourceSchema@@ -135,7 +135,7 @@ export interface schemaSceneLogicActions {section: 'columns' | 'danger-zone' | 'descriptions' | 'details' | 'schedule' | 'sync-method'}setCurrentTab: (tab: SchemaSceneTab) => {- tab: 'configuration' | 'history' | 'metrics' | 'syncs'+ tab: 'configuration' | 'data-quality' | 'history' | 'metrics' | 'syncs'}setIsProjectTime: (isProjectTime: boolean) => {isProjectTime: booleandiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8f2966b8f76b..6b543b587279 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20916,7 +20916,7 @@ export namespace Schemas {/** running, completed, failed, or empty (nothing matched the trigger). */readonly status: string;/**- * 'table' or 'view' when the run targets exactly one subject; null for a check-scoped or multi-subject run.+ * 'table' or 'view' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.* @nullable*/readonly subject_type: string | null;