Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-quality): add a checks overview and make checks editable (#83720)

Thiago Salvatore85959f6939eb
diff --git a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx
index 31f318191113..20c8d8f00515 100644
--- a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx
+++ b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx
@@ -12,6 +12,8 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
+import { DataQualityOverview } from 'products/data_quality/frontend/overview/DataQualityOverview'
+
import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneLogic'
import { DataModelingTab } from './scene/DataModelingTab'
import { MonitoringTab } from './scene/MonitoringTab'
@@ -29,6 +31,7 @@ const TAB_LABELS: Record<DataWarehouseTab, string> = {
[DataWarehouseTab.MONITORING]: 'Monitoring',
[DataWarehouseTab.SETTINGS]: 'Settings',
[DataWarehouseTab.MODELING]: 'Modeling',
+ [DataWarehouseTab.DATA_QUALITY]: 'Data quality',
}
function tabContent(tab: DataWarehouseTab): JSX.Element {
@@ -41,6 +44,8 @@ function tabContent(tab: DataWarehouseTab): JSX.Element {
return <SettingsTab />
case DataWarehouseTab.MODELING:
return <DataModelingTab />
+ case DataWarehouseTab.DATA_QUALITY:
+ return <DataQualityOverview />
}
}
diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts
index 47569c148109..90900eec7699 100644
--- a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts
+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts
@@ -16,6 +16,7 @@ export enum DataWarehouseTab {
MONITORING = 'monitoring',
SETTINGS = 'settings',
MODELING = 'modeling',
+ DATA_QUALITY = 'data-quality',
}
function isDataWarehouseTab(tab: unknown): tab is DataWarehouseTab {
@@ -125,6 +126,9 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([
if (featureFlags[FEATURE_FLAGS.DATA_MODELING_TAB]) {
tabs.push(DataWarehouseTab.MODELING)
}
+ if (featureFlags[FEATURE_FLAGS.DATA_QUALITY_CHECKS]) {
+ tabs.push(DataWarehouseTab.DATA_QUALITY)
+ }
if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]) {
tabs.push(DataWarehouseTab.SETTINGS)
}
diff --git a/playwright/e2e/data-quality-overview.spec.ts b/playwright/e2e/data-quality-overview.spec.ts
new file mode 100644
index 000000000000..36679277c0db
--- /dev/null
+++ b/playwright/e2e/data-quality-overview.spec.ts
@@ -0,0 +1,76 @@
+/**
+ * Editing and deleting a data quality check from the Data Ops overview.
+ */
+import { expect } from '@playwright/test'
+
+import { FEATURE_FLAGS } from '../../frontend/src/lib/constants'
+import { mockFeatureFlags } from '../utils/mockApi'
+import { test } from '../utils/workspace-test-base'
+
+const CHECK_NAME = 'orders_has_rows'
+const SUBJECT_NAME = 'orders_e2e'
+
+test('edits and deletes a check from Data Ops', async ({ page, playwrightSetup }) => {
+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true })
+ const auth = {
+ headers: {
+ Authorization: `Bearer ${workspace.personal_api_key}`,
+ 'Content-Type': 'application/json',
+ },
+ }
+
+ const savedQuery = await page.request.post(`/api/projects/${workspace.team_id}/warehouse_saved_queries/`, {
+ ...auth,
+ data: { name: SUBJECT_NAME, query: { kind: 'HogQLQuery', query: 'SELECT 1 AS id' } },
+ })
+ expect(savedQuery.ok()).toBe(true)
+ const savedQueryId = (await savedQuery.json()).id
+
+ const created = await page.request.post(
+ `/api/projects/${workspace.team_id}/warehouse_saved_queries/${savedQueryId}/checks/`,
+ {
+ ...auth,
+ data: {
+ name: CHECK_NAME,
+ check_type: 'custom_sql',
+ column_name: '',
+ config: { query: 'SELECT id FROM orders_e2e WHERE id < 0' },
+ },
+ }
+ )
+ expect(created.ok()).toBe(true)
+ const check = await created.json()
+
+ await mockFeatureFlags(page, {
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: true,
+ [FEATURE_FLAGS.DATA_QUALITY_CHECKS]: true,
+ })
+ await playwrightSetup.loginAndNavigateToTeam(page, workspace)
+ await page.goto('/data-ops?tab=data-quality')
+
+ await page.getByLabel(`Expand checks for ${SUBJECT_NAME}`).click({ timeout: 30000 })
+ await expect(page.getByText(CHECK_NAME)).toBeVisible()
+
+ await page.getByLabel(`Actions for check ${CHECK_NAME}`).click()
+ await page.getByRole('menuitem', { name: 'Edit' }).click()
+ await page.getByLabel('Description').fill('Every order keeps a positive id')
+ await page.getByTestId('data-quality-check-save').click()
+
+ await expect(page.getByText('Check saved')).toBeVisible()
+ const edited = await page.request.get(
+ `/api/projects/${workspace.team_id}/warehouse_saved_queries/${savedQueryId}/checks/${check.id}/`,
+ auth
+ )
+ const editedCheck = await edited.json()
+ // The point of the whole change: an edit refines the check rather than replacing it.
+ expect(editedCheck.id).toEqual(check.id)
+ expect(editedCheck.description).toEqual('Every order keeps a positive id')
+ expect(editedCheck.last_status).toEqual(check.last_status)
+ expect(editedCheck.last_run_at).toEqual(check.last_run_at)
+
+ await page.getByLabel(`Actions for check ${CHECK_NAME}`).click()
+ await page.getByRole('menuitem', { name: 'Delete' }).click()
+ await page.getByRole('button', { name: 'Delete' }).click()
+
+ await expect(page.getByText(CHECK_NAME)).toHaveCount(0)
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ecbc34b1c05c..13b19c69688c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2983,6 +2983,9 @@ importers:
kea-loaders:
specifier: 'catalog:'
version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ kea-router:
+ specifier: 'catalog:'
+ version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
react:
specifier: 18.3.1
version: 18.3.1
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index a701f84f5419..6a56b6da8bdc 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -699,6 +699,9 @@ SPECTACULAR_SETTINGS = {
"LayoutCompactionEnum": ["vertical", "horizontal", "stable"],
"DesktopAccessReasonEnum": "products.tasks.backend.facade.contracts.DESKTOP_ACCESS_REASON_SCHEMA_VALUES",
"PropertyGroupOperator": ["AND", "OR"],
+ # `severity` is shared by a data quality check, its overview projection, and the severity a
+ # past run was judged at.
+ "DataQualityCheckSeverityEnum": ["error", "warn"],
# `scope`/`state` are generic field names; one shared name for the canvas state scope set.
"CanvasStateScopeEnum": ["user", "shared"],
# `kind` is a generic field name; one shared name for the canvas kind set.
diff --git a/products/access_control/backend/tests/__snapshots__/test_access_control.ambr b/products/access_control/backend/tests/__snapshots__/test_access_control.ambr
index 6afcef36e6c4..7e4aea4b80a8 100644
--- a/products/access_control/backend/tests/__snapshots__/test_access_control.ambr
+++ b/products/access_control/backend/tests/__snapshots__/test_access_control.ambr
@@ -63,6 +63,7 @@
'survey',
'tagger',
'ticket',
+ 'warehouse_objects',
'warehouse_table',
'warehouse_view',
])
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index be137ef6e701..03df6fa3fe25 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -24,6 +24,7 @@ _LAZY = {
"materialize_saved_query": "logic.node_materialization",
"run_saved_query_materialization": "logic.node_materialization",
"get_materialized_table_uri": "logic.saved_query_reads",
+ "get_node_ids_for_saved_queries": "logic.saved_query_reads",
"get_saved_query_ids_for_nodes": "logic.saved_query_reads",
"get_saved_query_summary": "logic.saved_query_reads",
"saved_query_materialized_at": "logic.saved_query_freshness",
diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.py
index e06616228e07..dc80c69e0251 100644
--- a/products/data_modeling/backend/logic/saved_query_reads.py
+++ b/products/data_modeling/backend/logic/saved_query_reads.py
@@ -44,6 +44,24 @@ def get_materialized_table_uri(team_id: int, saved_query_id: UUID | str) -> str
return f"{settings.BUCKET_URL}/{saved_query.folder_path}/{saved_query.normalized_name}"
+def get_node_ids_for_saved_queries(team_id: int, saved_query_ids: Iterable[UUID | str]) -> dict[str, str]:
+ """The DAG node each of these saved queries sits on, as one query.
+
+ A saved query can appear in several DAGs; the lowest node id wins so a link built from this
+ stays put across refreshes instead of following whichever row the database returned first.
+ """
+ ids = list(saved_query_ids)
+ if not ids:
+ return {}
+ rows = (
+ Node.objects.filter(team_id=team_id, saved_query_id__in=ids).order_by("id").values_list("saved_query_id", "id")
+ )
+ nodes: dict[str, str] = {}
+ for saved_query_id, node_id in rows:
+ nodes.setdefault(str(saved_query_id), str(node_id))
+ return nodes
+
+
def get_saved_query_ids_for_nodes(team_id: int, node_ids: Iterable[UUID | str]) -> list[str]:
"""The saved queries behind these DAG nodes. Source-table nodes have none and are dropped."""
rows = Node.objects.filter(team_id=team_id, id__in=list(node_ids), saved_query__isnull=False).values_list(
diff --git a/products/data_quality/backend/admin.py b/products/data_quality/backend/admin.py
index c7fbc5585387..74b5e0faa8f8 100644
--- a/products/data_quality/backend/admin.py
+++ b/products/data_quality/backend/admin.py
@@ -8,7 +8,7 @@ class DataQualityCheckAdmin(admin.ModelAdmin):
list_display = ("id", "check_type", "subject_name", "column_name", "severity", "enabled", "last_status")
list_filter = ("check_type", "severity", "enabled", "subject_type", "subject_status")
search_fields = ("id", "name", "subject_name", "team__id")
- raw_id_fields = ("team", "created_by", "owner", "saved_query", "table")
+ raw_id_fields = ("team", "created_by", "definition_author", "owner", "saved_query", "table")
readonly_fields = ("id", "fingerprint", "created_at", "updated_at", "last_run_at", "last_status")
diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.py
index 35c2436a5981..a94ab43fd613 100644
--- a/products/data_quality/backend/facade/api.py
+++ b/products/data_quality/backend/facade/api.py
@@ -9,19 +9,21 @@ data. ORM model classes never cross here either -- ``facade/models.py`` is their
from ..logic.checks import (
checks_for_subject,
+ edit_check,
+ empty_check_suite,
ensure_name_available,
soft_delete_check,
start_check_suite,
subject_health,
- update_check,
upsert_check,
validate_check,
)
from ..logic.compiler import compile_check, related_subject_ref
from ..logic.config import get_gate_config, set_gate_materialization_on_checks
from ..logic.contracts import CompiledCheck, SubjectRef
-from ..logic.errors import CheckConfigError, SubjectUnresolvableError
+from ..logic.errors import CheckConfigError, CheckEditConflict, SubjectUnresolvableError
from ..logic.health import CheckStatusRow, roll_up_health
+from ..logic.navigation import SubjectKey, SubjectLocation, subject_locations
from ..logic.notifications import notify_materialization_blocked
from ..logic.registry import UnknownCheckTypeError, list_check_types
from ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entry
@@ -32,9 +34,12 @@ from .contracts import CheckTypeInfo
__all__ = [
"CheckConfigError",
+ "CheckEditConflict",
"CheckStatusRow",
"CheckTypeInfo",
"CompiledCheck",
+ "SubjectKey",
+ "SubjectLocation",
"SubjectRef",
"SubjectUnresolvableError",
"UnknownCheckTypeError",
@@ -42,6 +47,8 @@ __all__ = [
"compile_check",
"compute_fingerprint",
"denied_subject_names",
+ "edit_check",
+ "empty_check_suite",
"ensure_name_available",
"from_config_entry",
"get_gate_config",
@@ -57,8 +64,8 @@ __all__ = [
"soft_delete_check",
"start_check_suite",
"subject_health",
+ "subject_locations",
"to_config_entry",
- "update_check",
"upsert_check",
"validate_check",
]
diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.py
index b3e623270afa..31b8b7eb0df2 100644
--- a/products/data_quality/backend/logic/checks.py
+++ b/products/data_quality/backend/logic/checks.py
@@ -17,6 +17,7 @@ from django.db.models import QuerySet
from temporalio.common import RetryPolicy
+from posthog.dataclasses import frozen
from posthog.models.team import Team
from posthog.models.user import User
from posthog.temporal.common.client import sync_connect
@@ -25,7 +26,7 @@ from ..facade.contracts import CHECK_SUITE_WORKFLOW_NAME
from ..facade.enums import SubjectHealth, SubjectStatus, SubjectType, SuiteRunStatus, SuiteRunTrigger
from ..models import DataQualityCheck, DataQualitySuiteRun
from .compiler import related_subject_ref
-from .errors import SubjectUnresolvableError
+from .errors import DuplicateDefinitionError, NameConflictError, SubjectUnresolvableError
from .exceptions import CheckNameConflict
from .health import CheckStatusRow, roll_up_health
from .registry import get_spec
@@ -46,6 +47,11 @@ _UPSERTABLE_FIELDS = (
"owner",
)
+# What the fingerprint hashes: change any of these and the check asserts something else.
+_ASSERTION_FIELDS = ("check_type", "column_name", "config")
+
+_EDITABLE_FIELDS = (*_UPSERTABLE_FIELDS, *_ASSERTION_FIELDS)
+
def _subject_fk(subject_type: str, subject_uuid: str | UUID) -> dict[str, Any]:
"""The FK kwargs for whichever subject kind this is."""
@@ -94,12 +100,15 @@ def upsert_check(
parsed = validate_check(team, subject_type, subject_uuid, check_type, column_name, config)
subject = resolve_subject(team.id, subject_type, subject_uuid)
+ # Stored in the same canonical form the fingerprint hashes, so a created check and one edited
+ # into the same definition are indistinguishable afterwards.
+ canonical = parsed.model_dump(mode="json")
fingerprint = compute_fingerprint(
subject_type=subject_type,
subject_uuid=str(subject_uuid),
check_type=check_type,
column_name=column_name,
- config=parsed.model_dump(mode="json"),
+ config=canonical,
)
existing = _find_by_fingerprint(team.id, subject_type, subject_uuid, fingerprint)
fields = {key: value for key, value in optional.items() if key in _UPSERTABLE_FIELDS and value is not None}
@@ -120,7 +129,7 @@ def upsert_check(
subject_status=SubjectStatus.ACTIVE,
check_type=check_type,
column_name=column_name,
- config=config,
+ config=canonical,
fingerprint=fingerprint,
**_subject_fk(subject_type, subject_uuid),
**fields,
@@ -129,38 +138,146 @@ def upsert_check(
except IntegrityError:
# Check-then-insert race: a concurrent identical request inserted this fingerprint between
# the lookup above and this create. Refetch and refine the row it won with, so the loser
- # gets the promised existing check (HTTP 200) rather than a 500. A collision on any other
- # constraint (e.g. the name) is a genuine conflict, not this race -- re-raise it.
+ # gets the promised existing check (HTTP 200) rather than a 500.
existing = _find_by_fingerprint(team.id, subject_type, subject_uuid, fingerprint)
if existing is None:
+ # The name constraint races the same way, past its own precheck, so report it as the
+ # conflict it is rather than letting the database error surface as a 500.
+ ensure_name_available(team.id, fields.get("name") or "")
raise
- return update_check(existing, **fields, deleted=False), False
+ return update_check(existing, **fields), False
def _find_by_fingerprint(
team_id: int, subject_type: str, subject_uuid: str, fingerprint: str
) -> DataQualityCheck | None:
+ """The *active* check carrying this fingerprint, if any.
+
+ Active-only so authoring a definition that was deleted earlier creates a new check with its own
+ id and history, rather than resurrecting a row the user believes is gone.
+ """
return (
DataQualityCheck.objects.for_team(team_id)
- .filter(fingerprint=fingerprint, **_subject_fk(subject_type, subject_uuid))
+ .filter(fingerprint=fingerprint, deleted=False, **_subject_fk(subject_type, subject_uuid))
.first()
)
def update_check(check: DataQualityCheck, **fields: Any) -> DataQualityCheck:
- """Apply presentation changes. The assertion itself is immutable -- re-create instead."""
- changed = []
- for key, value in fields.items():
- if key in _UPSERTABLE_FIELDS or key == "deleted":
- setattr(check, key, value)
- changed.append(key)
+ """Apply presentation changes only. Editing the assertion goes through ``edit_check``."""
+ changed = [key for key in fields if key in _UPSERTABLE_FIELDS]
+ for key in changed:
+ setattr(check, key, fields[key])
if changed:
check.save(update_fields=[*changed, "updated_at"])
return check
+@frozen
+class _CandidateDefinition:
+ """What a requested edit would leave the check asserting, canonicalized."""
+
+ check_type: str
+ column_name: str
+ config: dict[str, Any]
+ fingerprint: str
+
+
+def edit_check(*, team: Team, check: DataQualityCheck, editor: User | None, **fields: Any) -> DataQualityCheck:
+ """Save a complete definition change, or none of it. The owning subject never moves.
+
+ Two edits to the same check serialize on the row lock, so the loser recomputes against what the
+ winner committed. Two *different* rows converging on one definition race past that lock, and the
+ active-fingerprint constraint is what settles them -- its ``IntegrityError`` comes back as the
+ same conflict the precheck raises.
+ """
+ requested = {key: value for key, value in fields.items() if key in _EDITABLE_FIELDS}
+ try:
+ with transaction.atomic():
+ locked = DataQualityCheck.objects.for_team(team.id).select_for_update().get(id=check.id)
+ return _commit_edit(team, locked, editor, requested)
+ except IntegrityError:
+ # Which constraint lost decides which field the error is addressed to. Asking about the
+ # definition alone would answer "duplicate" for every one of them, since an edit that leaves
+ # the assertion alone still finds its own fingerprint.
+ candidate = _candidate_definition(team, check, requested)
+ if _definition_taken(check, candidate.fingerprint):
+ raise DuplicateDefinitionError()
+ if _name_taken(team.id, requested.get("name") or "", exclude_id=check.id):
+ raise NameConflictError()
+ raise
+
+
+def _commit_edit(
+ team: Team, check: DataQualityCheck, editor: User | None, requested: dict[str, Any]
+) -> DataQualityCheck:
+ candidate = _candidate_definition(team, check, requested)
+ _ensure_definition_available(check, candidate.fingerprint)
+ if _name_taken(team.id, requested.get("name") or "", exclude_id=check.id):
+ raise NameConflictError()
+
+ changed = {key for key in requested if key in _UPSERTABLE_FIELDS}
+ for key in changed:
+ setattr(check, key, requested[key])
+
+ if candidate.fingerprint != check.fingerprint:
+ check.check_type = candidate.check_type
+ check.column_name = candidate.column_name
+ check.config = candidate.config
+ check.fingerprint = candidate.fingerprint
+ # An automated run of an edited definition authorizes as whoever last changed what it reads,
+ # not as whoever created it years ago.
+ check.definition_author = editor
+ changed |= {*_ASSERTION_FIELDS, "fingerprint", "definition_author"}
+
+ if changed:
+ check.save(update_fields=[*changed, "updated_at"])
+ return check
+
+
+def _candidate_definition(team: Team, check: DataQualityCheck, requested: dict[str, Any]) -> _CandidateDefinition:
+ check_type = requested.get("check_type", check.check_type)
+ column_name = requested.get("column_name", check.column_name)
+ parsed = validate_check(
+ team,
+ check.subject_type,
+ str(check.subject_uuid),
+ check_type,
+ column_name,
+ requested.get("config", check.config) or {},
+ )
+ config = parsed.model_dump(mode="json")
+ return _CandidateDefinition(
+ check_type=check_type,
+ column_name=column_name,
+ config=config,
+ fingerprint=compute_fingerprint(
+ subject_type=check.subject_type,
+ subject_uuid=str(check.subject_uuid),
+ check_type=check_type,
+ column_name=column_name,
+ config=config,
+ ),
+ )
+
+
+def _definition_taken(check: DataQualityCheck, fingerprint: str) -> bool:
+ """Whether *another* active check on this subject already asserts this."""
+ return (
+ DataQualityCheck.objects.for_team(check.team_id)
+ .filter(fingerprint=fingerprint, deleted=False, **_subject_fk(check.subject_type, str(check.subject_uuid)))
+ .exclude(id=check.id)
+ .exists()
+ )
+
+
+def _ensure_definition_available(check: DataQualityCheck, fingerprint: str) -> None:
+ if _definition_taken(check, fingerprint):
+ raise DuplicateDefinitionError()
+
+
def soft_delete_check(check: DataQualityCheck) -> None:
"""Hide the definition but keep its run history queryable."""
check.deleted = True
@@ -249,11 +366,34 @@ def start_check_suite(
return suite_run
-def ensure_name_available(team_id: int, name: str, exclude_id: UUID | str | None = None) -> None:
+def empty_check_suite(*, team: Team, user: User | None = None) -> DataQualitySuiteRun:
+ """Record a run that had nothing to run, without starting a workflow.
+
+ An empty selection cannot be expressed to the worker: by the time ``check_ids`` reaches the
+ prepare activity, an empty list is indistinguishable from no selector at all, and the suite
+ would sweep the whole project.
+ """
+ now = datetime.now(UTC)
+ return DataQualitySuiteRun.objects.for_team(team.id).create(
+ team=team,
+ trigger=SuiteRunTrigger.MANUAL,
+ created_by=user,
+ status=SuiteRunStatus.EMPTY,
+ started_at=now,
+ finished_at=now,
+ )
+
+
+def _name_taken(team_id: int, name: str, exclude_id: UUID | str | None = None) -> bool:
+ """Whether an *active* check already holds this name. Deleted ones keep theirs only as history."""
if not name:
- return
- clashes = DataQualityCheck.objects.for_team(team_id).filter(name=name)
+ return False
+ clashes = DataQualityCheck.objects.for_team(team_id).filter(name=name, deleted=False)
if exclude_id is not None:
clashes = clashes.exclude(id=exclude_id)
- if clashes.exists():
+ return clashes.exists()
+
+
+def ensure_name_available(team_id: int, name: str, exclude_id: UUID | str | None = None) -> None:
+ if _name_taken(team_id, name, exclude_id):
raise CheckNameConflict(f"A check named '{name}' already exists in this project.")
diff --git a/products/data_quality/backend/logic/errors.py b/products/data_quality/backend/logic/errors.py
index 0f86133e7a90..71fc0904ba8d 100644
--- a/products/data_quality/backend/logic/errors.py
+++ b/products/data_quality/backend/logic/errors.py
@@ -11,3 +11,34 @@ class CheckConfigError(ValueError):
class SubjectUnresolvableError(ValueError):
"""The subject a check targets no longer resolves in its owning product."""
+
+
+class CheckEditConflict(ValueError):
+ """An edit that cannot be committed as asked, addressed to the fields at fault.
+
+ Carries ``code`` and ``fields`` so the presentation layer can render it beside the offending
+ form fields instead of as a bare status code.
+ """
+
+ code = "check_edit_conflict"
+ fields: tuple[str, ...] = ()
+
+
+class DuplicateDefinitionError(CheckEditConflict):
+ """Another active check on this subject already asserts exactly this."""
+
+ code = "duplicate_definition"
+ fields = ("config", "check_type", "column_name")
+
+ def __init__(self, message: str = "A check with this definition already exists.") -> None:
+ super().__init__(message)
+
+
+class NameConflictError(CheckEditConflict):
+ """Another check in the project already holds this name."""
+
+ code = "name_conflict"
+ fields = ("name",)
+
+ def __init__(self, message: str = "A check with this name already exists.") -> None:
+ super().__init__(message)
diff --git a/products/data_quality/backend/logic/flags.py b/products/data_quality/backend/logic/flags.py
index d37defec0666..f3f9b60adc53 100644
--- a/products/data_quality/backend/logic/flags.py
+++ b/products/data_quality/backend/logic/flags.py
@@ -13,7 +13,9 @@ DATA_QUALITY_CHECKS_FEATURE_FLAG = "data-quality-checks"
def is_data_quality_checks_enabled(team: "Team") -> bool:
"""The `data-quality-checks` flag check, org-keyed. Canonical home for the check -- gate any
data-quality surface (API, information_schema tables, MCP tools, triggers) through here."""
- if settings.DEBUG:
+ # The flag is evaluated against PostHog's own analytics project, which a local or end-to-end
+ # environment has no membership in, so it would gate the whole product out of both.
+ if settings.DEBUG or settings.E2E_TESTING:
return True
return feature_enabled_or_false(
DATA_QUALITY_CHECKS_FEATURE_FLAG,
diff --git a/products/data_quality/backend/logic/navigation.py b/products/data_quality/backend/logic/navigation.py
new file mode 100644
index 000000000000..7a72da76a68c
--- /dev/null
+++ b/products/data_quality/backend/logic/navigation.py
@@ -0,0 +1,50 @@
+"""Where a check's subject can be opened.
+
+A check row carries the subject's id, which is enough to run it but not enough to link to it: a
+view is administered on its DAG node and a synced table on its source's schema page. Both are
+resolved in bulk for a whole page of checks, never per row -- the overview lists every check in the
+project, so a query per row is a query per table in the warehouse.
+"""
+
+from collections.abc import Iterable
+
+from posthog.dataclasses import frozen
+
+from products.data_modeling.backend.facade import api as data_modeling_facade
+from products.warehouse_sources.backend.facade import api as warehouse_facade
+
+from ..facade.enums import SubjectType
+from ..models import DataQualityCheck
+
+
+@frozen
+class SubjectKey:
+ """What identifies a subject across types. Both parts are strings, so they are never positional."""
+
+ subject_type: SubjectType
+ subject_uuid: str
+
+
+@frozen
+class SubjectLocation:
+ """The ids a subject's detail route needs. All absent when the subject has no such page."""
+
+ node_id: str | None = None
+ source_id: str | None = None
+ schema_id: str | None = None
+
+
+def subject_locations(team_id: int, checks: Iterable[DataQualityCheck]) -> dict[SubjectKey, SubjectLocation]:
+ """Two queries for any number of checks."""
+ view_ids = {str(check.saved_query_id) for check in checks if check.saved_query_id}
+ table_ids = {check.table_id for check in checks if check.table_id}
+
+ locations: dict[SubjectKey, SubjectLocation] = {
+ SubjectKey(subject_type=SubjectType.VIEW, subject_uuid=saved_query_id): SubjectLocation(node_id=node_id)
+ for saved_query_id, node_id in data_modeling_facade.get_node_ids_for_saved_queries(team_id, view_ids).items()
+ }
+ for table_id, location in warehouse_facade.source_locations_for_tables(team_id, table_ids).items():
+ locations[SubjectKey(subject_type=SubjectType.TABLE, subject_uuid=str(table_id))] = SubjectLocation(
+ source_id=str(location.source_id), schema_id=str(location.schema_id)
+ )
+ return locations
diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.py
index 3ee0905a0a80..a84fede1eab1 100644
--- a/products/data_quality/backend/logic/runner.py
+++ b/products/data_quality/backend/logic/runner.py
@@ -137,17 +137,18 @@ def _authorize(check: DataQualityCheck, suite_run: DataQualitySuiteRun) -> _Auth
- Automated runs (materialization, source sync) have no initiator. A check constrained to only
its declared subject exposes nothing the definition doesn't already name, so the service
bypass is safe. A check that reads a further subject has no such guarantee, so it executes as
- the check's author; with no author there is nobody to authorize against, and returning
- ``None`` errors the run rather than bypassing the ACL over a subject the author may since
- have lost access to.
+ whoever last authored the definition -- the creator only until someone edits it, since after
+ an edit it is the editor who was authorized against what it now reads. With nobody to
+ authorize against, returning ``None`` errors the run rather than bypassing the ACL.
"""
if suite_run.trigger == SuiteRunTrigger.MANUAL:
return _Authorization(run_as=suite_run.created_by, bypass=suite_run.created_by is None)
if not check_type_reads_beyond_subject(check.check_type):
return _Authorization(run_as=None, bypass=True)
- if check.created_by is None:
+ principal = check.definition_author or check.created_by
+ if principal is None:
return None
- return _Authorization(run_as=check.created_by, bypass=False)
+ return _Authorization(run_as=principal, bypass=False)
def _staged_database(
@@ -327,6 +328,8 @@ def _record_run(
check_type=check.check_type,
check_fingerprint=check.fingerprint,
column_name=check.column_name,
+ check_config=check.config,
+ check_severity=check.severity,
status=outcome.status,
failed_row_count=outcome.failed_row_count,
observed_value=outcome.observed_value,
@@ -341,4 +344,11 @@ def _record_run(
def _update_check(check: DataQualityCheck, outcome: CheckOutcome) -> None:
check.last_status = outcome.status
check.last_run_at = datetime.now(UTC)
- check.save(update_fields=["last_status", "last_run_at", "subject_name", "subject_status", "updated_at"])
+ updated = ["last_status", "last_run_at", "subject_name", "subject_status", "updated_at"]
+ if outcome.status is CheckRunStatus.PASSED:
+ check.last_succeeded_at = check.last_run_at
+ # Written only by the run that earned it. A failing run holds whatever this row said when its
+ # batch loaded it, so listing the column unconditionally would let it overwrite a success a
+ # concurrent run committed in between.
+ updated.append("last_succeeded_at")
+ check.save(update_fields=updated)
diff --git a/products/data_quality/backend/migrations/0002_editable_check_definitions.py b/products/data_quality/backend/migrations/0002_editable_check_definitions.py
new file mode 100644
index 000000000000..7e1a1f9937de
--- /dev/null
+++ b/products/data_quality/backend/migrations/0002_editable_check_definitions.py
@@ -0,0 +1,81 @@
+# Generated by Django 5.2.17 on 2026-08-18 22:41
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_modeling", "0031_datamodelingjob_run_mode"),
+ ("data_quality", "0001_initial"),
+ ("posthog", "1306_add_youtube_analytics_integration_kind"),
+ ("warehouse_sources", "0140_scaffold_samcart_source"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.RemoveConstraint(
+ model_name="dataqualitycheck",
+ name="unique_quality_check_fp_view",
+ ),
+ migrations.RemoveConstraint(
+ model_name="dataqualitycheck",
+ name="unique_quality_check_fp_table",
+ ),
+ migrations.AddField(
+ model_name="dataqualitycheck",
+ name="definition_author",
+ field=models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ help_text="Who last changed what this check asserts. Automated runs authorize as them, falling back to created_by.",
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ migrations.AddField(
+ model_name="dataqualitycheckrun",
+ name="check_config",
+ field=models.JSONField(
+ blank=True,
+ help_text="Canonical config this run executed. Null for runs recorded before snapshots.",
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="dataqualitycheckrun",
+ name="check_severity",
+ field=models.CharField(
+ blank=True,
+ choices=[("error", "error"), ("warn", "warn")],
+ help_text="Severity this run was judged at. Null for runs recorded before snapshots.",
+ max_length=16,
+ null=True,
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="dataqualitycheck",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(
+ ("saved_query__isnull", False),
+ models.Q(("deleted", False), ("deleted__isnull", True), _connector="OR"),
+ ),
+ fields=("team", "saved_query", "fingerprint"),
+ name="unique_quality_check_fp_view",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="dataqualitycheck",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(
+ ("table__isnull", False),
+ models.Q(("deleted", False), ("deleted__isnull", True), _connector="OR"),
+ ),
+ fields=("team", "table", "fingerprint"),
+ name="unique_quality_check_fp_table",
+ ),
+ ),
+ ]
diff --git a/products/data_quality/backend/migrations/0003_dataqualitycheck_last_succeeded_at.py b/products/data_quality/backend/migrations/0003_dataqualitycheck_last_succeeded_at.py
new file mode 100644
index 000000000000..dce0fb2245f8
--- /dev/null
+++ b/products/data_quality/backend/migrations/0003_dataqualitycheck_last_succeeded_at.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.17 on 2026-08-19 18:37
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_quality", "0002_editable_check_definitions"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="dataqualitycheck",
+ name="last_succeeded_at",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="When the check last passed. Null means it has not passed within the run retention window.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/data_quality/backend/migrations/0004_backfill_last_succeeded_at.py b/products/data_quality/backend/migrations/0004_backfill_last_succeeded_at.py
new file mode 100644
index 000000000000..1ce4c1a57be2
--- /dev/null
+++ b/products/data_quality/backend/migrations/0004_backfill_last_succeeded_at.py
@@ -0,0 +1,31 @@
+from django.db import migrations
+from django.db.models import OuterRef, Subquery
+
+
+def backfill_last_succeeded_at(apps, schema_editor):
+ """Read the answer out of run history, which already holds it.
+
+ Without this, every check that is already failing reads as "never passed" until its next
+ success -- the one case where the field matters most. One UPDATE with a correlated subquery
+ over the (quality_check, -created_at) index; checks are authored per table, so the outer table
+ is small.
+ """
+ DataQualityCheck = apps.get_model("data_quality", "DataQualityCheck")
+ DataQualityCheckRun = apps.get_model("data_quality", "DataQualityCheckRun")
+
+ newest_pass = (
+ DataQualityCheckRun.objects.filter(quality_check_id=OuterRef("pk"), status="passed")
+ .order_by("-created_at")
+ .values("created_at")[:1]
+ )
+ DataQualityCheck.objects.update(last_succeeded_at=Subquery(newest_pass))
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_quality", "0003_dataqualitycheck_last_succeeded_at"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_last_succeeded_at, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/data_quality/backend/migrations/0005_free_deleted_check_names.py b/products/data_quality/backend/migrations/0005_free_deleted_check_names.py
new file mode 100644
index 000000000000..d58fa571f9bb
--- /dev/null
+++ b/products/data_quality/backend/migrations/0005_free_deleted_check_names.py
@@ -0,0 +1,32 @@
+# Generated by Django 5.2.17 on 2026-08-20 21:16
+
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_modeling", "0031_datamodelingjob_run_mode"),
+ ("data_quality", "0004_backfill_last_succeeded_at"),
+ ("posthog", "1310_provisioning_rate_limit_overrides"),
+ ("warehouse_sources", "0150_repin_bloomerang_api_version"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.RemoveConstraint(
+ model_name="dataqualitycheck",
+ name="unique_quality_check_name_per_team",
+ ),
+ migrations.AddConstraint(
+ model_name="dataqualitycheck",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(
+ models.Q(("name", ""), _negated=True),
+ models.Q(("deleted", False), ("deleted__isnull", True), _connector="OR"),
+ ),
+ fields=("team", "name"),
+ name="unique_quality_check_name_per_team",
+ ),
+ ),
+ ]
diff --git a/products/data_quality/backend/migrations/max_migration.txt b/products/data_quality/backend/migrations/max_migration.txt
index cbab66dde92a..20e6e6a0e758 100644
--- a/products/data_quality/backend/migrations/max_migration.txt
+++ b/products/data_quality/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0005_free_deleted_check_names
diff --git a/products/data_quality/backend/models/check.py b/products/data_quality/backend/models/check.py
index aa10af6333fb..b7dadcbd5603 100644
--- a/products/data_quality/backend/models/check.py
+++ b/products/data_quality/backend/models/check.py
@@ -17,6 +17,9 @@ CHECK_NAME_REGEX = r"^[A-Za-z][A-Za-z0-9_]*$"
SUBJECT_STATUS_FIELD = "subject_status"
+# `deleted` is nullable, so "not deleted" has to name the null case too.
+ACTIVE = models.Q(deleted=False) | models.Q(deleted__isnull=True)
+
validate_check_name = RegexValidator(
regex=CHECK_NAME_REGEX,
message="Name must start with a letter and contain only letters, numbers, and underscores.",
@@ -52,8 +55,9 @@ class DataQualityCheck(
A check passes when its compiled query finds zero failing rows. The definition is the source of
truth here; ``fingerprint`` makes agent authoring idempotent (re-creating a semantically
- identical check upserts instead of duplicating), and it is also the stable identity a git-synced
- config file would round-trip against.
+ identical *active* check upserts instead of duplicating), and it is also the stable identity a
+ git-synced config file would round-trip against. Editing the assertion recomputes it in place:
+ the check keeps its id, history, and latest status.
The subject is one of two foreign keys -- ``saved_query`` (views and matviews) or ``table``
(warehouse source tables) -- and never both. The data modeling Node for a subject is resolved at
@@ -77,6 +81,16 @@ class DataQualityCheck(
created_by = models.ForeignKey(
"posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"
)
+ definition_author = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ help_text="Who last changed what this check asserts. Automated runs authorize as them, "
+ "falling back to created_by.",
+ )
owner = models.ForeignKey(
"posthog.User",
on_delete=models.SET_NULL,
@@ -161,6 +175,13 @@ class DataQualityCheck(
blank=True,
help_text="Outcome of the newest run, denormalized so health rollups stay a single read.",
)
+ # Denormalized for the same reason as last_status: "failing since when" is the first question a
+ # failing check raises, and the answer can be older than any page of run history.
+ last_succeeded_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="When the check last passed. Null means it has not passed within the run retention window.",
+ )
fingerprint = models.CharField(
max_length=64,
@@ -189,21 +210,25 @@ class DataQualityCheck(
& ~models.Q(table__isnull=False, subject_type=SubjectType.VIEW)
),
),
- # Partial per FK: orphaned checks (both FKs null) are exempt on purpose.
+ # Partial per FK: orphaned checks (both FKs null) are exempt on purpose, and so are
+ # soft-deleted ones -- a deleted definition may be authored again, as a new check with
+ # its own id and history, rather than resurrecting the row that was deleted.
models.UniqueConstraint(
fields=["team", "saved_query", "fingerprint"],
- condition=models.Q(saved_query__isnull=False),
+ condition=models.Q(saved_query__isnull=False) & ACTIVE,
name="unique_quality_check_fp_view",
),
models.UniqueConstraint(
fields=["team", "table", "fingerprint"],
- condition=models.Q(table__isnull=False),
+ condition=models.Q(table__isnull=False) & ACTIVE,
name="unique_quality_check_fp_table",
),
- # Partial: a blank name is the "address me by id" case, and many checks share it.
+ # Partial on both counts: a blank name is the "address me by id" case, which many checks
+ # share, and a deleted check keeps its name only as history -- holding the name against a
+ # new check would make a delete irreversible for anyone who wants that name back.
models.UniqueConstraint(
fields=["team", "name"],
- condition=~models.Q(name=""),
+ condition=~models.Q(name="") & ACTIVE,
name="unique_quality_check_name_per_team",
),
]
diff --git a/products/data_quality/backend/models/check_run.py b/products/data_quality/backend/models/check_run.py
index fc080776333d..e36f517b9ca6 100644
--- a/products/data_quality/backend/models/check_run.py
+++ b/products/data_quality/backend/models/check_run.py
@@ -3,7 +3,7 @@ from django.db import models
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
-from ..facade.enums import CheckRunStatus, SubjectType, SuiteRunStatus, SuiteRunTrigger
+from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectType, SuiteRunStatus, SuiteRunTrigger
class DataQualitySuiteRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):
@@ -104,6 +104,19 @@ class DataQualityCheckRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFie
check_type = models.CharField(max_length=32)
check_fingerprint = models.CharField(max_length=64)
column_name = models.CharField(max_length=400, blank=True)
+ # Null means "recorded before runs snapshotted this", never "same as the check has now": a
+ # definition can be edited after the fact, so borrowing the current values would misreport
+ # what actually ran.
+ check_config = models.JSONField(
+ null=True, blank=True, help_text="Canonical config this run executed. Null for runs recorded before snapshots."
+ )
+ check_severity = models.CharField(
+ max_length=16,
+ choices=[(s.value, s.value) for s in CheckSeverity],
+ null=True,
+ blank=True,
+ help_text="Severity this run was judged at. Null for runs recorded before snapshots.",
+ )
status = models.CharField(max_length=16, choices=[(s.value, s.value) for s in CheckRunStatus])
failed_row_count = models.BigIntegerField(
diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.py
index fa90c034f098..626bc3c92a84 100644
--- a/products/data_quality/backend/presentation/serializers.py
+++ b/products/data_quality/backend/presentation/serializers.py
@@ -8,6 +8,7 @@ union: a new check type must not need a serializer change.
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field, extend_schema_serializer
from rest_framework import serializers
+from rest_framework.exceptions import ErrorDetail
from posthog.api.shared import UserBasicSerializer
@@ -60,6 +61,12 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):
read_only=True,
help_text="Outcome of the newest run: passed, failed, errored, skipped, or empty if never run.",
)
+ last_succeeded_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="When the check last passed, so a failing check can say how long it has been failing. "
+ "Null means it has not passed within the run retention window.",
+ )
subject_status = serializers.CharField(
read_only=True,
help_text="'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted.",
@@ -86,6 +93,7 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):
"owner",
"last_run_at",
"last_status",
+ "last_succeeded_at",
"fingerprint",
"created_source",
"ai_model",
@@ -101,6 +109,7 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):
"subject_status",
"last_run_at",
"last_status",
+ "last_succeeded_at",
"fingerprint",
"created_by",
"created_at",
@@ -139,26 +148,7 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):
def get_subject_uuid(self, obj: DataQualityCheck) -> str | None:
return str(obj.subject_uuid) if obj.subject_uuid else None
- # The assertion is the check's identity: it is what the fingerprint hashes and what the runner
- # compiles. Editing it in place would leave a fingerprint describing a different check, so
- # subsequent identical creates would duplicate instead of upserting. Re-create instead. The
- # subject needs no entry: it comes from the URL, and moving a check means re-creating it there.
- IMMUTABLE_AFTER_CREATE = ("check_type", "column_name", "config")
-
def validate(self, attrs: dict) -> dict:
- if self.instance is not None:
- changed = [
- field
- for field in self.IMMUTABLE_AFTER_CREATE
- if field in attrs and attrs[field] != getattr(self.instance, field)
- ]
- if changed:
- raise serializers.ValidationError(
- dict.fromkeys(
- changed, "A check's assertion cannot be edited. Create a new check and delete this one."
- )
- )
-
def resolved(field: str) -> str:
return attrs.get(field) or getattr(self.instance, field, None) or ""
@@ -179,11 +169,66 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):
return attrs
def update(self, instance: DataQualityCheck, validated_data: dict) -> DataQualityCheck:
- # Routed through update_check so writes stay restricted to the mutable field allowlist.
- name = validated_data.get("name")
- if name and name != instance.name:
- api.ensure_name_available(instance.team_id, name, exclude_id=instance.id)
- return api.update_check(instance, **validated_data)
+ request = self.context.get("request")
+ try:
+ return api.edit_check(
+ team=self.context["get_team"](),
+ check=instance,
+ editor=getattr(request, "user", None) if request else None,
+ **validated_data,
+ )
+ except api.CheckEditConflict as conflict:
+ # Rendered beside the offending fields rather than as a status code, so the editor can
+ # keep the draft open and point at what to change.
+ raise serializers.ValidationError(
+ {field: ErrorDetail(str(conflict), code=conflict.code) for field in conflict.fields}
+ )
+
+
+@extend_schema_serializer(component_name="DataQualityOverviewCheck")
+class DataQualityOverviewCheckSerializer(DataQualityCheckSerializer):
+ """A check plus where its subject can be opened, for the project-wide list.
+
+ The per-subject surfaces already know their parent; only this one lists checks across every
+ table and view, so only this one needs to say where each subject lives. The ids are resolved
+ for a whole page at once and handed in through ``subject_locations`` in the context.
+ """
+
+ subject_node_id = serializers.SerializerMethodField(
+ help_text="Data modeling node of the view this check audits, or null when it is on no DAG "
+ "or the subject is a table."
+ )
+ subject_source_id = serializers.SerializerMethodField(
+ help_text="Warehouse source of the table this check audits, or null when the subject is a view."
+ )
+ subject_schema_id = serializers.SerializerMethodField(
+ help_text="Warehouse source schema of the table this check audits, or null when the subject is a view."
+ )
+
+ class Meta(DataQualityCheckSerializer.Meta):
+ fields = [
+ *DataQualityCheckSerializer.Meta.fields,
+ "subject_node_id",
+ "subject_source_id",
+ "subject_schema_id",
+ ]
+
+ def _location(self, obj: DataQualityCheck) -> api.SubjectLocation:
+ locations: dict[api.SubjectKey, api.SubjectLocation] = self.context.get("subject_locations") or {}
+ key = api.SubjectKey(subject_type=SubjectType(obj.subject_type), subject_uuid=str(obj.subject_uuid))
+ return locations.get(key) or api.SubjectLocation()
+
+ @extend_schema_field(serializers.UUIDField(allow_null=True))
+ def get_subject_node_id(self, obj: DataQualityCheck) -> str | None:
+ return self._location(obj).node_id
+
+ @extend_schema_field(serializers.UUIDField(allow_null=True))
+ def get_subject_source_id(self, obj: DataQualityCheck) -> str | None:
+ return self._location(obj).source_id
+
+ @extend_schema_field(serializers.UUIDField(allow_null=True))
+ def get_subject_schema_id(self, obj: DataQualityCheck) -> str | None:
+ return self._location(obj).schema_id
@extend_schema_serializer(component_name="DataQualityCheckRun")
@@ -196,6 +241,18 @@ class DataQualityCheckRunSerializer(serializers.ModelSerializer):
read_only=True,
help_text="Which assertion this run made.",
)
+ check_config = CheckConfigField(
+ read_only=True,
+ allow_null=True,
+ help_text="Config this run executed, snapshotted so an edit to the check cannot rewrite history. "
+ "Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.",
+ )
+ check_severity = serializers.ChoiceField(
+ choices=[(s.value, s.value) for s in CheckSeverity],
+ read_only=True,
+ allow_null=True,
+ help_text="Severity this run was judged at. Null for runs recorded before snapshots existed.",
+ )
class Meta:
model = DataQualityCheckRun
@@ -208,6 +265,8 @@ class DataQualityCheckRunSerializer(serializers.ModelSerializer):
"subject_name",
"check_type",
"column_name",
+ "check_config",
+ "check_severity",
"status",
"failed_row_count",
"observed_value",
@@ -279,6 +338,17 @@ class SubjectHealthSerializer(serializers.Serializer):
checks_failing = serializers.IntegerField(help_text="How many of those checks last reported a failure.")
+@extend_schema_serializer(component_name="DataQualityRunRequest")
+class DataQualityRunRequestSerializer(serializers.Serializer):
+ """What to run in a project-wide suite run."""
+
+ check_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ required=False,
+ help_text="Ids of the checks to run. Omit to run every enabled check in the project.",
+ )
+
+
@extend_schema_serializer(component_name="DataQualityGateConfig")
class DataQualityGateConfigSerializer(serializers.Serializer):
"""The team-level materialization gate. Checks always run and warn; this only toggles blocking."""
diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.py
index d4e1cd6c2379..af09e1c8607d 100644
--- a/products/data_quality/backend/presentation/views.py
+++ b/products/data_quality/backend/presentation/views.py
@@ -7,8 +7,11 @@ serialize the result. Nothing here runs a check -- every trigger hands off to Te
a suite-run handle to poll.
"""
+import json
+from collections import defaultdict
from collections.abc import Callable
from typing import ClassVar, cast
+from uuid import UUID
from django.db.models import QuerySet
@@ -19,6 +22,7 @@ from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import SAFE_METHODS
from rest_framework.request import Request
from rest_framework.response import Response
+from rest_framework.serializers import BaseSerializer
from rest_framework.views import APIView
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -29,7 +33,7 @@ from posthog.models import Team, User
from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
from ..facade import api
-from ..facade.enums import CheckRunStatus, SubjectType
+from ..facade.enums import CheckRunStatus, SubjectStatus, SubjectType
from ..facade.flags import is_data_quality_checks_enabled
from ..facade.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
from .serializers import (
@@ -37,6 +41,8 @@ from .serializers import (
DataQualityCheckRunSerializer,
DataQualityCheckSerializer,
DataQualityGateConfigSerializer,
+ DataQualityOverviewCheckSerializer,
+ DataQualityRunRequestSerializer,
DataQualitySuiteRunSerializer,
SubjectHealthSerializer,
)
@@ -44,31 +50,25 @@ from .serializers import (
_RECENT_RUNS_LIMIT = 50
-class _SubjectScopedViewSet(TeamAndOrgViewSetMixin):
- """Shared plumbing for viewsets nested under a warehouse saved query or table.
+class _QualityGatedViewSet(TeamAndOrgViewSetMixin):
+ """The gating every data quality surface shares, whether or not it is nested under a subject.
- Every entry point is gated on the product flag and on access to the parent subject -- the same
- name-based denial the information_schema loaders read, so REST and SQL can never disagree about
- which subjects a member may see. Most actions additionally require query access: run results are
- a count oracle over the underlying rows, so a member denied `query` must not reach them through
- a check. Only the check-type *catalog* stays ungated by query: static schema metadata.
+ Entry points are gated on the product flag, and most additionally on query access: run results
+ are a count oracle over the underlying rows, so a member denied `query` must not reach them
+ through a check. Only the check-type *catalog* stays ungated by query: static schema metadata.
+
+ Denial is name-based, reading the same set the information_schema loaders do, so REST and SQL
+ can never disagree about which subjects a member may see.
"""
team: Team
- subject_type: ClassVar[SubjectType]
- subject_field: ClassVar[str]
QUERY_GATED_ACTIONS: ClassVar[frozenset[str]] = frozenset()
- @property
- def subject_uuid(self) -> str:
- return str(self.parents_query_dict[f"{self.subject_field}_id"])
-
def initial(self, request: Request, *args, **kwargs) -> None:
super().initial(request, *args, **kwargs)
self._require_flag()
if getattr(self, "action", None) in self.QUERY_GATED_ACTIONS:
self._require_query_access()
- self._require_parent_subject_access()
def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:
# Token callers carry scopes but no RBAC, so the query gate has to be a scope for them.
@@ -89,27 +89,6 @@ class _SubjectScopedViewSet(TeamAndOrgViewSetMixin):
if not self.user_access_control.check_access_level_for_resource("query", "viewer"):
raise PermissionDenied("You need query access to work with data quality checks.")
- def _require_parent_subject_access(self) -> None:
- """403 a denied parent -- for every action, including list.
-
- A member denied a view must not be able to enumerate its check configs or counts through
- this surface. Orphan-tolerant rather than 404ing: a parent that no longer resolves still
- serves its checks (they are skipped, not hidden), because resolution carries no RBAC to
- enforce and orphaned history must stay reachable -- but only for a caller who cannot be
- object-denied, since an orphan has no name left to check a denial against.
- """
- ref = api.resolve_subject(self.team.id, self.subject_type, self.subject_uuid)
- if not ref.exists:
- # Deleting the subject takes its denial with it: the orphan resolves to an empty name,
- # and the denial set is rebuilt from the subjects that still exist, so neither can show
- # the caller was allowed this one. Without that proof, only a caller who cannot be
- # object-denied keeps orphan access.
- if self._can_be_object_denied():
- raise PermissionDenied("You don't have access to this table or view.")
- return
- if api.is_subject_denied(ref.name, self._denied_subject_names()):
- raise PermissionDenied("You don't have access to this table or view.")
-
def _can_be_object_denied(self) -> bool:
"""Whether object-level warehouse denials can apply to this caller at all.
@@ -143,19 +122,101 @@ class _SubjectScopedViewSet(TeamAndOrgViewSetMixin):
self._denied_subjects_cache = cached
return cached
+ def _reads_denied_subject(self, check_type: str, config: dict, denied: set[str]) -> bool:
+ """Whether this definition reads a subject the caller is denied.
+
+ The parent is not the only subject a check reads: a relationships check names a second
+ subject and a custom_sql query selects arbitrary tables, both run by the worker with team
+ scope only. Authorize them too, or a check on an allowed subject is a count oracle over a
+ denied one.
+ """
+ return any(
+ api.is_subject_denied(name, denied)
+ for name in api.referenced_subject_names(self.team.id, check_type, config)
+ )
+
def _require_referenced_subject_access(self, check_type: str, config: dict) -> None:
- # The parent is not the only subject a check reads: a relationships check names a second
- # subject and a custom_sql query selects arbitrary tables, both run by the worker with team
- # scope only. Authorize them too, or a check on an allowed subject is a count oracle over a
- # denied one.
denied = self._denied_subject_names()
if not denied:
return
- for name in api.referenced_subject_names(self.team.id, check_type, config):
- if api.is_subject_denied(name, denied):
- raise PermissionDenied("You don't have access to a table or view this check reads.")
+ if self._reads_denied_subject(check_type, config, denied):
+ raise PermissionDenied("You don't have access to a table or view this check reads.")
+ def _readable_runs(self, runs: list[DataQualityCheckRun]) -> list[DataQualityCheckRun]:
+ """Drop the runs whose definition read a subject the caller is denied.
+
+ Judged from the definition each run executed, not the one its check carries now, so editing
+ a check cannot retroactively expose or hide its history. Runs older than the config snapshot
+ fall back to their check; one that predates it and has lost its check is withheld, since what
+ it read cannot be established.
+ """
+ denied = self._denied_subject_names()
+ if not denied:
+ return runs
+ verdicts: dict[str, bool] = {}
+ readable = []
+ for run in runs:
+ config = run.check_config if run.check_config is not None else getattr(run.quality_check, "config", None)
+ if config is None:
+ continue
+ # One verdict per definition: a suite re-runs the same checks, and resolving a
+ # relationships target costs a query.
+ cache_key = f"{run.check_type}:{json.dumps(config, sort_keys=True, default=str)}"
+ if cache_key not in verdicts:
+ verdicts[cache_key] = self._reads_denied_subject(run.check_type, config, denied)
+ if not verdicts[cache_key]:
+ readable.append(run)
+ return readable
+
+
+class _SubjectScopedViewSet(_QualityGatedViewSet):
+ """Adds the parent-subject gate for viewsets nested under a warehouse saved query or table."""
+
+ subject_type: ClassVar[SubjectType]
+ subject_field: ClassVar[str]
+
+ @property
+ def subject_uuid(self) -> str:
+ return str(self.parents_query_dict[f"{self.subject_field}_id"])
+
+ def initial(self, request: Request, *args, **kwargs) -> None:
+ super().initial(request, *args, **kwargs)
+ self._require_parent_subject_access()
+
+ def _require_parent_subject_access(self) -> None:
+ """403 a denied parent -- for every action, including list.
+
+ A member denied a view must not be able to enumerate its check configs or counts through
+ this surface. Orphan-tolerant rather than 404ing: a parent that no longer resolves still
+ serves its checks (they are skipped, not hidden), because resolution carries no RBAC to
+ enforce and orphaned history must stay reachable -- but only for a caller who cannot be
+ object-denied, since an orphan has no name left to check a denial against.
+ """
+ ref = api.resolve_subject(self.team.id, self.subject_type, self.subject_uuid)
+ if not ref.exists:
+ # Deleting the subject takes its denial with it: the orphan resolves to an empty name,
+ # and the denial set is rebuilt from the subjects that still exist, so neither can show
+ # the caller was allowed this one. Without that proof, only a caller who cannot be
+ # object-denied keeps orphan access.
+ if self._can_be_object_denied():
+ raise PermissionDenied("You don't have access to this table or view.")
+ return
+ if api.is_subject_denied(ref.name, self._denied_subject_names()):
+ raise PermissionDenied("You don't have access to this table or view.")
+
+_EDIT_DESCRIPTION = (
+ "Edit this check in place, including what it asserts (check_type, column_name, config). The "
+ "table or view it audits is fixed, and the check keeps its id, run history, latest status, and "
+ "latest run time. A definition or name already held by another active check comes back as a "
+ "field error, with nothing written."
+)
+
+
+@extend_schema_view(
+ update=extend_schema(description=_EDIT_DESCRIPTION),
+ partial_update=extend_schema(description=_EDIT_DESCRIPTION),
+)
class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsets.ModelViewSet):
"""CRUD for one subject's checks, plus the actions that run them and report on them."""
@@ -219,6 +280,17 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse
status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,
)
+ def perform_update(self, serializer: BaseSerializer) -> None:
+ # The candidate definition, not the stored one: an edit that points the check at a new
+ # relationships target or rewrites its custom SQL has to clear that subject too, before it
+ # is saved and the worker starts running it.
+ check = cast(DataQualityCheck, serializer.instance)
+ data = serializer.validated_data
+ self._require_referenced_subject_access(
+ data.get("check_type", check.check_type), data.get("config", check.config) or {}
+ )
+ serializer.save()
+
def perform_destroy(self, instance: DataQualityCheck) -> None:
api.soft_delete_check(instance)
@@ -273,9 +345,16 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse
@action(methods=["GET"], detail=True, pagination_class=None)
def runs(self, request: Request, **kwargs) -> Response:
check = self.get_object()
+ # The current definition gates the check itself; each run is then judged on the definition
+ # it executed, so editing a check into a harmless one does not unlock what it used to read.
self._require_referenced_subject_access(check.check_type, check.config)
- runs = DataQualityCheckRun.objects.for_team(self.team_id).filter(quality_check=check).order_by("-created_at")
- return Response(DataQualityCheckRunSerializer(runs[:_RECENT_RUNS_LIMIT], many=True).data)
+ runs = list(
+ DataQualityCheckRun.objects.for_team(self.team_id)
+ .filter(quality_check=check)
+ .select_related("quality_check")
+ .order_by("-created_at")[:_RECENT_RUNS_LIMIT]
+ )
+ return Response(DataQualityCheckRunSerializer(self._readable_runs(runs), many=True).data)
@extend_schema(
description="Health rollup for this table or view, from the denormalized status of its checks.",
@@ -372,6 +451,204 @@ class TableSuiteRunViewSet(_BaseSuiteRunViewSet):
filter_rewrite_rules = {"table_id": "subject_uuid"}
+class DataQualityCheckOverviewViewSet(
+ _QualityGatedViewSet,
+ AccessControlViewSetMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Every check in the project, and the health of every subject that has one.
+
+ The per-subject surfaces answer "what is wrong with this table". This answers "what is wrong
+ across the project", which they cannot: each is nested under one parent. Read-only -- authoring
+ still happens against the subject that owns the check.
+ """
+
+ QUERY_GATED_ACTIONS = frozenset({"list", "health"})
+ scope_object = "warehouse_objects"
+ serializer_class = DataQualityOverviewCheckSerializer
+ queryset = DataQualityCheck.objects.unscoped()
+ _subject_locations: dict[api.SubjectKey, api.SubjectLocation] = {}
+
+ def safely_get_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:
+ # Orphans are excluded: their subject is gone, so there is no page to link to, nothing to
+ # run, and no rollup to sit under. The run history they left behind stays queryable.
+ return (
+ queryset.filter(team_id=self.team_id, deleted=False)
+ .exclude(subject_status=SubjectStatus.ORPHANED)
+ .order_by("subject_name", "name")
+ )
+
+ def get_serializer_context(self) -> dict:
+ return {**super().get_serializer_context(), "subject_locations": self._subject_locations}
+
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ queryset = self.filter_queryset(self.get_queryset())
+ page = self.paginate_queryset(queryset)
+ checks = list(queryset) if page is None else page
+ # Resolved once for the page, so linking to a subject costs two queries rather than one per
+ # check. Anything the batch cannot resolve stays absent and renders as plain text.
+ self._subject_locations = api.subject_locations(self.team_id, checks)
+ serializer = self.get_serializer(checks, many=True)
+ return self.get_paginated_response(serializer.data) if page is not None else Response(serializer.data)
+
+ def filter_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:
+ # Hiding a denied subject's checks matters more here than on the nested surfaces: this one
+ # lists everything, so a leak is a directory of the tables a member cannot read. Denial is
+ # matched by name rather than equality, so the pass has to happen in Python; only a
+ # restricted member pays for it, since the denied set is empty for everyone else.
+ queryset = super().filter_queryset(queryset)
+ denied = self._denied_subject_names()
+ if not denied:
+ return queryset
+ hidden = [check.id for check in queryset if api.is_subject_denied(check.subject_name, denied)]
+ return queryset.exclude(id__in=hidden)
+
+ @extend_schema(
+ description="Health rollup for every table and view in the project that has checks.",
+ responses={200: SubjectHealthSerializer(many=True)},
+ )
+ @action(methods=["GET"], detail=False, pagination_class=None)
+ def health(self, request: Request, **kwargs) -> Response:
+ # Rolled up from the checks already loaded, using the same rule as the per-subject endpoint.
+ # Calling subject_health() per subject would be a query per table.
+ by_subject: dict[tuple[str, str], list[DataQualityCheck]] = defaultdict(list)
+ for check in self.filter_queryset(self.get_queryset()).filter(enabled=True):
+ if check.subject_uuid is None:
+ # An orphan has no subject left to roll up under.
+ continue
+ by_subject[(check.subject_type, str(check.subject_uuid))].append(check)
+
+ rollups = [
+ {
+ "subject_type": subject_type,
+ "subject_uuid": subject_uuid,
+ "health": api.roll_up_health(
+ api.CheckStatusRow(severity=check.severity, last_status=check.last_status) for check in checks
+ ),
+ "checks_total": len(checks),
+ "checks_failing": sum(1 for check in checks if check.last_status == CheckRunStatus.FAILED),
+ }
+ for (subject_type, subject_uuid), checks in by_subject.items()
+ ]
+ return Response(SubjectHealthSerializer(rollups, many=True).data)
+
+
+class DataQualityRunViewSet(
+ _QualityGatedViewSet,
+ AccessControlViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Project-wide check runs: start one over a selection, and read every run the project has had.
+
+ The per-subject surfaces only serve runs scoped to their own subject, so this is where a sweep
+ across several subjects -- a manual project-wide run, a materialization, a source sync -- is
+ readable. Scoped to `warehouse_objects` because it spans tables and views at once.
+ """
+
+ QUERY_GATED_ACTIONS = frozenset({"list", "retrieve", "create"})
+ scope_object = "warehouse_objects"
+ serializer_class = DataQualitySuiteRunSerializer
+ queryset = DataQualitySuiteRun.objects.unscoped()
+
+ def safely_get_queryset(self, queryset: QuerySet[DataQualitySuiteRun]) -> QuerySet[DataQualitySuiteRun]:
+ return queryset.filter(team_id=self.team_id).order_by("-created_at")
+
+ def filter_queryset(self, queryset: QuerySet[DataQualitySuiteRun]) -> QuerySet[DataQualitySuiteRun]:
+ """Withhold the suites that report on a subject the caller is denied.
+
+ A suite row carries its subject and its passed/failed/errored/skipped counters, so serving
+ one is serving outcome counts over the rows behind it. The nested suite lists are gated by
+ their parent; this one spans every subject and has no parent to gate on. Excluded in SQL
+ rather than filtered per page, so the paginated count cannot report the withheld suites
+ either.
+ """
+ queryset = super().filter_queryset(queryset)
+ denied_uuids = self._denied_subject_uuids()
+ if not denied_uuids:
+ return queryset
+ covering_denied = (
+ DataQualityCheckRun.objects.for_team(self.team_id)
+ .filter(subject_uuid__in=denied_uuids)
+ .values("suite_run_id")
+ )
+ return queryset.exclude(subject_uuid__in=denied_uuids).exclude(id__in=covering_denied)
+
+ def _denied_subject_uuids(self) -> set[UUID]:
+ """The ids of the subjects this caller is denied, as suite and check runs record them.
+
+ Read from the names already denormalized onto checks and their runs rather than resolved one
+ subject at a time, so a restricted member's page costs two queries instead of one per
+ subject. That inherits the denormalized name's rename window, which every check-list surface
+ shares.
+ """
+ denied = self._denied_subject_names()
+ if not denied:
+ return set()
+ checks = DataQualityCheck.objects.for_team(self.team_id).values_list(
+ "saved_query_id", "table_id", "subject_name"
+ )
+ named_subjects = [(saved_query_id or table_id, name) for saved_query_id, table_id, name in checks]
+ # A hard-deleted check leaves its runs behind with the FK nulled, so its subject would drop
+ # out of the set above while its suites still report on it.
+ named_subjects += (
+ DataQualityCheckRun.objects.for_team(self.team_id)
+ .filter(quality_check__isnull=True)
+ .values_list("subject_uuid", "subject_name")
+ .distinct()
+ )
+ return {uuid for uuid, name in named_subjects if uuid and api.is_subject_denied(name, denied)}
+
+ @extend_schema(
+ description="Run the named checks now, or every enabled check in the project when none are named. "
+ "Returns the suite run to poll for the report.",
+ request=DataQualityRunRequestSerializer,
+ responses={200: DataQualitySuiteRunSerializer},
+ )
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = DataQualityRunRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ requested = [str(check_id) for check_id in serializer.validated_data.get("check_ids") or []]
+
+ runnable = DataQualityCheck.objects.for_team(self.team_id).filter(deleted=False, enabled=True)
+ if requested:
+ runnable = runnable.filter(id__in=requested)
+ checks = self._authorized_checks(list(runnable), named=bool(requested))
+ if not checks:
+ # An empty selection cannot be handed to the worker: it reads as no selector at all and
+ # would sweep the project, which is the opposite of what the caller may run.
+ suite_run = api.empty_check_suite(team=self.team, user=cast(User, request.user))
+ else:
+ suite_run = api.start_check_suite(
+ team=self.team,
+ user=cast(User, request.user),
+ check_ids=[str(check.id) for check in checks],
+ )
+ return Response(DataQualitySuiteRunSerializer(suite_run).data)
+
+ def _authorized_checks(self, checks: list[DataQualityCheck], named: bool) -> list[DataQualityCheck]:
+ """Drop, or reject, the checks this member may not run.
+
+ Naming a denied check is an attempt to read it, so it 403s the way the per-subject run does.
+ Sweeping the project is not: a denied subject is one the member cannot see at all, so its
+ checks are simply not part of "everything" for them.
+ """
+ denied = self._denied_subject_names()
+ if not denied:
+ return checks
+ allowed = []
+ for check in checks:
+ if api.is_subject_denied(check.subject_name, denied):
+ if named:
+ raise PermissionDenied("You don't have access to a table or view this check reads.")
+ continue
+ self._require_referenced_subject_access(check.check_type, check.config)
+ allowed.append(check)
+ return allowed
+
+
def data_quality_gate_response(team: Team, request: Request) -> Response:
"""GET/PATCH handler for the team's gate setting, mounted on the warehouse viewset.
diff --git a/products/data_quality/backend/routes.py b/products/data_quality/backend/routes.py
new file mode 100644
index 000000000000..034d3e730301
--- /dev/null
+++ b/products/data_quality/backend/routes.py
@@ -0,0 +1,12 @@
+from posthog.api.routing import RouterRegistry
+
+from products.data_quality.backend.presentation.views import DataQualityCheckOverviewViewSet, DataQualityRunViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ # The per-subject check surfaces are nested under their warehouse parent and registered by the
+ # data_warehouse product. This one spans every subject, so it hangs off the project directly.
+ routers.projects.register(
+ r"data_quality_checks", DataQualityCheckOverviewViewSet, "project_data_quality_checks", ["team_id"]
+ )
+ routers.projects.register(r"data_quality_runs", DataQualityRunViewSet, "project_data_quality_runs", ["team_id"])
diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.py
index b8ccb0781d0c..e6df73f35c97 100644
--- a/products/data_quality/backend/tests/test_api.py
+++ b/products/data_quality/backend/tests/test_api.py
@@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.core.cache import cache
from django.test import SimpleTestCase
+from django.utils.timezone import now
from parameterized import parameterized
from rest_framework import status
@@ -82,8 +83,8 @@ class TestDataQualityCheckAPI(APIBaseTest):
**overrides,
}
- def _create_check(self, **overrides) -> DataQualityCheck:
- response = self.client.post(f"{self.url}/", self._payload(**overrides))
+ def _create_check(self, url: str | None = None, **overrides) -> DataQualityCheck:
+ response = self.client.post(f"{url or self.url}/", self._payload(**overrides))
assert response.status_code == status.HTTP_201_CREATED, response.json()
return DataQualityCheck.objects.for_team(self.team.id).get(id=response.json()["id"])
@@ -174,22 +175,149 @@ class TestDataQualityCheckAPI(APIBaseTest):
assert again.status_code == status.HTTP_200_OK
assert again.json()["id"] == created.json()["id"]
- @parameterized.expand([("check_type",), ("column_name",), ("config",)])
- def test_the_assertion_cannot_be_edited_in_place(self, field: str) -> None:
- # Editing it would leave the fingerprint describing a different check, so later identical
- # creates would duplicate instead of upserting.
+ @parameterized.expand(
+ [
+ ("view", "type", {"check_type": CheckType.UNIQUE}),
+ ("view", "column", {"column_name": "total"}),
+ (
+ "view",
+ "config",
+ {"check_type": CheckType.ACCEPTED_VALUES, "config": {"values": ["paid", "refunded"]}},
+ ),
+ (
+ "view",
+ "custom_sql",
+ {"check_type": CheckType.CUSTOM_SQL, "column_name": "", "config": {"query": "SELECT 1"}},
+ ),
+ ("table", "type", {"check_type": CheckType.UNIQUE}),
+ ("table", "config", {"check_type": CheckType.ROW_COUNT, "column_name": "", "config": {"min": 1}}),
+ ]
+ )
+ def test_editing_the_assertion_keeps_the_check_identity(self, kind: str, _case: str, edit: dict) -> None:
+ url = self.url if kind == "view" else self._table_checks_url()
+ check = self._create_check(url=url)
+ ran_at = now()
+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(
+ last_status=CheckRunStatus.FAILED, last_run_at=ran_at
+ )
+
+ response = self.client.patch(f"{url}/{check.id}/", edit)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["id"] == str(check.id)
+ assert body["last_status"] == CheckRunStatus.FAILED
+ assert body["last_run_at"] is not None
+ assert body["fingerprint"] != check.fingerprint
+ check.refresh_from_db()
+ assert check.check_type == edit.get("check_type", check.check_type)
+ assert check.column_name == edit.get("column_name", check.column_name)
+ assert edit.get("config", {}).items() <= check.config.items()
+ assert check.created_by == self.user
+ assert check.last_run_at == ran_at
+
+ def test_a_metadata_edit_leaves_the_definition_and_its_author_alone(self) -> None:
+ check = self._create_check()
+
+ response = self.client.patch(f"{self.url}/{check.id}/", {"description": "why this matters", "tags": ["core"]})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ check.refresh_from_db()
+ assert check.description == "why this matters"
+ assert check.fingerprint == response.json()["fingerprint"]
+ assert check.definition_author is None
+
+ def test_editing_the_assertion_records_who_authorized_it(self) -> None:
+ # Automated runs of a check that reads beyond its subject execute as this user, so it has to
+ # be whoever last changed what the check reads, not whoever created it.
check = self._create_check()
- new_value = {
- "check_type": CheckType.UNIQUE,
- "column_name": "total",
- "config": {"values": ["a"]},
- }[field]
- response = self.client.patch(f"{self.url}/{check.id}/", {field: new_value})
+ self.client.patch(f"{self.url}/{check.id}/", {"check_type": CheckType.UNIQUE})
+
+ check.refresh_from_db()
+ assert check.definition_author == self.user
+
+ def test_editing_into_another_active_definition_writes_nothing(self) -> None:
+ taken = self._create_check(check_type=CheckType.UNIQUE, name="orders_customer_id_unique")
+ check = self._create_check(column_name="total")
+
+ response = self.client.patch(
+ f"{self.url}/{check.id}/",
+ {"check_type": CheckType.UNIQUE, "column_name": "customer_id", "description": "not saved either"},
+ )
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "duplicate_definition"
check.refresh_from_db()
- assert str(getattr(check, field)) != str(new_value)
+ assert check.column_name == "total"
+ assert check.description == ""
+ assert taken.fingerprint != check.fingerprint
+
+ def test_editing_onto_a_taken_name_is_a_field_error(self) -> None:
+ self._create_check(check_type=CheckType.UNIQUE, name="orders_customer_id_unique")
+ check = self._create_check(column_name="total")
+
+ response = self.client.patch(f"{self.url}/{check.id}/", {"name": "orders_customer_id_unique"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "name"
+ check.refresh_from_db()
+ assert check.name == ""
+
+ def test_a_definition_freed_by_deletion_becomes_a_new_check(self) -> None:
+ # The old check keeps its own id and history; reusing the definition must not resurrect it.
+ first = self._create_check()
+ assert self.client.delete(f"{self.url}/{first.id}/").status_code == status.HTTP_204_NO_CONTENT
+
+ again = self.client.post(f"{self.url}/", self._payload())
+
+ assert again.status_code == status.HTTP_201_CREATED, again.json()
+ assert again.json()["id"] != str(first.id)
+ first.refresh_from_db()
+ assert first.deleted is True
+
+ def test_a_name_freed_by_deletion_can_be_used_again(self) -> None:
+ # A deleted check keeps its name as history. Holding it against a new check would make the
+ # delete irreversible for anyone who wants that name back.
+ first = self._create_check(name="orders_customer_id_not_null")
+ assert self.client.delete(f"{self.url}/{first.id}/").status_code == status.HTTP_204_NO_CONTENT
+
+ again = self.client.post(f"{self.url}/", self._payload(column_name="total", name="orders_customer_id_not_null"))
+
+ assert again.status_code == status.HTTP_201_CREATED, again.json()
+ assert again.json()["id"] != str(first.id)
+
+ def test_a_definition_race_lost_to_the_constraint_reads_as_a_conflict(self) -> None:
+ # Two rows can both clear the duplicate precheck and race to commit one fingerprint; the
+ # active-only constraint settles it, and the loser must see the same field error the
+ # precheck raises rather than a 500.
+ winner = self._create_check(check_type=CheckType.UNIQUE)
+ loser = self._create_check(column_name="total")
+
+ with patch.object(checks_logic, "_ensure_definition_available", return_value=None):
+ response = self.client.patch(
+ f"{self.url}/{loser.id}/", {"check_type": CheckType.UNIQUE, "column_name": "customer_id"}
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["code"] == "duplicate_definition"
+ loser.refresh_from_db()
+ assert loser.column_name == "total"
+ assert winner.check_type == CheckType.UNIQUE
+
+ def test_a_name_race_lost_to_the_constraint_reads_as_a_conflict(self) -> None:
+ # Two rows can both clear the name precheck and race to commit one name; the constraint
+ # settles it, and the loser must see the same field error the precheck raises, not a 500.
+ self._create_check(check_type=CheckType.UNIQUE, name="orders_customer_id_unique")
+ loser = self._create_check(column_name="total")
+
+ with patch.object(checks_logic, "_name_taken", side_effect=[False, True]):
+ response = self.client.patch(f"{self.url}/{loser.id}/", {"name": "orders_customer_id_unique"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "name"
+ loser.refresh_from_db()
+ assert loser.name == ""
def test_a_racing_identical_create_returns_the_winning_row_not_a_500(self) -> None:
# Two identical creates can both miss the fingerprint lookup and race to insert; the uniqueness
@@ -387,6 +515,45 @@ class TestDataQualityCheckAPI(APIBaseTest):
check_runs = self.client.get(f"{base}/{mine.id}/check_runs/")
assert [row["subject_name"] for row in check_runs.json()] == ["orders"]
+ def test_editing_a_check_does_not_unlock_the_history_it_used_to_read(self) -> None:
+ # Authorizing history against the definition the check carries *now* lets a member point a
+ # check that reads the denied "orders" at something harmless and then read what it recorded:
+ # the compiled query, the failed-row count and the observed value.
+ allowed = self._make_view("customers")
+ reads_orders = {"query": "SELECT 1 FROM orders"}
+ check = DataQualityCheck.objects.for_team(self.team.id).create(
+ team=self.team,
+ subject_type=SubjectType.VIEW,
+ saved_query_id=allowed.id,
+ subject_name="customers",
+ check_type=CheckType.CUSTOM_SQL,
+ config=reads_orders,
+ fingerprint=uuid4().hex,
+ )
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual"),
+ quality_check=check,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=allowed.id,
+ subject_name="customers",
+ check_type=CheckType.CUSTOM_SQL,
+ check_config=reads_orders,
+ check_fingerprint=check.fingerprint,
+ status=CheckRunStatus.FAILED,
+ failed_row_count=3,
+ compiled_query="SELECT * FROM orders",
+ )
+ self._deny_the_view()
+
+ url = f"{self._checks_url(allowed.id)}/{check.id}"
+ edited = self.client.patch(url + "/", {"check_type": CheckType.NOT_NULL, "column_name": "id", "config": {}})
+ history = self.client.get(f"{url}/runs/")
+
+ assert edited.status_code == status.HTTP_200_OK, edited.json()
+ assert history.status_code == status.HTTP_200_OK
+ assert history.json() == []
+
def _deny_the_view(self) -> None:
# Deny the default member object-level access to the "orders" view, the way the HogQL
# database sees it -- so denied_subject_names() picks it up and the endpoint hides it.
@@ -415,6 +582,10 @@ class TestDataQualityCheckAPI(APIBaseTest):
("list", lambda self, check, suite: self.client.get(f"{self.url}/")),
("retrieve", lambda self, check, suite: self.client.get(f"{self.url}/{check.id}/")),
("create", lambda self, check, suite: self.client.post(f"{self.url}/", self._payload())),
+ (
+ "partial_update",
+ lambda self, check, suite: self.client.patch(f"{self.url}/{check.id}/", {"description": "edited"}),
+ ),
("run", lambda self, check, suite: self.client.post(f"{self.url}/{check.id}/run/")),
("runs", lambda self, check, suite: self.client.get(f"{self.url}/{check.id}/runs/")),
("run_all", lambda self, check, suite: self.client.post(f"{self.url}/run_all/")),
@@ -476,6 +647,22 @@ class TestDataQualityCheckAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
assert DataQualityCheck.objects.for_team(self.team.id).count() == 0
+ def test_editing_a_check_to_read_a_denied_subject_writes_nothing(self) -> None:
+ # The stored definition cleared the denial; the candidate one has to clear it too, or an edit
+ # is the way to point a visible check at a table the member cannot read.
+ allowed = self._make_view("customers")
+ check = self._create_check(url=self._checks_url(allowed.id), column_name="id")
+ self._deny_the_view()
+
+ response = self.client.patch(
+ f"{self._checks_url(allowed.id)}/{check.id}/",
+ {"check_type": CheckType.CUSTOM_SQL, "column_name": "", "config": {"query": "SELECT 1 FROM orders"}},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ check.refresh_from_db()
+ assert check.check_type == CheckType.NOT_NULL
+
@parameterized.expand(
[
("run", lambda self, url, check: self.client.post(f"{url}/{check.id}/run/")),
diff --git a/products/data_quality/backend/tests/test_models.py b/products/data_quality/backend/tests/test_models.py
index ce7930ae1227..ff5a3f4bf12b 100644
--- a/products/data_quality/backend/tests/test_models.py
+++ b/products/data_quality/backend/tests/test_models.py
@@ -46,6 +46,15 @@ class TestDataQualityModels(BaseTest):
)
assert table_subject.pk is not None
+ def test_a_deleted_check_frees_its_definition_for_a_new_one(self) -> None:
+ # Authoring a definition that was deleted earlier is a new check with its own id and
+ # history, not a resurrection of the row the user believes is gone.
+ deleted = self._create_check(deleted=True)
+
+ replacement = self._create_check()
+
+ assert replacement.pk != deleted.pk
+
def test_orphaned_checks_escape_fingerprint_uniqueness(self) -> None:
# SET_NULL orphaning must never be blocked by the constraint, even for twin fingerprints.
self._create_check(saved_query_id=None)
diff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.py
index 401e7252216e..be55b26caadc 100644
--- a/products/data_quality/backend/tests/test_runner.py
+++ b/products/data_quality/backend/tests/test_runner.py
@@ -1,3 +1,4 @@
+from datetime import UTC, datetime
from uuid import uuid4
from posthog.test.base import BaseTest
@@ -6,6 +7,7 @@ from unittest.mock import patch
from parameterized import parameterized
from posthog.clickhouse.query_tagging import Feature, Product, QueryTags, get_query_tags
+from posthog.models.user import User
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.data_quality.backend.facade.enums import (
@@ -180,7 +182,7 @@ class TestCheckRunner(BaseTest):
assert query.call_args.kwargs["bypass_warehouse_access_control"] is expected_bypass
assert query.call_args.kwargs["user"] == (None if expected_bypass else self.user)
- def _referencing_check(self, check_type: CheckType, created_by) -> DataQualityCheck:
+ def _referencing_check(self, check_type: CheckType, created_by, **overrides) -> DataQualityCheck:
# Both types read beyond their declared subject: custom_sql over arbitrary SQL, relationships
# over a target subject. The relationships target must resolve so the check compiles.
if check_type == CheckType.RELATIONSHIPS:
@@ -188,8 +190,12 @@ class TestCheckRunner(BaseTest):
team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
)
config = {"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(target.id), "to_column": "id"}
- return self._check(check_type=check_type, column_name="customer_id", config=config, created_by=created_by)
- return self._check(check_type=check_type, column_name="", config={"query": "select 1"}, created_by=created_by)
+ return self._check(
+ check_type=check_type, column_name="customer_id", config=config, created_by=created_by, **overrides
+ )
+ return self._check(
+ check_type=check_type, column_name="", config={"query": "select 1"}, created_by=created_by, **overrides
+ )
@parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])
def test_an_automated_referencing_check_runs_as_its_author(self, _name, check_type: CheckType) -> None:
@@ -206,6 +212,67 @@ class TestCheckRunner(BaseTest):
assert query.call_args.kwargs["bypass_warehouse_access_control"] is False
assert query.call_args.kwargs["user"] == self.user
+ def test_an_edited_referencing_check_runs_as_whoever_last_changed_it(self) -> None:
+ # The creator may never have seen what the check reads now, and may have lost access to it;
+ # the editor is the one whose warehouse ACL was checked against the current definition.
+ editor = User.objects.create_and_join(self.organization, "[email protected]", None)
+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger=SuiteRunTrigger.MATERIALIZATION
+ )
+ check = self._referencing_check(CheckType.CUSTOM_SQL, created_by=self.user, definition_author=editor)
+
+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])) as query:
+ run_check(check, suite_run, self.team)
+
+ assert query.call_args.kwargs["user"] == editor
+
+ @parameterized.expand(
+ [
+ ("passing_run_stamps_it", CheckRunStatus.PASSED, [0, 0], True),
+ ("failing_run_leaves_the_earlier_success", CheckRunStatus.FAILED, [3, 3], False),
+ ]
+ )
+ def test_the_last_success_is_denormalized_onto_the_check(self, _name, expected_status, row, advances) -> None:
+ # "Failing since when" can be older than any page of run history, so it cannot be derived
+ # from the runs a caller fetches.
+ earlier = datetime(2020, 1, 1, tzinfo=UTC)
+ check = self._check(last_succeeded_at=earlier)
+
+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], row)):
+ outcome = run_check(check, self.suite_run, self.team)
+
+ assert outcome.status == expected_status
+ check.refresh_from_db()
+ last_succeeded_at = check.last_succeeded_at
+ assert last_succeeded_at is not None
+ assert (last_succeeded_at > earlier) is advances
+
+ def test_a_failing_run_cannot_erase_a_success_recorded_beside_it(self) -> None:
+ # Batches load their checks up front, so a failing run holds whatever last_succeeded_at said
+ # then. Writing the column back would undo a pass another batch committed in between.
+ check = self._check(last_succeeded_at=None)
+ stale = DataQualityCheck.objects.for_team(self.team.id).get(id=check.id)
+ succeeded_at = datetime(2026, 1, 1, tzinfo=UTC)
+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(last_succeeded_at=succeeded_at)
+
+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [3, 3])):
+ run_check(stale, self.suite_run, self.team)
+
+ stale.refresh_from_db()
+ assert stale.last_succeeded_at == succeeded_at
+
+ def test_a_run_snapshots_the_definition_it_executed(self) -> None:
+ # History has to keep reading as what actually ran, even after the definition is edited.
+ check = self._check(
+ check_type=CheckType.ROW_COUNT, column_name="", config={"min": 1}, severity=CheckSeverity.WARN
+ )
+ with patch(RUNNER_QUERY, return_value=_Response(["observed_value"], [7])):
+ run_check(check, self.suite_run, self.team)
+
+ run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)
+ assert run.check_config == {"min": 1}
+ assert run.check_severity == CheckSeverity.WARN
+
@parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])
def test_an_automated_referencing_check_without_an_author_errors_without_running(
self, _name, check_type: CheckType
diff --git a/products/data_quality/backend/tests/test_runs_api.py b/products/data_quality/backend/tests/test_runs_api.py
new file mode 100644
index 000000000000..1847ea2bed75
--- /dev/null
+++ b/products/data_quality/backend/tests/test_runs_api.py
@@ -0,0 +1,298 @@
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_modeling.backend.models.dag import DAG
+from products.data_modeling.backend.models.node import Node
+from products.data_quality.backend.facade import api
+from products.data_quality.backend.facade.enums import CheckRunStatus, CheckType, SubjectStatus, SubjectType
+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+START_SUITE = "products.data_quality.backend.logic.checks.sync_connect"
+FLAG = "products.data_quality.backend.presentation.views.is_data_quality_checks_enabled"
+
+
+class TestDataQualityRunAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.orders = self._make_view("orders")
+ self.customers = self._make_view("customers")
+ self.url = f"/api/projects/{self.team.id}/data_quality_runs/"
+ self.checks_url = f"/api/projects/{self.team.id}/data_quality_checks/"
+ flag = patch(FLAG, return_value=True)
+ flag.start()
+ self.addCleanup(flag.stop)
+
+ def _make_view(self, name: str) -> DataWarehouseSavedQuery:
+ return DataWarehouseSavedQuery.objects.create(
+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
+ )
+
+ def _check(self, view: DataWarehouseSavedQuery, **overrides) -> DataQualityCheck:
+ return DataQualityCheck.objects.for_team(self.team.id).create(
+ **{
+ "team": self.team,
+ "subject_type": SubjectType.VIEW,
+ "saved_query_id": view.id,
+ "subject_name": view.name,
+ "check_type": CheckType.NOT_NULL,
+ "column_name": "id",
+ "fingerprint": uuid4().hex,
+ **overrides,
+ }
+ )
+
+ def _run(self, **body):
+ with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):
+ return self.client.post(self.url, body, format="json")
+
+ def _deny_orders(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_view",
+ resource_id=str(self.orders.id),
+ organization_member=self.organization_membership,
+ access_level="none",
+ )
+ warehouse_ac = patch(
+ "posthog.hogql.database.database.feature_enabled_or_false",
+ side_effect=lambda name, *a, **k: name == "hogql-warehouse-access-control",
+ )
+ warehouse_ac.start()
+ self.addCleanup(warehouse_ac.stop)
+ cache.clear()
+
+ def test_running_with_no_selection_runs_every_enabled_check(self) -> None:
+ self._check(self.orders)
+ self._check(self.customers)
+ self._check(self.customers, column_name="total", enabled=False)
+
+ response = self._run()
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=response.json()["id"])
+ assert suite_run.status == "running"
+ # A sweep has no single subject, so the response has to say so rather than name one.
+ assert response.json()["subject_type"] is None
+
+ def test_a_sweep_leaves_out_checks_on_a_denied_subject(self) -> None:
+ # "Everything" means everything this member can see. A denied subject is not part of it.
+ mine = self._check(self.customers)
+ self._check(self.orders)
+ self._deny_orders()
+
+ with (
+ patch("products.data_quality.backend.presentation.views.api.start_check_suite") as start,
+ patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())),
+ ):
+ start.return_value = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="manual"
+ )
+ self.client.post(self.url, {}, format="json")
+
+ assert start.call_args.kwargs["check_ids"] == [str(mine.id)]
+
+ @parameterized.expand([("every_check_is_denied",), ("named_ids_match_nothing_runnable",)])
+ def test_a_run_with_nothing_to_run_starts_no_workflow(self, case: str) -> None:
+ # An empty selection is indistinguishable from no selector by the time it reaches the
+ # worker, so handing one over sweeps the whole project instead of running none of it.
+ body: dict = {}
+ if case == "every_check_is_denied":
+ self._check(self.orders)
+ self._deny_orders()
+ else:
+ self._check(self.customers)
+ body = {"check_ids": [str(uuid4())]}
+
+ with patch(START_SUITE) as connect:
+ response = self.client.post(self.url, body, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["status"] == "empty"
+ connect.assert_not_called()
+
+ def test_naming_a_denied_check_is_refused(self) -> None:
+ # Naming one is an attempt to read it, so it 403s rather than being silently dropped.
+ denied = self._check(self.orders)
+ self._deny_orders()
+
+ response = self._run(check_ids=[str(denied.id)])
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_the_sweep_is_gated_on_the_feature_flag(self) -> None:
+ with patch(FLAG, return_value=False):
+ assert self.client.post(self.url, {}, format="json").status_code == status.HTTP_403_FORBIDDEN
+
+ def test_query_denied_members_cannot_sweep_or_read_runs(self) -> None:
+ AccessControl.objects.create(team=self.team, resource="query", access_level="none")
+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": "access"}]
+ self.organization.save()
+
+ assert self.client.post(self.url, {}, format="json").status_code == status.HTTP_403_FORBIDDEN
+ assert self.client.get(self.url).status_code == status.HTTP_403_FORBIDDEN
+
+ def test_history_serves_the_sweeps_the_per_subject_surfaces_hide(self) -> None:
+ # The nested suite-run lists filter on subject_uuid, so a multi-subject sweep is only
+ # readable here.
+ sweep = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")
+ scoped = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="materialization", subject_type=SubjectType.VIEW, subject_uuid=self.orders.id
+ )
+
+ listed = self.client.get(self.url)
+
+ assert {row["id"] for row in listed.json()["results"]} == {str(sweep.id), str(scoped.id)}
+ assert self.client.get(f"{self.url}{sweep.id}/").status_code == status.HTTP_200_OK
+
+ def test_history_withholds_the_suites_that_report_on_a_denied_subject(self) -> None:
+ # A suite row carries its subject and its outcome counters, so serving one is serving counts
+ # over rows the member cannot read. The nested lists are gated by their parent; this one
+ # spans every subject and has none.
+ self._check(self.orders)
+ mine = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="materialization", subject_type=SubjectType.VIEW, subject_uuid=self.customers.id
+ )
+ denied = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="materialization", subject_type=SubjectType.VIEW, subject_uuid=self.orders.id
+ )
+ sweep = self._sweep_covering(self.orders)
+ self._deny_orders()
+
+ listed = self.client.get(self.url)
+
+ assert {row["id"] for row in listed.json()["results"]} == {str(mine.id)}
+ assert self.client.get(f"{self.url}{denied.id}/").status_code == status.HTTP_404_NOT_FOUND
+ assert self.client.get(f"{self.url}{sweep.id}/").status_code == status.HTTP_404_NOT_FOUND
+
+ def _sweep_covering(self, view: DataWarehouseSavedQuery) -> DataQualitySuiteRun:
+ """A multi-subject sweep whose counters include one check run against this view."""
+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=suite_run,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=view.id,
+ subject_name=view.name,
+ check_type=CheckType.NOT_NULL,
+ check_fingerprint=uuid4().hex,
+ status=CheckRunStatus.FAILED,
+ )
+ return suite_run
+
+ def test_the_overview_lists_every_subjects_checks(self) -> None:
+ # The nested surfaces each serve one parent, so this is the only list that spans subjects.
+ self._check(self.orders)
+ self._check(self.customers)
+
+ response = self.client.get(self.checks_url)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert {row["subject_name"] for row in response.json()["results"]} == {"orders", "customers"}
+
+ def test_the_overview_hides_a_denied_subjects_checks(self) -> None:
+ # A list of everything is a directory of the project's tables, so a denied one must not
+ # appear in it, nor in the health rollup derived from the same set.
+ self._check(self.orders)
+ self._check(self.customers)
+ self._deny_orders()
+
+ listed = self.client.get(self.checks_url)
+ health = self.client.get(f"{self.checks_url}health/")
+
+ assert {row["subject_name"] for row in listed.json()["results"]} == {"customers"}
+ assert {row["subject_uuid"] for row in health.json()} == {str(self.customers.id)}
+
+ def test_the_overview_leaves_out_orphans_but_keeps_their_history(self) -> None:
+ # An orphan has no subject page to link to, nothing to run, and no rollup to sit under, so
+ # showing it in the project list would be a dead row.
+ live = self._check(self.customers)
+ orphan = self._check(self.orders, subject_status=SubjectStatus.ORPHANED)
+
+ listed = self.client.get(self.checks_url)
+ health = self.client.get(f"{self.checks_url}health/")
+
+ assert {row["id"] for row in listed.json()["results"]} == {str(live.id)}
+ assert {row["subject_uuid"] for row in health.json()} == {str(self.customers.id)}
+ assert DataQualityCheck.objects.for_team(self.team.id).filter(id=orphan.id).exists()
+
+ def test_the_overview_says_where_each_subject_can_be_opened(self) -> None:
+ # The row links to the subject's own page, which lives on a DAG node for a view and on a
+ # source schema for a synced table -- neither of which the check row itself carries.
+ node = Node.objects.create(team=self.team, dag=DAG.get_or_create_default(self.team), saved_query=self.orders)
+ table, schema = self._synced_table("stripe_charges")
+ self._check(self.orders)
+ self._check(self.customers)
+ self._check(
+ self.orders, subject_type=SubjectType.TABLE, saved_query_id=None, table_id=table.id, subject_name=table.name
+ )
+
+ rows = {row["subject_name"]: row for row in self.client.get(self.checks_url).json()["results"]}
+
+ assert rows["orders"]["subject_node_id"] == str(node.id)
+ assert rows["orders"]["subject_source_id"] is None
+ assert rows["stripe_charges"]["subject_source_id"] == str(schema.source_id)
+ assert rows["stripe_charges"]["subject_schema_id"] == str(schema.id)
+ # A view on no DAG has no node page; the row renders its name as plain text.
+ assert rows["customers"]["subject_node_id"] is None
+
+ def test_resolving_where_subjects_live_does_not_grow_with_the_project(self) -> None:
+ # The overview lists every check in the project, so a query per row is a query per table in
+ # the warehouse.
+ views = [self._check(self._make_view(f"view_{index}")) for index in range(5)]
+ tables = [
+ self._check(
+ self.orders,
+ subject_type=SubjectType.TABLE,
+ saved_query_id=None,
+ table_id=self._synced_table(f"table_{index}")[0].id,
+ )
+ for index in range(5)
+ ]
+
+ with self.assertNumQueries(2):
+ located = api.subject_locations(self.team.id, [*views, *tables])
+
+ assert len(located) == 5
+
+ def _synced_table(self, name: str) -> tuple[DataWarehouseTable, ExternalDataSchema]:
+ source = ExternalDataSource.objects.create(team=self.team, source_type="Stripe")
+ table = DataWarehouseTable.objects.create(
+ team=self.team, name=name, format=DataWarehouseTable.TableFormat.Parquet, url_pattern=""
+ )
+ schema = ExternalDataSchema.objects.create(team=self.team, source=source, table=table, name=name)
+ return table, schema
+
+ def test_health_rolls_up_each_subject_without_a_query_per_subject(self) -> None:
+ self._check(self.orders, last_status=CheckRunStatus.FAILED)
+ self._check(self.orders, column_name="total", last_status=CheckRunStatus.PASSED)
+ self._check(self.customers, last_status=CheckRunStatus.PASSED)
+
+ response = self.client.get(f"{self.checks_url}health/")
+
+ by_subject = {row["subject_uuid"]: row for row in response.json()}
+ assert by_subject[str(self.orders.id)] == {
+ "subject_type": "view",
+ "subject_uuid": str(self.orders.id),
+ "health": "failing",
+ "checks_total": 2,
+ "checks_failing": 1,
+ }
+ assert by_subject[str(self.customers.id)]["health"] == "healthy"
diff --git a/products/data_quality/frontend/CheckFormModal.tsx b/products/data_quality/frontend/CheckEditorModal.tsx
similarity index 57%
rename from products/data_quality/frontend/CheckFormModal.tsx
rename to products/data_quality/frontend/CheckEditorModal.tsx
index e81ab9475488..fb88b5f4b5ba 100644
--- a/products/data_quality/frontend/CheckFormModal.tsx
+++ b/products/data_quality/frontend/CheckEditorModal.tsx
@@ -9,51 +9,58 @@ import {
LemonSegmentedButton,
LemonSelect,
LemonTextArea,
+ Spinner,
} 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
+import { dataQualityCheckEditorLogic } from './dataQualityCheckEditorLogic'
+import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi } from './generated/api.schemas'
+
+export function CheckEditorModal(): JSX.Element {
+ const {
+ isOpen,
+ editingCheck,
+ checkForm,
+ checkTypes,
+ checkTypesLoading,
+ requiresColumn,
+ availableColumns,
+ databaseLoading,
+ isCheckFormSubmitting,
+ serverError,
+ } = useValues(dataQualityCheckEditorLogic)
+ // Which fields the form has depends on the check-type catalog, so showing the form before it
+ // arrives means fields appearing under the user's cursor a moment later.
+ const formShapeLoading = checkTypesLoading && !checkTypes.length
+ const { requestClose, submitCheckForm, setCheckFormValues } = useActions(dataQualityCheckEditorLogic)
return (
<LemonModal
- isOpen={checkModalOpen}
- onClose={closeCheckModal}
- title={isEditing ? 'Edit check' : 'New check'}
+ isOpen={isOpen}
+ onClose={requestClose}
+ title={editingCheck ? '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}>
+ <LemonButton type="secondary" onClick={requestClose}>
Cancel
</LemonButton>
<LemonButton
type="primary"
onClick={submitCheckForm}
loading={isCheckFormSubmitting}
+ disabledReason={
+ isCheckFormSubmitting
+ ? 'Saving'
+ : formShapeLoading
+ ? 'Loading the check types'
+ : undefined
+ }
data-attr="data-quality-check-save"
>
Save check
@@ -62,10 +69,19 @@ export function CheckFormModal({ columns, ...logicProps }: CheckFormModalProps):
</div>
}
>
- <Form logic={dataQualityChecksLogic} props={logicProps} formKey="checkForm" className="flex flex-col gap-3">
+ {formShapeLoading && (
+ <div className="flex items-center gap-2 py-8 justify-center text-secondary">
+ <Spinner className="text-xl" />
+ <span>Loading check types...</span>
+ </div>
+ )}
+ <Form
+ logic={dataQualityCheckEditorLogic}
+ formKey="checkForm"
+ className={formShapeLoading ? 'hidden' : '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),
@@ -96,24 +112,30 @@ export function CheckFormModal({ columns, ...logicProps }: CheckFormModalProps):
{requiresColumn && (
<LemonField name="columnName" label="Column">
<LemonSelect
- disabledReason={editLockReason}
- options={columns.map((column) => ({ value: column.name, label: column.name }))}
+ loading={databaseLoading && !availableColumns.length}
+ options={availableColumns.map((column) => ({ value: column, label: column }))}
/>
</LemonField>
)}
- <CheckConfigFields
- checkType={checkForm.checkType}
- disabledReason={editLockReason}
- logicProps={logicProps}
- />
+ <CheckConfigFields checkType={checkForm.checkType} />
- <LemonField name="name" label="Name" showOptional>
+ <LemonField
+ name="name"
+ label="Name"
+ showOptional
+ help="Lets you refer to this check by name in SQL and the API instead of by its id. Letters, numbers and underscores, starting with a letter."
+ >
<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
+ name="description"
+ label="Description"
+ showOptional
+ help="Why this check exists and what a failure means. Shown to whoever finds the check failing."
+ >
+ <LemonTextArea placeholder="Every order has to belong to a customer" minRows={2} />
</LemonField>
<LemonField name="severity" label="Severity">
@@ -133,38 +155,24 @@ export function CheckFormModal({ columns, ...logicProps }: CheckFormModalProps):
)
}
-function CheckConfigFields({
- checkType,
- disabledReason,
- logicProps,
-}: {
- checkType: CheckTypeEnumApi
- disabledReason?: string
- logicProps: DataQualityChecksLogicProps
-}): JSX.Element | null {
+function CheckConfigFields({ checkType }: { checkType: CheckTypeEnumApi }): 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"
- />
+ <LemonInputSelect mode="multiple" allowCustomValues options={[]} placeholder="Add a value" />
</LemonField>
)
case CheckTypeEnumApi.Relationships:
- return <RelationshipFields disabledReason={disabledReason} logicProps={logicProps} />
+ return <RelationshipFields />
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} />
+ <LemonInput type="number" min={0} />
</LemonField>
<LemonField name="rowCountMax" label="Maximum rows" showOptional className="flex-1">
- <LemonInput type="number" min={0} disabled={!!disabledReason} />
+ <LemonInput type="number" min={0} />
</LemonField>
</div>
)
@@ -175,7 +183,7 @@ function CheckConfigFields({
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} />
+ <LemonInput type="number" min={1} />
</LemonField>
)
case CheckTypeEnumApi.CustomSql:
@@ -192,7 +200,6 @@ function CheckConfigFields({
onChange={(query) => onChange(query ?? '')}
minHeight="8rem"
maxHeight="40vh"
- options={{ readOnly: !!disabledReason }}
/>
)}
</LemonField>
@@ -202,41 +209,22 @@ function CheckConfigFields({
}
}
-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)
+function RelationshipFields(): JSX.Element {
+ const { checkForm, relationshipSubjects, databaseLoading } = useValues(dataQualityCheckEditorLogic)
+ const { setCheckFormValues } = useActions(dataQualityCheckEditorLogic)
- const selected = subjects.find((subject) => subject.id === checkForm.toSubjectUuid)
+ const selected = relationshipSubjects.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 }))}
+ loading={databaseLoading}
+ options={relationshipSubjects.map((subject) => ({ value: subject.id, label: subject.name }))}
onChange={(toSubjectUuid) =>
setCheckFormValues({
toSubjectUuid,
- toSubjectType: subjects.find((subject) => subject.id === toSubjectUuid)?.type,
+ toSubjectType: relationshipSubjects.find((subject) => subject.id === toSubjectUuid)?.type,
toColumn: '',
})
}
@@ -244,8 +232,8 @@ function RelationshipFields({
</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 }))}
+ disabledReason={selected ? undefined : 'Pick a table or view first'}
+ options={(selected?.fields ?? []).map((field) => ({ value: field, label: field }))}
/>
</LemonField>
</>
diff --git a/products/data_quality/frontend/CheckRunsTable.tsx b/products/data_quality/frontend/CheckRunsTable.tsx
index 4285676d6ef3..68f3ad068334 100644
--- a/products/data_quality/frontend/CheckRunsTable.tsx
+++ b/products/data_quality/frontend/CheckRunsTable.tsx
@@ -1,10 +1,8 @@
-import { LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonTable, LemonTag, 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'
@@ -22,9 +20,6 @@ export function CheckRunsTable({ runs, loading }: CheckRunsTableProps): JSX.Elem
loading={loading}
nouns={['run', 'runs']}
emptyState="No runs yet"
- expandable={{
- expandedRowRender: (run) => <CheckRunQuery run={run} />,
- }}
columns={[
{
title: 'Status',
@@ -71,17 +66,3 @@ export function CheckRunsTable({ runs, loading }: CheckRunsTableProps): JSX.Elem
/>
)
}
-
-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/CheckStatusCell.tsx b/products/data_quality/frontend/CheckStatusCell.tsx
new file mode 100644
index 000000000000..45f8e34e06ea
--- /dev/null
+++ b/products/data_quality/frontend/CheckStatusCell.tsx
@@ -0,0 +1,32 @@
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+
+import { CHECK_STATUS_TAG_TYPES, failingForLabel } from './checksConstants'
+import type { DataQualityCheckApi } from './generated/api.schemas'
+
+/** The status, plus how long it has been broken -- a red tag alone never says "since when". */
+export function CheckStatusCell({
+ check,
+}: {
+ check: Pick<DataQualityCheckApi, 'last_status' | 'last_succeeded_at'>
+}): JSX.Element {
+ const failingFor = failingForLabel(check)
+ if (!check.last_status) {
+ return <LemonTag type="muted">Not run yet</LemonTag>
+ }
+ return (
+ <div className="flex items-center gap-1.5">
+ <LemonTag type={CHECK_STATUS_TAG_TYPES[check.last_status] ?? 'default'}>{check.last_status}</LemonTag>
+ {failingFor && (
+ <Tooltip
+ title={
+ check.last_succeeded_at ? `Last passed ${dayjs(check.last_succeeded_at).fromNow()}` : undefined
+ }
+ >
+ <span className="text-secondary text-xs whitespace-nowrap">{failingFor}</span>
+ </Tooltip>
+ )}
+ </div>
+ )
+}
diff --git a/products/data_quality/frontend/ChecksTable.tsx b/products/data_quality/frontend/ChecksTable.tsx
index 585136f27054..53dbdc7ebcf0 100644
--- a/products/data_quality/frontend/ChecksTable.tsx
+++ b/products/data_quality/frontend/ChecksTable.tsx
@@ -6,14 +6,21 @@ import { LemonButton, LemonDialog, LemonMenu, LemonSwitch, LemonTable, LemonTag,
import { TZLabel } from 'lib/components/TZLabel'
import { CheckRunsTable } from './CheckRunsTable'
-import { CHECK_STATUS_TAG_TYPES, SEVERITY_TAG_TYPES, checkDisplayName, checkTypeLabel } from './checksConstants'
+import { SEVERITY_TAG_TYPES, checkDisplayName, checkTypeLabel } from './checksConstants'
+import { CheckStatusCell } from './CheckStatusCell'
+import { dataQualityCheckEditorLogic } from './dataQualityCheckEditorLogic'
import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'
import type { DataQualityCheckApi } from './generated/api.schemas'
-export function ChecksTable(props: DataQualityChecksLogicProps): JSX.Element {
+interface ChecksTableProps extends DataQualityChecksLogicProps {
+ columns: string[]
+}
+
+export function ChecksTable({ columns, ...props }: ChecksTableProps): JSX.Element {
const logic = dataQualityChecksLogic(props)
const { sortedChecks, checksLoading, pendingCheckActions, checkRunsByCheckId } = useValues(logic)
- const { openCheckModal, deleteCheck, toggleCheckEnabled, runCheck, loadCheckRuns } = useActions(logic)
+ const { deleteCheck, toggleCheckEnabled, runCheck, loadCheckRuns, openFailingRows } = useActions(logic)
+ const { openEditor } = useActions(dataQualityCheckEditorLogic)
const confirmDelete = (check: DataQualityCheckApi): void => {
LemonDialog.open({
@@ -98,14 +105,7 @@ export function ChecksTable(props: DataQualityChecksLogicProps): JSX.Element {
{
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>
- ),
+ render: (_, check) => <CheckStatusCell check={check} />,
},
{
title: 'Last run',
@@ -125,7 +125,12 @@ export function ChecksTable(props: DataQualityChecksLogicProps): JSX.Element {
? 'This check is already starting'
: undefined,
},
- { label: 'Edit', onClick: () => openCheckModal(check) },
+ { label: 'Edit', onClick: () => openEditor(check, props, columns) },
+ {
+ label: 'Open failing rows in SQL editor',
+ tooltip: "The query behind this check's latest run",
+ onClick: () => openFailingRows(check.id),
+ },
{
label: 'Delete',
status: 'danger',
diff --git a/products/data_quality/frontend/DataQualityChecksPanel.tsx b/products/data_quality/frontend/DataQualityChecksPanel.tsx
index 6c476c1e73f1..ca3e06ccb358 100644
--- a/products/data_quality/frontend/DataQualityChecksPanel.tsx
+++ b/products/data_quality/frontend/DataQualityChecksPanel.tsx
@@ -1,4 +1,4 @@
-import { useActions, useValues } from 'kea'
+import { BindLogic, useActions, useValues } from 'kea'
import { LemonBanner, LemonButton, LemonSwitch, LemonTag, Spinner } from '@posthog/lemon-ui'
@@ -7,9 +7,10 @@ import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { DatabaseSchemaField } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
-import { CheckFormModal } from './CheckFormModal'
+import { CheckEditorModal } from './CheckEditorModal'
import { HEALTH_LABELS, HEALTH_TAG_TYPES } from './checksConstants'
import { ChecksTable } from './ChecksTable'
+import { DataQualityCheckEditorLogicProps, dataQualityCheckEditorLogic } from './dataQualityCheckEditorLogic'
import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'
import { dataQualityGateLogic } from './dataQualityGateLogic'
import { SuiteRunsHistory } from './SuiteRunsHistory'
@@ -36,91 +37,100 @@ export function DataQualityChecksPanel({
runAllInFlight,
accessDenied,
} = useValues(logic)
- const { openCheckModal, runAll, loadChecks, loadHealth } = useActions(logic)
+ const { runAll, loadChecks, loadHealth, upsertCheck, runCheck } = useActions(logic)
+
+ const editorProps: DataQualityCheckEditorLogicProps = {
+ surface: `subject:${logicProps.subjectType}:${logicProps.subjectId}`,
+ onSaved: (check) => {
+ upsertCheck(check)
+ loadHealth()
+ },
+ onRunNow: (check) => runCheck(check.id),
+ }
+ const { openEditor } = useActions(dataQualityCheckEditorLogic(editorProps))
+ const columnNames = columns.map((column) => column.name)
+ const addCheck = (): void => openEditor(null, logicProps, columnNames)
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>
+ <BindLogic logic={dataQualityCheckEditorLogic} props={editorProps}>
+ <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={addCheck} data-attr="data-quality-new-check">
+ New check
+ </LemonButton>
+ </div>
</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>
- )}
+ {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} />
- )}
+ {!checksLoading && checks.length === 0 ? (
+ <NoChecksYet onAddCheck={addCheck} />
+ ) : (
+ <ChecksTable {...logicProps} columns={columnNames} />
+ )}
- <SuiteRunsHistory {...logicProps} />
+ <SuiteRunsHistory {...logicProps} />
- {showGateToggle && <GateToggle />}
+ {showGateToggle && <GateToggle />}
- <CheckFormModal {...logicProps} columns={columns} />
- </div>
+ <CheckEditorModal />
+ </div>
+ </BindLogic>
)
}
diff --git a/products/data_quality/frontend/checksApi.ts b/products/data_quality/frontend/checksApi.ts
index f34dae21ffb1..0bf6f4abafb2 100644
--- a/products/data_quality/frontend/checksApi.ts
+++ b/products/data_quality/frontend/checksApi.ts
@@ -1,4 +1,4 @@
-import { ApiConfig } from 'lib/api'
+import { ApiConfig, ApiError } from 'lib/api'
import {
warehouseSavedQueriesCheckSuiteRunsCheckRunsList,
@@ -36,6 +36,10 @@ import type {
PaginatedDataQualitySuiteRunListApi,
} from './generated/api.schemas'
+export function apiErrorDetail(error: unknown): string | null {
+ return error instanceof ApiError ? error.detail : null
+}
+
export type DataQualitySubjectType = 'table' | 'view'
export interface DataQualitySubjectRef {
diff --git a/products/data_quality/frontend/checksConstants.test.ts b/products/data_quality/frontend/checksConstants.test.ts
new file mode 100644
index 000000000000..252a310025f8
--- /dev/null
+++ b/products/data_quality/frontend/checksConstants.test.ts
@@ -0,0 +1,19 @@
+import { dayjs } from 'lib/dayjs'
+
+import { failingForLabel } from './checksConstants'
+
+describe('checksConstants', () => {
+ const now = dayjs('2026-08-19T12:00:00Z')
+
+ // A red tag alone never says "since when", and the answer can be older than any page of run
+ // history, so it has to come off the check rather than be derived from the runs on screen.
+ it.each<[string, string, string | null, string | null]>([
+ ['passing checks say nothing', 'passed', '2026-08-19T11:00:00Z', null],
+ ['checks that never ran say nothing', '', null, null],
+ ['a failing check counts from its last pass', 'failed', '2026-08-16T12:00:00Z', 'for 3 days'],
+ ['an erroring check counts too', 'errored', '2026-08-19T09:00:00Z', 'for 3 hours'],
+ ['a check with no pass on record says so', 'failed', null, 'never passed'],
+ ])('%s', (_case, lastStatus, lastSucceededAt, expected) => {
+ expect(failingForLabel({ last_status: lastStatus, last_succeeded_at: lastSucceededAt }, now)).toEqual(expected)
+ })
+})
diff --git a/products/data_quality/frontend/checksConstants.ts b/products/data_quality/frontend/checksConstants.ts
index 49240158b0db..1eedfa586ddf 100644
--- a/products/data_quality/frontend/checksConstants.ts
+++ b/products/data_quality/frontend/checksConstants.ts
@@ -1,3 +1,4 @@
+import { Dayjs, dayjs } from 'lib/dayjs'
import { LemonTagType } from 'lib/lemon-ui/LemonTag'
import { CheckTypeEnumApi } from './generated/api.schemas'
@@ -43,17 +44,42 @@ export const HEALTH_LABELS: Record<string, string> = {
unknown: 'Not run yet',
}
+/** Matches the vocabulary the lineage graph uses for the same objects, without importing across products. */
+export const SUBJECT_TYPE_TAGS: Record<string, { label: string; type: LemonTagType }> = {
+ table: { label: 'Table', type: 'default' },
+ view: { label: 'View', type: 'primary' },
+}
+
export const SEVERITY_TAG_TYPES: Record<string, LemonTagType> = {
error: 'danger',
warn: 'warning',
}
+const FAILING_STATUSES = ['failed', 'errored']
+
+/**
+ * How long a check has been broken, or null when it is not broken. The first question a red row
+ * raises. Kept short because it sits beside the status tag, which already says it failed.
+ */
+export function failingForLabel(
+ check: Pick<DataQualityCheckApi, 'last_status' | 'last_succeeded_at'>,
+ now: Dayjs = dayjs()
+): string | null {
+ if (!FAILING_STATUSES.includes(check.last_status ?? '')) {
+ return null
+ }
+ if (!check.last_succeeded_at) {
+ return 'never passed'
+ }
+ return `for ${dayjs(check.last_succeeded_at).from(now, true)}`
+}
+
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 {
+export function checkDisplayName(check: Pick<DataQualityCheckApi, 'name' | 'check_type' | 'column_name'>): string {
if (check.name) {
return check.name
}
diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts
new file mode 100644
index 000000000000..16b20b279e6f
--- /dev/null
+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts
@@ -0,0 +1,441 @@
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { initKeaTests } from '~/test/init'
+import { expectLogic } from '~/test/keaTestUtils'
+
+import { DataQualitySubjectRef } from './checksApi'
+import { DataQualityCheckEditorLogicProps, dataQualityCheckEditorLogic } from './dataQualityCheckEditorLogic'
+import {
+ warehouseSavedQueriesChecksCheckTypesList,
+ warehouseSavedQueriesChecksCreate,
+ warehouseSavedQueriesChecksPartialUpdate,
+ warehouseTablesChecksCreate,
+} from './generated/api'
+import type { DataQualityCheckApi } from './generated/api.schemas'
+import { CheckTypeEnumApi } from './generated/api.schemas'
+
+jest.mock('lib/api', () => {
+ class ApiError extends Error {
+ status?: number
+ detail: string | null
+ code: string | null
+ attr: string | null
+ constructor(
+ message?: string,
+ status?: number,
+ _headers?: unknown,
+ data?: { detail?: string; code?: string; attr?: string }
+ ) {
+ super(message)
+ this.status = status
+ this.detail = data?.detail ?? null
+ this.code = data?.code ?? null
+ this.attr = data?.attr ?? 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('lib/lemon-ui/LemonDialog', () => ({
+ LemonDialog: { open: jest.fn() },
+}))
+
+// A real logic rather than a stub: the editor connects the catalog's values, and `loadCount` is how
+// these tests see whether it asked for them.
+jest.mock('scenes/data-management/database/databaseTableListLogic', () => {
+ const { actions, kea, path, reducers } = jest.requireActual('kea')
+ return {
+ databaseTableListLogic: kea([
+ path(['scenes', 'data-management', 'database', 'databaseTableListLogic']),
+ actions({ loadDatabase: true }),
+ reducers({
+ views: [[]],
+ dataWarehouseTables: [
+ [{ id: 'table-9', name: 'stripe_charges', fields: { customer_id: {}, amount: {} } }],
+ ],
+ databaseLoading: [false],
+ loadCount: [0, { loadDatabase: (state: number) => state + 1 }],
+ }),
+ ]),
+ }
+})
+
+jest.mock('./generated/api', () => ({
+ warehouseSavedQueriesChecksCreate: jest.fn(),
+ warehouseSavedQueriesChecksPartialUpdate: jest.fn(),
+ warehouseSavedQueriesChecksCheckTypesList: jest.fn(),
+ warehouseTablesChecksCreate: jest.fn(),
+ warehouseTablesChecksPartialUpdate: jest.fn(),
+ warehouseTablesChecksCheckTypesList: jest.fn(),
+}))
+
+const VIEW_SUBJECT: DataQualitySubjectRef = { subjectType: 'view', subjectId: 'view-1' }
+const COLUMNS = ['customer_id', 'status', 'created_at', 'total']
+
+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',
+ name: '',
+ description: '',
+ enabled: true,
+ severity: 'error',
+ last_status: '',
+ config: {},
+ tags: [],
+ ...overrides,
+ } as DataQualityCheckApi
+}
+
+function apiError(data: { detail?: string; code?: string; attr?: string }, status = 400): Error {
+ const { ApiError } = jest.requireMock('lib/api')
+ return new ApiError(data.detail, status, undefined, data)
+}
+
+describe('dataQualityCheckEditorLogic', () => {
+ let logic: ReturnType<typeof dataQualityCheckEditorLogic.build>
+ const onSaved = jest.fn()
+ const onRunNow = jest.fn()
+ const onClosed = jest.fn()
+
+ async function mountLogic(
+ overrides: Partial<DataQualityCheckEditorLogicProps> = {}
+ ): Promise<ReturnType<typeof dataQualityCheckEditorLogic.build>> {
+ initKeaTests()
+ logic = dataQualityCheckEditorLogic({ surface: 'subject', onSaved, onRunNow, onClosed, ...overrides })
+ logic.mount()
+ return logic
+ }
+
+ async function openWith(
+ check: DataQualityCheckApi | null,
+ values: Record<string, unknown> = {},
+ columns: string[] = COLUMNS
+ ): Promise<void> {
+ logic.actions.openEditor(check, VIEW_SUBJECT, columns)
+ await expectLogic(logic).toFinishAllListeners()
+ if (Object.keys(values).length) {
+ logic.actions.setCheckFormValues(values)
+ await expectLogic(logic).toFinishAllListeners()
+ }
+ }
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ silenceKeaLoadersErrors()
+ ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG)
+ })
+
+ afterEach(() => {
+ resumeKeaLoadersErrors()
+ logic?.unmount()
+ })
+
+ 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 goes out blank.
+ ['row_count', { checkType: 'row_count', rowCountMin: 1 }, { column_name: '', 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' },
+ { column_name: '', 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 openWith(null, formValues)
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warehouseSavedQueriesChecksCreate).toHaveBeenCalledWith('1', 'view-1', {
+ check_type: checkType,
+ severity: 'error',
+ tags: [],
+ ...expectedBody,
+ })
+ })
+
+ it('sends the whole definition when an assertion is edited', async () => {
+ // The old check kept its assertion; an edit now has to carry type, column and config together
+ // so switching type cannot leave the previous type's config behind.
+ ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())
+ await mountLogic()
+ await openWith(buildCheck({ name: 'orders_not_null', description: 'why' }), {
+ checkType: 'accepted_values',
+ columnName: 'status',
+ acceptedValues: ['paid'],
+ })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith('1', 'view-1', 'check-1', {
+ check_type: 'accepted_values',
+ column_name: 'status',
+ config: { values: ['paid'] },
+ severity: 'error',
+ name: 'orders_not_null',
+ description: 'why',
+ tags: [],
+ })
+ })
+
+ it('does not submit before the check-type catalog arrives', async () => {
+ // Enter can submit while the catalog request is still pending. Without it there is no column
+ // requirement to validate against, so the payload would omit column_name and be rejected.
+ ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock).mockReturnValueOnce(new Promise(() => {}))
+ await mountLogic()
+ logic.actions.openEditor(null, VIEW_SUBJECT, COLUMNS)
+
+ // Not toFinishAllListeners: the catalog request never settles, which is the point.
+ logic.actions.submitCheckForm()
+ for (let tick = 0; tick < 20; tick++) {
+ await Promise.resolve()
+ }
+
+ expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()
+ })
+
+ it('sends blank metadata on an edit so it can be cleared', async () => {
+ // Create omits blank optional fields, which would leave an edit unable to remove a name.
+ ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())
+ await mountLogic()
+ await openWith(buildCheck({ name: 'orders_not_null', description: 'why', tags: ['core'] }), {
+ name: '',
+ description: '',
+ tags: [],
+ })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith(
+ '1',
+ 'view-1',
+ 'check-1',
+ expect.objectContaining({ name: '', description: '', tags: [] })
+ )
+ })
+
+ 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 openWith(null, formValues)
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()
+ expect(logic.values.isOpen).toBe(true)
+ })
+
+ 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 openWith(null, { checkType: 'not_null', columnName: 'customer_id' })
+
+ logic.actions.submitCheckForm()
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warehouseSavedQueriesChecksCreate).toHaveBeenCalledTimes(1)
+ })
+
+ it.each<[string, { detail: string; code?: string; attr?: string }, string, string]>([
+ [
+ 'a taken name beside the name field',
+ { detail: 'A check with this name already exists.', attr: 'name', code: 'name_conflict' },
+ 'name',
+ 'A check with this name already exists.',
+ ],
+ [
+ 'an unusable config beside the config field',
+ { detail: 'Invalid config for a custom_sql check.', attr: 'config' },
+ 'customSql',
+ 'Invalid config for a custom_sql check.',
+ ],
+ [
+ 'a duplicate definition beside every assertion field',
+ {
+ detail: 'A check with this definition already exists.',
+ attr: 'config',
+ code: 'duplicate_definition',
+ },
+ 'checkType',
+ 'A check with this definition already exists.',
+ ],
+ ])('keeps the draft open and shows %s', async (_case, data, field, message) => {
+ ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockRejectedValue(apiError(data))
+ await mountLogic()
+ await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT 1' })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.checkFormErrors[field as 'name']).toEqual(message)
+ expect(logic.values.serverError).toBeNull()
+ expect(logic.values.isOpen).toBe(true)
+ })
+
+ it('shows a failure with no field of its own in the modal banner', async () => {
+ ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockRejectedValue(
+ apiError({ detail: 'nope', code: 'permission_denied' }, 403)
+ )
+ await mountLogic()
+ await openWith(null, { checkType: 'not_null', columnName: 'customer_id' })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.serverError).toEqual("You don't have access to all data referenced by this check.")
+ expect(logic.values.isOpen).toBe(true)
+ })
+
+ it('hands the saved check to the surface that opened it, and offers to run it', async () => {
+ const saved = buildCheck({ id: 'check-new' })
+ ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockResolvedValue(saved)
+ await mountLogic()
+ await openWith(null, { checkType: 'not_null', columnName: 'customer_id' })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(onSaved).toHaveBeenCalledWith(saved)
+ expect(logic.values.isOpen).toBe(false)
+ const toast = (lemonToast.success as jest.Mock).mock.calls[0]
+ expect(toast[0]).toEqual('Check saved')
+ toast[1].button.action()
+ expect(onRunNow).toHaveBeenCalledWith(saved)
+ })
+
+ it('routes an edit to the subject the check belongs to, not the surface', async () => {
+ // The overview edits checks on every table and view, so the subject travels with the check.
+ ;(warehouseTablesChecksCreate as jest.Mock).mockResolvedValue(buildCheck())
+ await mountLogic({ surface: 'overview' })
+ logic.actions.openEditor(null, { subjectType: 'table', subjectId: 'table-9' }, COLUMNS)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setCheckFormValues({ checkType: 'not_null', columnName: 'customer_id' })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warehouseTablesChecksCreate).toHaveBeenCalledWith('1', 'table-9', expect.anything())
+ expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()
+ })
+
+ it('closes an untouched draft without asking', async () => {
+ await mountLogic()
+ await openWith(buildCheck())
+
+ logic.actions.requestClose()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(LemonDialog.open).not.toHaveBeenCalled()
+ expect(logic.values.isOpen).toBe(false)
+ expect(onClosed).toHaveBeenCalled()
+ })
+
+ it('asks before dropping an edited draft, and closes only on discard', async () => {
+ await mountLogic()
+ await openWith(buildCheck(), { description: 'half written' })
+
+ logic.actions.requestClose()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.isOpen).toBe(true)
+ const dialog = (LemonDialog.open as jest.Mock).mock.calls[0][0]
+ expect(dialog.title).toEqual('Discard changes?')
+ dialog.primaryButton.onClick()
+ expect(logic.values.isOpen).toBe(false)
+ })
+
+ it('closes a saved draft without asking, since it is no longer unsaved', async () => {
+ ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(
+ buildCheck({ description: 'written' })
+ )
+ await mountLogic()
+ await openWith(buildCheck(), { description: 'written' })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(LemonDialog.open).not.toHaveBeenCalled()
+ expect(logic.values.checkFormChanged).toBe(false)
+ })
+
+ it.each<[string, Record<string, unknown>, string[], number]>([
+ ['a plain edit with known columns', { checkType: 'not_null', columnName: 'customer_id' }, COLUMNS, 0],
+ ['a relationships check', { checkType: 'relationships' }, COLUMNS, 1],
+ ['a subject whose columns the surface does not know', { checkType: 'not_null' }, [], 1],
+ ])('loads the warehouse catalog only for %s', async (_case, values, columns, expected) => {
+ await mountLogic()
+ await openWith(null, values, columns)
+
+ expect((databaseTableListLogic.values as unknown as { loadCount: number }).loadCount).toEqual(expected)
+ })
+
+ it('loads the warehouse catalog once across type switches', async () => {
+ await mountLogic()
+ await openWith(null, { checkType: 'relationships' })
+
+ logic.actions.setCheckFormValues({ checkType: 'not_null', columnName: 'customer_id' })
+ logic.actions.setCheckFormValues({ checkType: 'relationships' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect((databaseTableListLogic.values as unknown as { loadCount: number }).loadCount).toEqual(1)
+ })
+})
diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.ts
new file mode 100644
index 000000000000..9b8af5690d87
--- /dev/null
+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.ts
@@ -0,0 +1,633 @@
+import { MakeLogicType, actions, 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 { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+
+import type {
+ DatabaseSchemaDataWarehouseTable,
+ DatabaseSchemaViewTable,
+} from '../../../frontend/src/queries/schema/schema-general'
+import { DataQualitySubjectRef, checksApi } from './checksApi'
+import type { DataQualityCheckApi, DataQualityCheckTypeApi } from './generated/api.schemas'
+import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi, SubjectTypeEnumApi } from './generated/api.schemas'
+
+const CHECK_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/
+
+/** Stable code the API returns when another active check already asserts the same thing. */
+const DUPLICATE_DEFINITION_CODE = 'duplicate_definition'
+
+const DENIED_REFERENCE_MESSAGE = "You don't have access to all data referenced by this check."
+
+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: '',
+}
+
+/** A warehouse table or view a relationships check can point at. */
+export interface RelationshipSubject {
+ id: string
+ name: string
+ type: SubjectTypeEnumApi
+ fields: string[]
+}
+
+export interface DataQualityCheckEditorLogicProps {
+ /** Which surface mounted this editor. One editor per surface, never one per row. */
+ surface: string
+ onSaved?: (check: DataQualityCheckApi) => void
+ onRunNow?: (check: DataQualityCheckApi) => void
+ onClosed?: () => void
+}
+
+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 {}
+ }
+}
+
+/** Only the selected type's configuration, so switching type cannot leave stale values behind. */
+function definitionPayload(form: CheckFormValues, requiresColumn: boolean): CheckDefinitionPayload {
+ return {
+ check_type: form.checkType,
+ column_name: requiresColumn ? form.columnName : '',
+ config: formToConfig(form),
+ }
+}
+
+type CheckDefinitionPayload = Pick<CheckCreatePayload, 'check_type' | 'column_name' | 'config'>
+type CheckCreatePayload = Parameters<typeof checksApi.create>[1]
+type CheckEditPayload = Parameters<typeof checksApi.partialUpdate>[2]
+
+export function checkCreatePayload(form: CheckFormValues, requiresColumn: boolean): CheckCreatePayload {
+ return {
+ ...definitionPayload(form, requiresColumn),
+ severity: form.severity,
+ tags: form.tags,
+ ...(form.name ? { name: form.name } : {}),
+ ...(form.description ? { description: form.description } : {}),
+ }
+}
+
+export function checkEditPayload(form: CheckFormValues, requiresColumn: boolean): CheckEditPayload {
+ return {
+ ...definitionPayload(form, requiresColumn),
+ severity: form.severity,
+ // Sent even when blank, unlike create: an edit is how metadata gets cleared.
+ name: form.name,
+ description: form.description,
+ tags: form.tags,
+ }
+}
+
+export 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) ?? '',
+ }
+}
+
+/** Which form field a config-level server error belongs beside, per check type. */
+function configFieldFor(checkType: CheckTypeEnumApi): keyof CheckFormValues | null {
+ switch (checkType) {
+ case CheckTypeEnumApi.AcceptedValues:
+ return 'acceptedValues'
+ case CheckTypeEnumApi.Relationships:
+ return 'toSubjectUuid'
+ case CheckTypeEnumApi.RowCount:
+ return 'rowCountMin'
+ case CheckTypeEnumApi.Freshness:
+ return 'maxAgeMinutes'
+ case CheckTypeEnumApi.CustomSql:
+ return 'customSql'
+ default:
+ return null
+ }
+}
+
+const FIELD_BY_ATTR: Record<string, keyof CheckFormValues> = {
+ name: 'name',
+ description: 'description',
+ severity: 'severity',
+ tags: 'tags',
+ check_type: 'checkType',
+ column_name: 'columnName',
+}
+
+/** The form errors a rejected save maps to. Empty means the failure belongs in the modal banner. */
+export function serverFieldErrors(
+ error: unknown,
+ checkType: CheckTypeEnumApi
+): Partial<Record<keyof CheckFormValues, string>> {
+ if (!(error instanceof ApiError) || !error.detail) {
+ return {}
+ }
+ // The whole assertion is at fault, not one field of it, so every part of it is highlighted.
+ if (error.code === DUPLICATE_DEFINITION_CODE) {
+ const configField = configFieldFor(checkType)
+ return {
+ checkType: error.detail,
+ columnName: error.detail,
+ ...(configField ? { [configField]: error.detail } : {}),
+ }
+ }
+ if (error.attr === 'config') {
+ const configField = configFieldFor(checkType)
+ return configField ? { [configField]: error.detail } : {}
+ }
+ const field = error.attr ? FIELD_BY_ATTR[error.attr] : undefined
+ return field ? { [field]: error.detail } : {}
+}
+
+function generalErrorMessage(error: unknown): string {
+ if (error instanceof ApiError && error.status === 403) {
+ return DENIED_REFERENCE_MESSAGE
+ }
+ return (error instanceof ApiError ? error.detail : null) ?? 'Could not save the check. Try again.'
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityCheckEditorLogicValues {
+ dataWarehouseTables: DatabaseSchemaDataWarehouseTable[] // databaseTableListLogic
+ databaseLoading: boolean // databaseTableListLogic
+ views: DatabaseSchemaViewTable[] // databaseTableListLogic
+ availableColumns: string[]
+ 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>
+ checkTypeByName: {
+ [k: string]: DataQualityCheckTypeApi
+ }
+ checkTypes: DataQualityCheckTypeApi[]
+ checkTypesLoading: boolean
+ editingCheck: DataQualityCheckApi | null
+ isCheckFormSubmitting: boolean
+ isCheckFormValid: boolean
+ isOpen: boolean
+ needsWarehouseCatalog: boolean
+ relationshipSubjects: RelationshipSubject[]
+ requiresColumn: boolean
+ serverError: string | null
+ showCheckFormErrors: boolean
+ subject: DataQualitySubjectRef | null
+ subjectColumns: string[]
+ warehouseCatalogRequested: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityCheckEditorLogicActions {
+ loadDatabase: (
+ args_0?:
+ | {
+ force?: boolean
+ shallow?: boolean
+ }
+ | undefined
+ ) => {
+ force?: boolean
+ shallow?: boolean
+ } // databaseTableListLogic
+ closeEditor: () => {
+ value: true
+ }
+ loadCheckTypes: () => any
+ loadCheckTypesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadCheckTypesSuccess: (
+ checkTypes: DataQualityCheckTypeApi[],
+ payload?: any
+ ) => {
+ checkTypes: DataQualityCheckTypeApi[]
+ payload?: any
+ }
+ loadWarehouseCatalog: () => {
+ value: true
+ }
+ openEditor: (
+ check: DataQualityCheckApi | null,
+ subject: DataQualitySubjectRef,
+ columns?: string[]
+ ) => {
+ check: DataQualityCheckApi | null
+ columns: string[]
+ subject: DataQualitySubjectRef
+ }
+ requestClose: () => {
+ value: true
+ }
+ resetCheckForm: (values?: CheckFormValues) => {
+ values?: CheckFormValues
+ }
+ 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>
+ }
+ setServerError: (serverError: string | null) => {
+ serverError: string | null
+ }
+ 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
+ }
+ touchCheckFormField: (key: string) => {
+ key: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityCheckEditorLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ checkTypeByName: (checkTypes: DataQualityCheckTypeApi[]) => {
+ [k: string]: DataQualityCheckTypeApi
+ }
+ relationshipSubjects: (
+ views: DatabaseSchemaViewTable[],
+ dataWarehouseTables: DatabaseSchemaDataWarehouseTable[]
+ ) => RelationshipSubject[]
+ availableColumns: (
+ subjectColumns: string[],
+ subject: DataQualitySubjectRef | null,
+ relationshipSubjects: RelationshipSubject[]
+ ) => string[]
+ requiresColumn: (
+ checkForm: CheckFormValues,
+ checkTypeByName: {
+ [k: string]: DataQualityCheckTypeApi
+ }
+ ) => boolean
+ needsWarehouseCatalog: (
+ checkForm: CheckFormValues,
+ requiresColumn: boolean,
+ subjectColumns: string[]
+ ) => boolean
+ }
+}
+
+export type dataQualityCheckEditorLogicType = MakeLogicType<
+ dataQualityCheckEditorLogicValues,
+ dataQualityCheckEditorLogicActions,
+ DataQualityCheckEditorLogicProps,
+ dataQualityCheckEditorLogicMeta
+>
+
+/**
+ * The one check editor, shared by the subject pages and the project overview.
+ *
+ * It never reaches back into whichever surface opened it: the mounting surface passes
+ * `onSaved` / `onRunNow` / `onClosed`, so refreshing rows, running a check, and restoring focus
+ * stay with the surface that knows how to do them.
+ */
+export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>([
+ props({} as DataQualityCheckEditorLogicProps),
+ key((props: DataQualityCheckEditorLogicProps) => props.surface),
+ path((key) => ['products', 'data_quality', 'frontend', 'dataQualityCheckEditorLogic', key]),
+ connect(() => ({
+ actions: [databaseTableListLogic, ['loadDatabase']],
+ values: [databaseTableListLogic, ['views', 'dataWarehouseTables', 'databaseLoading']],
+ })),
+ actions({
+ openEditor: (check: DataQualityCheckApi | null, subject: DataQualitySubjectRef, columns: string[] = []) => ({
+ check,
+ subject,
+ columns,
+ }),
+ requestClose: true,
+ closeEditor: true,
+ setServerError: (serverError: string | null) => ({ serverError }),
+ loadWarehouseCatalog: true,
+ }),
+ loaders(({ values }) => ({
+ checkTypes: [
+ [] as DataQualityCheckTypeApi[],
+ {
+ loadCheckTypes: async () =>
+ values.subject ? await checksApi.checkTypes(values.subject) : values.checkTypes,
+ },
+ ],
+ })),
+ reducers({
+ isOpen: [
+ false,
+ {
+ openEditor: () => true,
+ closeEditor: () => false,
+ },
+ ],
+ editingCheck: [
+ null as DataQualityCheckApi | null,
+ {
+ openEditor: (_, { check }) => check,
+ closeEditor: () => null,
+ },
+ ],
+ subject: [
+ null as DataQualitySubjectRef | null,
+ {
+ openEditor: (_, { subject }) => subject,
+ },
+ ],
+ subjectColumns: [
+ [] as string[],
+ {
+ openEditor: (_, { columns }) => columns,
+ },
+ ],
+ // One request per editor instance: a type switch back to relationships must not refetch.
+ warehouseCatalogRequested: [
+ false,
+ {
+ loadWarehouseCatalog: () => true,
+ },
+ ],
+ serverError: [
+ null as string | null,
+ {
+ setServerError: (_, { serverError }) => serverError,
+ openEditor: () => null,
+ closeEditor: () => null,
+ },
+ ],
+ }),
+ selectors({
+ checkTypeByName: [
+ (s) => [s.checkTypes],
+ (checkTypes: DataQualityCheckTypeApi[]) =>
+ Object.fromEntries(checkTypes.map((checkType) => [checkType.check_type, checkType])),
+ ],
+ relationshipSubjects: [
+ (s) => [s.views, s.dataWarehouseTables],
+ (views: any[], dataWarehouseTables: any[]): RelationshipSubject[] =>
+ // Only warehouse subjects carry the uuid a relationships check references;
+ // PostHog-native and system tables have no check subject to point at.
+ [
+ ...views.map((view) => ({ ...view, type: SubjectTypeEnumApi.View })),
+ ...dataWarehouseTables.map((table) => ({ ...table, type: SubjectTypeEnumApi.Table })),
+ ]
+ .filter((subject) => !!subject.id)
+ .map((subject) => ({
+ id: subject.id,
+ name: subject.name,
+ type: subject.type,
+ fields: Object.keys(subject.fields ?? {}),
+ })),
+ ],
+ availableColumns: [
+ (s) => [s.subjectColumns, s.subject, s.relationshipSubjects],
+ (
+ subjectColumns: string[],
+ subject: DataQualitySubjectRef | null,
+ relationshipSubjects: RelationshipSubject[]
+ ) =>
+ subjectColumns.length
+ ? subjectColumns
+ : (relationshipSubjects.find((candidate) => candidate.id === subject?.subjectId)?.fields ?? []),
+ ],
+ }),
+ 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, or
+ // while the check-type catalog is still arriving, neither of which the button's own
+ // disabled state can prevent. Without the catalog there is no column requirement to
+ // validate against, so the payload would omit column_name and be rejected.
+ // Only while it is in flight: a catalog that failed to load must not wedge the form.
+ const catalogPending = values.checkTypesLoading && !values.checkTypes.length
+ if (cache.savingCheck || !values.subject || catalogPending) {
+ return
+ }
+ cache.savingCheck = true
+ actions.setServerError(null)
+ const editing = values.editingCheck
+ try {
+ const saved = editing
+ ? await checksApi.partialUpdate(
+ values.subject,
+ editing.id,
+ checkEditPayload(form, values.requiresColumn)
+ )
+ : await checksApi.create(values.subject, checkCreatePayload(form, values.requiresColumn))
+ // Defaults come from the saved row before closing, so a clean form never trips
+ // the discard confirmation on the way out.
+ actions.resetCheckForm(checkToForm(saved))
+ actions.closeEditor()
+ props.onSaved?.(saved)
+ lemonToast.success('Check saved', {
+ button: { label: 'Run now', action: () => props.onRunNow?.(saved) },
+ })
+ } catch (error) {
+ const fieldErrors = serverFieldErrors(error, form.checkType)
+ if (Object.keys(fieldErrors).length) {
+ actions.setCheckFormManualErrors(fieldErrors)
+ } else {
+ actions.setServerError(generalErrorMessage(error))
+ }
+ throw error
+ } finally {
+ cache.savingCheck = false
+ }
+ },
+ },
+ })),
+ selectors({
+ requiresColumn: [
+ (s) => [s.checkForm, s.checkTypeByName],
+ (checkForm: CheckFormValues, checkTypeByName: Record<string, DataQualityCheckTypeApi>) =>
+ !!checkTypeByName[checkForm.checkType]?.requires_column,
+ ],
+ needsWarehouseCatalog: [
+ (s) => [s.checkForm, s.requiresColumn, s.subjectColumns],
+ (checkForm: CheckFormValues, requiresColumn: boolean, subjectColumns: string[]) =>
+ // Relationships needs every subject to point at; anything else only needs the
+ // catalog when the surface that opened the editor could not supply the columns.
+ checkForm.checkType === CheckTypeEnumApi.Relationships || (requiresColumn && !subjectColumns.length),
+ ],
+ }),
+ listeners(({ props, values, actions }) => {
+ const ensureWarehouseCatalog = (): void => {
+ if (values.warehouseCatalogRequested || !values.needsWarehouseCatalog) {
+ return
+ }
+ actions.loadWarehouseCatalog()
+ }
+
+ return {
+ openEditor: ({ check }) => {
+ actions.resetCheckForm(check ? checkToForm(check) : EMPTY_CHECK_FORM)
+ if (!values.checkTypes.length) {
+ actions.loadCheckTypes()
+ }
+ ensureWarehouseCatalog()
+ },
+ setCheckFormValues: () => {
+ if (values.isOpen) {
+ ensureWarehouseCatalog()
+ }
+ },
+ loadWarehouseCatalog: () => {
+ actions.loadDatabase()
+ },
+ requestClose: () => {
+ if (!values.checkFormChanged) {
+ actions.closeEditor()
+ return
+ }
+ LemonDialog.open({
+ title: 'Discard changes?',
+ description: 'Your unsaved changes will be lost.',
+ primaryButton: {
+ children: 'Discard changes',
+ status: 'danger',
+ onClick: () => actions.closeEditor(),
+ },
+ secondaryButton: { children: 'Keep editing' },
+ })
+ },
+ closeEditor: () => {
+ props.onClosed?.()
+ },
+ }
+ }),
+])
diff --git a/products/data_quality/frontend/dataQualityChecksLogic.test.ts b/products/data_quality/frontend/dataQualityChecksLogic.test.ts
index e51ed4121c16..7dc9be13e157 100644
--- a/products/data_quality/frontend/dataQualityChecksLogic.test.ts
+++ b/products/data_quality/frontend/dataQualityChecksLogic.test.ts
@@ -9,8 +9,6 @@ import {
warehouseSavedQueriesCheckSuiteRunsCheckRunsList,
warehouseSavedQueriesCheckSuiteRunsList,
warehouseSavedQueriesCheckSuiteRunsRetrieve,
- warehouseSavedQueriesChecksCheckTypesList,
- warehouseSavedQueriesChecksCreate,
warehouseSavedQueriesChecksDestroy,
warehouseSavedQueriesChecksHealthRetrieve,
warehouseSavedQueriesChecksList,
@@ -79,16 +77,6 @@ jest.mock('./generated/api', () => ({
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',
@@ -132,12 +120,6 @@ describe('dataQualityChecksLogic', () => {
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()
@@ -155,7 +137,6 @@ describe('dataQualityChecksLogic', () => {
})
;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })
;(warehouseTablesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })
- ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG)
})
afterEach(() => {
@@ -187,152 +168,6 @@ describe('dataQualityChecksLogic', () => {
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()
diff --git a/products/data_quality/frontend/dataQualityChecksLogic.ts b/products/data_quality/frontend/dataQualityChecksLogic.ts
index d4a0bbc06391..a0e81075acbf 100644
--- a/products/data_quality/frontend/dataQualityChecksLogic.ts
+++ b/products/data_quality/frontend/dataQualityChecksLogic.ts
@@ -1,32 +1,22 @@
-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 { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
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 { DataQualitySubjectRef, DataQualitySubjectType, apiErrorDetail, 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'
+import { openFailingRowsInSqlEditor } from './openFailingRows'
+import { isTerminalSuiteRun, suiteRunOutcome, suiteRunPollListeners, suiteRunSummary } from './suiteRuns'
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'
@@ -46,44 +36,6 @@ export interface DataQualityChecksLogicProps {
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 }
}
@@ -92,83 +44,6 @@ 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
@@ -180,36 +55,16 @@ function checkSortRank(check: DataQualityCheckApi): number {
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[]
@@ -219,23 +74,9 @@ export interface dataQualityChecksLogicValues {
// 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
}
@@ -245,21 +86,6 @@ export interface dataQualityChecksLogicActions {
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,
@@ -308,8 +134,8 @@ export interface dataQualityChecksLogicActions {
suiteRuns: DataQualitySuiteRunApi[]
payload?: any
}
- openCheckModal: (check?: DataQualityCheckApi | null) => {
- check: DataQualityCheckApi | null
+ openFailingRows: (checkId: string) => {
+ checkId: string
}
pollActiveSuiteRun: () => {
value: true
@@ -317,9 +143,6 @@ export interface dataQualityChecksLogicActions {
removeCheck: (checkId: string) => {
checkId: string
}
- resetCheckForm: (values?: CheckFormValues) => {
- values?: CheckFormValues
- }
runAll: () => {
value: true
}
@@ -335,19 +158,6 @@ export interface dataQualityChecksLogicActions {
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,
@@ -370,9 +180,6 @@ export interface dataQualityChecksLogicActions {
setRunAllInFlight: (inFlight: boolean) => {
inFlight: boolean
}
- setServerError: (serverError: string | null) => {
- serverError: string | null
- }
setSuiteRunCheckRuns: (
suiteRunId: string,
runs: DataQualityCheckRunApi[]
@@ -380,22 +187,6 @@ export interface dataQualityChecksLogicActions {
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
@@ -403,9 +194,6 @@ export interface dataQualityChecksLogicActions {
checkId: string
enabled: boolean
}
- touchCheckFormField: (key: string) => {
- key: string
- }
upsertCheck: (check: DataQualityCheckApi) => {
check: DataQualityCheckApi
}
@@ -417,9 +205,6 @@ export interface dataQualityChecksLogicMeta {
__keaTypeGenInternalSelectorTypes: {
enabledChecksCount: (checks: DataQualityCheckApi[]) => number
isSuiteRunning: (activeSuiteRun: DataQualitySuiteRunApi | null, pollTimedOut: boolean) => boolean
- checkTypeByName: (checkTypes: DataQualityCheckTypeApi[]) => {
- [k: string]: DataQualityCheckTypeApi
- }
sortedChecks: (checks: DataQualityCheckApi[]) => DataQualityCheckApi[]
}
}
@@ -435,13 +220,7 @@ 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 }),
@@ -457,6 +236,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([
setPollTimedOut: true,
adoptRunningSuiteRun: true,
loadCheckRuns: (checkId: string) => ({ checkId }),
+ openFailingRows: (checkId: string) => ({ checkId }),
setCheckRuns: (checkId: string, runs: DataQualityCheckRunApi[]) => ({ checkId, runs }),
loadSuiteRunCheckRuns: (suiteRunId: string) => ({ suiteRunId }),
setSuiteRunCheckRuns: (suiteRunId: string, runs: DataQualityCheckRunApi[]) => ({ suiteRunId, runs }),
@@ -475,12 +255,6 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([
loadHealth: async () => await checksApi.health(subjectRef(props)),
},
],
- checkTypes: [
- [] as DataQualityCheckTypeApi[],
- {
- loadCheckTypes: async () => await checksApi.checkTypes(subjectRef(props)),
- },
- ],
suiteRuns: [
[] as DataQualitySuiteRunApi[],
{
@@ -489,28 +263,6 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([
],
})),
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)
@@ -586,11 +338,6 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([
(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[]) =>
@@ -601,298 +348,176 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([
),
],
}),
- 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) {
+ listeners(({ props, values, actions, cache }) => {
+ // Assigned one by one rather than spread: kea-typegen walks this object literal and crashes
+ // on a spread element, which has no property name.
+ const poll = suiteRunPollListeners({
+ retrieve: (suiteRunId) => checksApi.suiteRunRetrieve(subjectRef(props), suiteRunId),
+ // 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.
+ onPollError: (error) => {
+ if (!isForbidden(error)) {
+ return false
+ }
+ actions.setAccessDenied()
+ return true
+ },
+ cache,
+ values,
+ actions,
+ })
+ return {
+ setActiveSuiteRun: poll.setActiveSuiteRun,
+ scheduleSuiteRunPoll: poll.scheduleSuiteRunPoll,
+ pollActiveSuiteRun: poll.pollActiveSuiteRun,
+ loadChecksFailure: ({ errorObject }) => {
+ if (isForbidden(errorObject)) {
+ actions.setAccessDenied()
+ }
+ },
+ loadHealthFailure: ({ errorObject }) => {
+ if (isForbidden(errorObject)) {
+ actions.setAccessDenied()
+ }
+ },
+ deleteCheck: async ({ checkId }) => {
+ if (values.pendingCheckActions.deleting[checkId]) {
return
}
- cache.savingCheck = true
- actions.setServerError(null)
- const editing = values.editingCheck
+ actions.setCheckPending('deleting', checkId, true)
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()
+ await checksApi.destroy(subjectRef(props), checkId)
+ actions.removeCheck(checkId)
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
+ lemonToast.error(apiErrorDetail(error) ?? 'Could not delete the check. Try again.')
} finally {
- cache.savingCheck = false
+ actions.setCheckPending('deleting', checkId, 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)
+ toggleCheckEnabled: async ({ checkId, enabled }) => {
+ if (values.pendingCheckActions.toggling[checkId]) {
+ return
}
- } 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)
+ 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)
}
- } 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()
+ },
+ 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)
+ }
+ },
+ openFailingRows: async ({ checkId }) => {
+ await openFailingRowsInSqlEditor({
+ cachedRuns: values.checkRunsByCheckId[checkId],
+ fetchRuns: () => checksApi.runs(subjectRef(props), checkId),
+ onRunsFetched: (runs) => actions.setCheckRuns(checkId, runs),
+ })
+ },
+ loadSuiteRunCheckRuns: async ({ suiteRunId }) => {
+ if (values.pendingCheckActions.loadingSuiteRunRuns[suiteRunId]) {
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()
+ 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.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)
+ 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)
}
- } catch (error) {
- if (isForbidden(error)) {
- actions.setAccessDenied()
+ },
+ 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)
}
- }
- },
- })),
+ },
+ 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()
+ }
+ const outcome = suiteRunOutcome(suiteRun)
+ if (outcome === 'empty') {
+ lemonToast.info('No enabled checks to run')
+ } else if (outcome === 'errored') {
+ lemonToast.error(suiteRun.error || "Couldn't run checks. Try again.")
+ } else if (outcome === 'warning') {
+ 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()
diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.ts
index ba4565499a70..227229deb162 100644
--- a/products/data_quality/frontend/generated/api.schemas.ts
+++ b/products/data_quality/frontend/generated/api.schemas.ts
@@ -7,45 +7,6 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
-export interface DataQualitySuiteRunApi {
- readonly id: string
- /** manual, materialization, or source_sync. */
- readonly trigger: string
- /** running, completed, failed, or empty (nothing matched the trigger). */
- readonly status: string
- /**
- * '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
- /**
- * Set when the run targets exactly one subject.
- * @nullable
- */
- readonly subject_uuid: string | null
- readonly workflow_id: string
- readonly checks_passed: number
- readonly checks_failed: number
- readonly checks_errored: number
- readonly checks_skipped: number
- /** @nullable */
- readonly started_at: string | null
- /** @nullable */
- readonly finished_at: string | null
- /** Why the suite itself failed, as opposed to an individual check. */
- readonly error: string
- readonly created_at: string
-}
-
-export interface PaginatedDataQualitySuiteRunListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: DataQualitySuiteRunApi[]
-}
-
/**
* * `table` - table
* * `view` - view
@@ -78,53 +39,6 @@ export const CheckTypeEnumApi = {
CustomSql: 'custom_sql',
} as const
-export interface DataQualityCheckRunApi {
- readonly id: string
- /**
- * The definition executed. Nulled rather than cascaded so history outlives hard deletes.
- * @nullable
- */
- readonly quality_check: string | null
- readonly suite_run: string
- readonly subject_type: SubjectTypeEnumApi
- readonly subject_uuid: string
- readonly subject_name: string
- /** Which assertion this run made.
- *
- * * `not_null` - not_null
- * * `unique` - unique
- * * `accepted_values` - accepted_values
- * * `relationships` - relationships
- * * `row_count` - row_count
- * * `freshness` - freshness
- * * `custom_sql` - custom_sql */
- readonly check_type: CheckTypeEnumApi
- readonly column_name: string
- /** passed, failed, errored, or skipped. */
- readonly status: string
- /**
- * Rows violating the assertion. Null for bounds checks like row_count.
- * @nullable
- */
- readonly failed_row_count: number | null
- /**
- * The check's headline number, recorded on passes too.
- * @nullable
- */
- readonly observed_value: number | null
- /** The HogQL that ran. Re-run it to see the offending rows. */
- readonly compiled_query: string
- /** Compilation or execution failure, when status is 'errored'. */
- readonly error: string
- /** @nullable */
- readonly duration_ms: number | null
- /** @nullable */
- readonly started_at: string | null
- /** @nullable */
- readonly finished_at: string | null
- readonly created_at: string
-}
-
/**
* * `error` - error
* * `warn` - warn
@@ -205,6 +119,263 @@ export interface UserBasicApi {
role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
}
+/**
+ * Type-specific configuration, validated against the check type's JSON schema.
+ */
+export type DataQualityOverviewCheckApiConfig = { [key: string]: unknown }
+
+/**
+ * A check plus where its subject can be opened, for the project-wide list.
+ *
+ * The per-subject surfaces already know their parent; only this one lists checks across every
+ * table and view, so only this one needs to say where each subject lives. The ids are resolved
+ * for a whole page at once and handed in through ``subject_locations`` in the context.
+ */
+export interface DataQualityOverviewCheckApi {
+ readonly id: string
+ /**
+ * Optional identifier-safe handle, unique per project. Omit to address the check by id.
+ * @maxLength 128
+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$
+ */
+ name?: string
+ /** Why this check exists and what a failure means. */
+ description?: string
+ /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).
+ *
+ * * `table` - table
+ * * `view` - view */
+ readonly subject_type: SubjectTypeEnumApi
+ /**
+ * Id of the table or view being checked -- the parent resource in the URL.
+ * @nullable
+ */
+ readonly subject_uuid: string | null
+ /** Queryable name of the subject, refreshed on every run. */
+ readonly subject_name: string
+ /** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */
+ readonly subject_status: string
+ /**
+ * Column the check applies to. Omit for table-scoped types like row_count.
+ * @maxLength 400
+ */
+ column_name?: string
+ /** Which assertion to make. Determines the shape of config; see /check_types/.
+ *
+ * * `not_null` - not_null
+ * * `unique` - unique
+ * * `accepted_values` - accepted_values
+ * * `relationships` - relationships
+ * * `row_count` - row_count
+ * * `freshness` - freshness
+ * * `custom_sql` - custom_sql */
+ check_type: CheckTypeEnumApi
+ /** Type-specific configuration, validated against the check type's JSON schema. */
+ config?: DataQualityOverviewCheckApiConfig
+ /** 'error' failures mark the subject failing and notify; 'warn' failures only surface.
+ *
+ * * `error` - error
+ * * `warn` - warn */
+ severity?: DataQualityCheckSeverityEnumApi
+ /** Disabled checks are never run by any trigger. */
+ enabled?: boolean
+ /** Free-form string labels for grouping and filtering. */
+ tags?: string[]
+ /**
+ * Email of the human accountable for this check, or null.
+ * @nullable
+ */
+ readonly owner: string | null
+ /**
+ * When the check last executed.
+ * @nullable
+ */
+ readonly last_run_at: string | null
+ /** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */
+ readonly last_status: string
+ /**
+ * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.
+ * @nullable
+ */
+ readonly last_succeeded_at: string | null
+ /** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */
+ readonly fingerprint: string
+ /** Whether a human ('user') or an agent ('ai_generated') authored this check.
+ *
+ * * `user` - user
+ * * `ai_generated` - ai_generated */
+ created_source?: CreatedSourceEnumApi
+ /**
+ * Model that generated the check, if AI-authored.
+ * @maxLength 128
+ */
+ ai_model?: string
+ /**
+ * AI author's confidence in the check, 0-1.
+ * @minimum 0
+ * @maximum 1
+ * @nullable
+ */
+ confidence?: number | null
+ /** AI author's reasoning, surfaced as review context. */
+ reasoning?: string
+ /** User who first created this check. */
+ readonly created_by: UserBasicApi
+ readonly created_at: string
+ /** @nullable */
+ readonly updated_at: string | null
+ /**
+ * Data modeling node of the view this check audits, or null when it is on no DAG or the subject is a table.
+ * @nullable
+ */
+ readonly subject_node_id: string | null
+ /**
+ * Warehouse source of the table this check audits, or null when the subject is a view.
+ * @nullable
+ */
+ readonly subject_source_id: string | null
+ /**
+ * Warehouse source schema of the table this check audits, or null when the subject is a view.
+ * @nullable
+ */
+ readonly subject_schema_id: string | null
+}
+
+export interface PaginatedDataQualityOverviewCheckListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: DataQualityOverviewCheckApi[]
+}
+
+/**
+ * Per-subject rollup, the same rule the information_schema.data_quality_health table uses.
+ */
+export interface DataQualitySubjectHealthApi {
+ /** 'table' or 'view'. */
+ subject_type: string
+ /** Id of the table or view. */
+ subject_uuid: string
+ /** failing (an error-severity check failed), erroring (a check could not run), warn (only warn-severity failures), healthy, or unknown (nothing has run yet). */
+ health: string
+ /** How many enabled, non-deleted checks cover this subject. */
+ checks_total: number
+ /** How many of those checks last reported a failure. */
+ checks_failing: number
+}
+
+export interface DataQualitySuiteRunApi {
+ readonly id: string
+ /** manual, materialization, or source_sync. */
+ readonly trigger: string
+ /** running, completed, failed, or empty (nothing matched the trigger). */
+ readonly status: string
+ /**
+ * '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
+ /**
+ * Set when the run targets exactly one subject.
+ * @nullable
+ */
+ readonly subject_uuid: string | null
+ readonly workflow_id: string
+ readonly checks_passed: number
+ readonly checks_failed: number
+ readonly checks_errored: number
+ readonly checks_skipped: number
+ /** @nullable */
+ readonly started_at: string | null
+ /** @nullable */
+ readonly finished_at: string | null
+ /** Why the suite itself failed, as opposed to an individual check. */
+ readonly error: string
+ readonly created_at: string
+}
+
+export interface PaginatedDataQualitySuiteRunListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: DataQualitySuiteRunApi[]
+}
+
+/**
+ * What to run in a project-wide suite run.
+ */
+export interface DataQualityRunRequestApi {
+ /** Ids of the checks to run. Omit to run every enabled check in the project. */
+ check_ids?: string[]
+}
+
+/**
+ * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.
+ * @nullable
+ */
+export type DataQualityCheckRunApiCheckConfig = { [key: string]: unknown } | null
+
+export interface DataQualityCheckRunApi {
+ readonly id: string
+ /**
+ * The definition executed. Nulled rather than cascaded so history outlives hard deletes.
+ * @nullable
+ */
+ readonly quality_check: string | null
+ readonly suite_run: string
+ readonly subject_type: SubjectTypeEnumApi
+ readonly subject_uuid: string
+ readonly subject_name: string
+ /** Which assertion this run made.
+ *
+ * * `not_null` - not_null
+ * * `unique` - unique
+ * * `accepted_values` - accepted_values
+ * * `relationships` - relationships
+ * * `row_count` - row_count
+ * * `freshness` - freshness
+ * * `custom_sql` - custom_sql */
+ readonly check_type: CheckTypeEnumApi
+ readonly column_name: string
+ /**
+ * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.
+ * @nullable
+ */
+ readonly check_config: DataQualityCheckRunApiCheckConfig
+ /** Severity this run was judged at. Null for runs recorded before snapshots existed.
+ *
+ * * `error` - error
+ * * `warn` - warn */
+ readonly check_severity: DataQualityCheckSeverityEnumApi | null
+ /** passed, failed, errored, or skipped. */
+ readonly status: string
+ /**
+ * Rows violating the assertion. Null for bounds checks like row_count.
+ * @nullable
+ */
+ readonly failed_row_count: number | null
+ /**
+ * The check's headline number, recorded on passes too.
+ * @nullable
+ */
+ readonly observed_value: number | null
+ /** The HogQL that ran. Re-run it to see the offending rows. */
+ readonly compiled_query: string
+ /** Compilation or execution failure, when status is 'errored'. */
+ readonly error: string
+ /** @nullable */
+ readonly duration_ms: number | null
+ /** @nullable */
+ readonly started_at: string | null
+ /** @nullable */
+ readonly finished_at: string | null
+ readonly created_at: string
+}
+
/**
* Type-specific configuration, validated against the check type's JSON schema.
*/
@@ -275,6 +446,11 @@ export interface DataQualityCheckApi {
readonly last_run_at: string | null
/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */
readonly last_status: string
+ /**
+ * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.
+ * @nullable
+ */
+ readonly last_succeeded_at: string | null
/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */
readonly fingerprint: string
/** Whether a human ('user') or an agent ('ai_generated') authored this check.
@@ -382,6 +558,11 @@ export interface PatchedDataQualityCheckApi {
readonly last_run_at?: string | null
/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */
readonly last_status?: string
+ /**
+ * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.
+ * @nullable
+ */
+ readonly last_succeeded_at?: string | null
/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */
readonly fingerprint?: string
/** Whether a human ('user') or an agent ('ai_generated') authored this check.
@@ -429,20 +610,26 @@ export interface DataQualityCheckTypeApi {
config_schema: DataQualityCheckTypeApiConfigSchema
}
-/**
- * Per-subject rollup, the same rule the information_schema.data_quality_health table uses.
- */
-export interface DataQualitySubjectHealthApi {
- /** 'table' or 'view'. */
- subject_type: string
- /** Id of the table or view. */
- subject_uuid: string
- /** failing (an error-severity check failed), erroring (a check could not run), warn (only warn-severity failures), healthy, or unknown (nothing has run yet). */
- health: string
- /** How many enabled, non-deleted checks cover this subject. */
- checks_total: number
- /** How many of those checks last reported a failure. */
- checks_failing: number
+export type DataQualityChecksListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type DataQualityRunsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
}
export type WarehouseSavedQueriesCheckSuiteRunsListParams = {
diff --git a/products/data_quality/frontend/generated/api.ts b/products/data_quality/frontend/generated/api.ts
index 60c69cc7acef..268ca67d5cd6 100644
--- a/products/data_quality/frontend/generated/api.ts
+++ b/products/data_quality/frontend/generated/api.ts
@@ -12,9 +12,13 @@ import type {
DataQualityCheckApi,
DataQualityCheckRunApi,
DataQualityCheckTypeApi,
+ DataQualityChecksListParams,
+ DataQualityRunRequestApi,
+ DataQualityRunsListParams,
DataQualitySubjectHealthApi,
DataQualitySuiteRunApi,
PaginatedDataQualityCheckListApi,
+ PaginatedDataQualityOverviewCheckListApi,
PaginatedDataQualitySuiteRunListApi,
PatchedDataQualityCheckApi,
WarehouseSavedQueriesCheckSuiteRunsListParams,
@@ -40,6 +44,133 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getDataQualityChecksListUrl = (projectId: string, params?: DataQualityChecksListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/data_quality_checks/?${stringifiedParams}`
+ : `/api/projects/${projectId}/data_quality_checks/`
+}
+
+/**
+ * Every check in the project, and the health of every subject that has one.
+ *
+ * The per-subject surfaces answer "what is wrong with this table". This answers "what is wrong
+ * across the project", which they cannot: each is nested under one parent. Read-only -- authoring
+ * still happens against the subject that owns the check.
+ */
+export const dataQualityChecksList = async (
+ projectId: string,
+ params?: DataQualityChecksListParams,
+ options?: RequestInit
+): Promise<PaginatedDataQualityOverviewCheckListApi> => {
+ return apiMutator<PaginatedDataQualityOverviewCheckListApi>(getDataQualityChecksListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getDataQualityChecksHealthListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_quality_checks/health/`
+}
+
+/**
+ * Health rollup for every table and view in the project that has checks.
+ */
+export const dataQualityChecksHealthList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<DataQualitySubjectHealthApi[]> => {
+ return apiMutator<DataQualitySubjectHealthApi[]>(getDataQualityChecksHealthListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getDataQualityRunsListUrl = (projectId: string, params?: DataQualityRunsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/data_quality_runs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/data_quality_runs/`
+}
+
+/**
+ * Project-wide check runs: start one over a selection, and read every run the project has had.
+ *
+ * The per-subject surfaces only serve runs scoped to their own subject, so this is where a sweep
+ * across several subjects -- a manual project-wide run, a materialization, a source sync -- is
+ * readable. Scoped to `warehouse_objects` because it spans tables and views at once.
+ */
+export const dataQualityRunsList = async (
+ projectId: string,
+ params?: DataQualityRunsListParams,
+ options?: RequestInit
+): Promise<PaginatedDataQualitySuiteRunListApi> => {
+ return apiMutator<PaginatedDataQualitySuiteRunListApi>(getDataQualityRunsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getDataQualityRunsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_quality_runs/`
+}
+
+/**
+ * Run the named checks now, or every enabled check in the project when none are named. Returns the suite run to poll for the report.
+ */
+export const dataQualityRunsCreate = async (
+ projectId: string,
+ dataQualityRunRequestApi?: DataQualityRunRequestApi,
+ options?: RequestInit
+): Promise<DataQualitySuiteRunApi> => {
+ return apiMutator<DataQualitySuiteRunApi>(getDataQualityRunsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataQualityRunRequestApi),
+ })
+}
+
+export const getDataQualityRunsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_quality_runs/${id}/`
+}
+
+/**
+ * Project-wide check runs: start one over a selection, and read every run the project has had.
+ *
+ * The per-subject surfaces only serve runs scoped to their own subject, so this is where a sweep
+ * across several subjects -- a manual project-wide run, a materialization, a source sync -- is
+ * readable. Scoped to `warehouse_objects` because it spans tables and views at once.
+ */
+export const dataQualityRunsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DataQualitySuiteRunApi> => {
+ return apiMutator<DataQualitySuiteRunApi>(getDataQualityRunsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getWarehouseSavedQueriesCheckSuiteRunsListUrl = (
projectId: string,
savedQueryId: string,
@@ -213,7 +344,7 @@ export const getWarehouseSavedQueriesChecksUpdateUrl = (projectId: string, saved
}
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const warehouseSavedQueriesChecksUpdate = async (
projectId: string,
@@ -235,7 +366,7 @@ export const getWarehouseSavedQueriesChecksPartialUpdateUrl = (projectId: string
}
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const warehouseSavedQueriesChecksPartialUpdate = async (
projectId: string,
@@ -534,7 +665,7 @@ export const getWarehouseTablesChecksUpdateUrl = (projectId: string, tableId: st
}
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const warehouseTablesChecksUpdate = async (
projectId: string,
@@ -556,7 +687,7 @@ export const getWarehouseTablesChecksPartialUpdateUrl = (projectId: string, tabl
}
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const warehouseTablesChecksPartialUpdate = async (
projectId: string,
diff --git a/products/data_quality/frontend/generated/api.zod.ts b/products/data_quality/frontend/generated/api.zod.ts
index 78415dc3c92f..fdec81d706bf 100644
--- a/products/data_quality/frontend/generated/api.zod.ts
+++ b/products/data_quality/frontend/generated/api.zod.ts
@@ -9,6 +9,18 @@
*/
import * as zod from 'zod'
+/**
+ * Run the named checks now, or every enabled check in the project when none are named. Returns the suite run to poll for the report.
+ */
+export const DataQualityRunsCreateBody = /* @__PURE__ */ zod
+ .object({
+ check_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe('Ids of the checks to run. Omit to run every enabled check in the project.'),
+ })
+ .describe('What to run in a project-wide suite run.')
+
/**
* Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.
*/
@@ -80,7 +92,7 @@ export const WarehouseSavedQueriesChecksCreateBody = /* @__PURE__ */ zod
.describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const warehouseSavedQueriesChecksUpdateBodyNameMax = 128
@@ -150,7 +162,7 @@ export const WarehouseSavedQueriesChecksUpdateBody = /* @__PURE__ */ zod
.describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const warehouseSavedQueriesChecksPartialUpdateBodyNameMax = 128
@@ -291,7 +303,7 @@ export const WarehouseTablesChecksCreateBody = /* @__PURE__ */ zod
.describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const warehouseTablesChecksUpdateBodyNameMax = 128
@@ -361,7 +373,7 @@ export const WarehouseTablesChecksUpdateBody = /* @__PURE__ */ zod
.describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const warehouseTablesChecksPartialUpdateBodyNameMax = 128
diff --git a/products/data_quality/frontend/openFailingRows.ts b/products/data_quality/frontend/openFailingRows.ts
new file mode 100644
index 000000000000..1fcc695bee62
--- /dev/null
+++ b/products/data_quality/frontend/openFailingRows.ts
@@ -0,0 +1,45 @@
+import { router } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { urls } from 'scenes/urls'
+
+import { apiErrorDetail } from './checksApi'
+import type { DataQualityCheckRunApi } from './generated/api.schemas'
+import { latestFailingRowsQuery } from './suiteRuns'
+
+/**
+ * Send the caller to this check's failing rows in the SQL editor.
+ *
+ * The rows that failed only exist in the run's compiled query, and runs load lazily, so a caller
+ * that has not expanded the check yet passes `fetchRuns` and gets them loaded here.
+ */
+export async function openFailingRowsInSqlEditor({
+ cachedRuns,
+ fetchRuns,
+ onRunsFetched,
+}: {
+ cachedRuns: DataQualityCheckRunApi[] | undefined
+ fetchRuns: () => Promise<DataQualityCheckRunApi[]>
+ onRunsFetched: (runs: DataQualityCheckRunApi[]) => void
+}): Promise<void> {
+ let runs = cachedRuns
+ if (!runs) {
+ try {
+ runs = await fetchRuns()
+ onRunsFetched(runs)
+ } catch (error) {
+ lemonToast.error(apiErrorDetail(error) ?? 'Could not load the run history. Try again.')
+ return
+ }
+ }
+ const query = latestFailingRowsQuery(runs)
+ if (!query) {
+ lemonToast.info(
+ runs.length
+ ? 'The query for this check is no longer kept. Run the check to see its failing rows.'
+ : "This check hasn't run yet. Run it to see its failing rows."
+ )
+ return
+ }
+ router.actions.push(urls.sqlEditor({ query }))
+}
diff --git a/products/data_quality/frontend/overview/DataQualityOverview.test.tsx b/products/data_quality/frontend/overview/DataQualityOverview.test.tsx
new file mode 100644
index 000000000000..6c6c7eb43c7e
--- /dev/null
+++ b/products/data_quality/frontend/overview/DataQualityOverview.test.tsx
@@ -0,0 +1,220 @@
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import {
+ dataQualityChecksHealthList,
+ dataQualityChecksList,
+ dataQualityRunsCreate,
+ dataQualityRunsRetrieve,
+ warehouseSavedQueriesChecksRunsList,
+} from 'products/data_quality/frontend/generated/api'
+import type { DataQualityOverviewCheckApi } from 'products/data_quality/frontend/generated/api.schemas'
+
+import { DataQualityOverview } from './DataQualityOverview'
+import { subjectDisclosureId } from './dataQualityOverviewLogic'
+
+jest.mock('lib/api', () => ({
+ __esModule: true,
+ default: {},
+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },
+ ApiError: class ApiError extends Error {},
+}))
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },
+}))
+
+jest.mock('products/data_quality/frontend/generated/api', () => ({
+ dataQualityChecksList: jest.fn(),
+ dataQualityChecksHealthList: jest.fn(),
+ dataQualityRunsCreate: jest.fn(),
+ dataQualityRunsRetrieve: jest.fn(),
+ warehouseSavedQueriesChecksRunsList: jest.fn(),
+ warehouseSavedQueriesChecksDestroy: jest.fn(),
+ warehouseTablesChecksDestroy: jest.fn(),
+ warehouseSavedQueriesChecksCheckTypesList: jest.fn(),
+ warehouseTablesChecksCheckTypesList: jest.fn(),
+ warehouseSavedQueriesChecksCreate: jest.fn(),
+ warehouseSavedQueriesChecksPartialUpdate: jest.fn(),
+ warehouseTablesChecksCreate: jest.fn(),
+ warehouseTablesChecksPartialUpdate: jest.fn(),
+}))
+
+function buildCheck(
+ id: string,
+ subject: string,
+ overrides: Partial<DataQualityOverviewCheckApi> = {}
+): DataQualityOverviewCheckApi {
+ return {
+ id,
+ name: `${subject}_${id}`,
+ subject_type: 'view',
+ subject_uuid: `uuid-${subject}`,
+ subject_name: subject,
+ check_type: 'not_null',
+ column_name: 'id',
+ severity: 'error',
+ enabled: true,
+ last_status: 'failed',
+ last_run_at: null,
+ subject_node_id: null,
+ subject_source_id: null,
+ subject_schema_id: null,
+ ...overrides,
+ } as DataQualityOverviewCheckApi
+}
+
+function failingHealth(subject: string): Record<string, unknown> {
+ return {
+ subject_type: 'view',
+ subject_uuid: `uuid-${subject}`,
+ health: 'failing',
+ checks_total: 1,
+ checks_failing: 1,
+ }
+}
+
+function queryAll(selector: string): HTMLElement[] {
+ return [...document.querySelectorAll<HTMLElement>(selector)]
+}
+
+function runSubjectButtons(): HTMLElement[] {
+ return queryAll('[data-attr="data-quality-overview-run-subject"]')
+}
+
+function isSpinning(button: HTMLElement): boolean {
+ return !!button.querySelector('.LemonIcon--spin, [class*="Spinner"]')
+}
+
+describe('DataQualityOverview', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({
+ results: [buildCheck('check-1', 'orders'), buildCheck('check-2', 'customers')],
+ })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([
+ failingHealth('orders'),
+ failingHealth('customers'),
+ ])
+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue({
+ id: 'suite-1',
+ status: 'running',
+ trigger: 'manual',
+ checks_passed: 0,
+ checks_failed: 0,
+ checks_errored: 0,
+ checks_skipped: 0,
+ error: '',
+ })
+ ;(dataQualityRunsRetrieve as jest.Mock).mockResolvedValue({ id: 'suite-1', status: 'running' })
+ ;(warehouseSavedQueriesChecksRunsList as jest.Mock).mockResolvedValue([
+ {
+ id: 'run-1',
+ status: 'failed',
+ compiled_query: 'SELECT 1',
+ duration_ms: 5,
+ observed_value: null,
+ failed_row_count: null,
+ error: '',
+ started_at: null,
+ },
+ ])
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ async function renderOverview(): Promise<void> {
+ render(<DataQualityOverview />)
+ await waitFor(() => expect(runSubjectButtons()).toHaveLength(2))
+ }
+
+ it('spins only the subject a run was started from, and disables the rest without a spinner', async () => {
+ // The reported regression: one shared loading flag put a spinner on every run control, so a
+ // run on one table looked like a run on the whole project.
+ await renderOverview()
+ fireEvent.click(runSubjectButtons()[0])
+
+ await waitFor(() => expect(isSpinning(runSubjectButtons()[0])).toBe(true))
+ const runAll = document.querySelector('[data-attr="data-quality-overview-run-all"]') as HTMLElement
+ expect(isSpinning(runSubjectButtons()[1])).toBe(false)
+ expect(runSubjectButtons()[1].getAttribute('aria-disabled')).toEqual('true')
+ expect(isSpinning(runAll)).toBe(false)
+ expect(runAll.getAttribute('aria-disabled')).toEqual('true')
+ })
+
+ it('renders no check rows for a collapsed subject', async () => {
+ await renderOverview()
+ expect(screen.getByText('orders_check-1')).toBeTruthy()
+
+ fireEvent.click(document.getElementById(subjectDisclosureId('view:uuid-orders'))!)
+
+ await waitFor(() => expect(screen.queryByText('orders_check-1')).toBeNull())
+ expect(queryAll('[data-attr="data-quality-overview-check-actions"]')).toHaveLength(1)
+ })
+
+ it('keeps the disclosure, the subject link and the run action as separate controls', async () => {
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({
+ results: [buildCheck('check-1', 'orders', { subject_node_id: 'node-1' })],
+ })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([failingHealth('orders')])
+ render(<DataQualityOverview />)
+ await waitFor(() => expect(runSubjectButtons()).toHaveLength(1))
+
+ const disclosure = queryAll('[data-attr="data-quality-subject-disclosure"]')[0]
+ const link = document.querySelector('a[href="/models/node-1"]')!
+ expect(disclosure.contains(link)).toBe(false)
+ expect(disclosure.contains(runSubjectButtons()[0])).toBe(false)
+ expect(disclosure.getAttribute('aria-expanded')).toEqual('true')
+ expect(disclosure.getAttribute('aria-controls')).toEqual('data-quality-subject-checks-view:uuid-orders')
+ })
+
+ it('renders the subject name as text when it has no page of its own', async () => {
+ await renderOverview()
+
+ expect(document.querySelector('a[href^="/models/"]')).toBeNull()
+ expect(screen.getAllByText('orders').length).toBeGreaterThan(0)
+ })
+
+ it('shows the first-use state when the project has no checks', async () => {
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({ results: [] })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([])
+ render(<DataQualityOverview />)
+
+ expect(await screen.findByText('No checks yet')).toBeTruthy()
+ expect(screen.queryByText('No checks match these filters.')).toBeNull()
+ })
+
+ it('shows a retry rather than an empty page when the first load fails', async () => {
+ ;(dataQualityChecksList as jest.Mock).mockRejectedValue(new Error('down'))
+ render(<DataQualityOverview />)
+
+ expect(await screen.findByText("Couldn't load data quality checks.")).toBeTruthy()
+ expect(screen.queryByText('No checks yet')).toBeNull()
+ })
+
+ it('separates the filtered-empty state from the first-use one', async () => {
+ await renderOverview()
+
+ fireEvent.change(screen.getByPlaceholderText('Search checks'), { target: { value: 'nothing matches this' } })
+
+ expect(await screen.findByText('No checks match these filters.')).toBeTruthy()
+ expect(screen.queryByText('No checks yet')).toBeNull()
+ fireEvent.click(screen.getByText('Clear filters'))
+ await waitFor(() => expect(runSubjectButtons()).toHaveLength(2))
+ })
+
+ it('returns focus to the row action when a delete is canceled', async () => {
+ await renderOverview()
+ const trigger = queryAll('[data-attr="data-quality-overview-check-actions"]')[0]
+
+ fireEvent.click(trigger)
+ fireEvent.click(await screen.findByText('Delete'))
+ fireEvent.click(await screen.findByText('Cancel'))
+
+ await waitFor(() => expect(document.activeElement).toBe(trigger))
+ })
+})
diff --git a/products/data_quality/frontend/overview/DataQualityOverview.tsx b/products/data_quality/frontend/overview/DataQualityOverview.tsx
new file mode 100644
index 000000000000..be6a47cfb4a8
--- /dev/null
+++ b/products/data_quality/frontend/overview/DataQualityOverview.tsx
@@ -0,0 +1,423 @@
+import { BindLogic, useActions, useValues } from 'kea'
+
+import { IconChevronRight, IconEllipsis } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonDialog,
+ LemonInput,
+ LemonMenu,
+ LemonSegmentedButton,
+ LemonTable,
+ LemonTag,
+ Link,
+ Spinner,
+} from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { urls } from 'scenes/urls'
+
+import { CheckEditorModal } from '../CheckEditorModal'
+import { CheckRunsTable } from '../CheckRunsTable'
+import { HEALTH_TAG_TYPES, SUBJECT_TYPE_TAGS, checkDisplayName, checkTypeLabel } from '../checksConstants'
+import { CheckStatusCell } from '../CheckStatusCell'
+import { DataQualityCheckEditorLogicProps, dataQualityCheckEditorLogic } from '../dataQualityCheckEditorLogic'
+import type { DataQualityOverviewCheckApi } from '../generated/api.schemas'
+import {
+ BROWSE_ACTION_ID,
+ OverviewStatusFilter,
+ SubjectGroup,
+ dataQualityOverviewLogic,
+ focusCandidatesAfterDelete,
+ rowActionsId,
+ subjectDisclosureId,
+ subjectKeyOf,
+} from './dataQualityOverviewLogic'
+
+const STATUS_FILTERS: { value: OverviewStatusFilter; label: string }[] = [
+ { value: 'all', label: 'All' },
+ { value: 'failing', label: 'Failing' },
+ { value: 'never_run', label: 'Not run yet' },
+]
+
+function focusFirstAvailable(elementIds: string[]): void {
+ // Runs after the removed row has left the DOM, so the first id that still resolves wins.
+ window.requestAnimationFrame(() => {
+ for (const elementId of elementIds) {
+ const element = document.getElementById(elementId)
+ if (element) {
+ element.focus()
+ return
+ }
+ }
+ })
+}
+
+export function DataQualityOverview(): JSX.Element {
+ const {
+ checks,
+ subjectGroups,
+ overviewLoading,
+ snapshotLoaded,
+ overviewError,
+ filters,
+ filtersActive,
+ startingRun,
+ isRunning,
+ runTarget,
+ pollTimedOut,
+ runError,
+ overviewSummary,
+ lastActionCheckId,
+ } = useValues(dataQualityOverviewLogic)
+ const { setFilters, runChecks, loadOverview } = useActions(dataQualityOverviewLogic)
+
+ const editorProps: DataQualityCheckEditorLogicProps = {
+ surface: 'data-quality-overview',
+ onSaved: () => loadOverview(),
+ onRunNow: (check) =>
+ runChecks({ kind: 'subject', subjectKey: subjectKeyOf(check.subject_type, check.subject_uuid) }, [
+ check.id,
+ ]),
+ onClosed: () => {
+ if (lastActionCheckId) {
+ focusFirstAvailable([rowActionsId(lastActionCheckId)])
+ }
+ },
+ }
+
+ const runningAll = (startingRun || isRunning) && runTarget?.kind === 'all'
+ const anyRunActive = startingRun || isRunning
+
+ if (!snapshotLoaded && overviewLoading) {
+ return <LemonTable dataSource={[]} loading columns={[{ title: 'Check', key: 'name' }]} />
+ }
+
+ if (!snapshotLoaded && overviewError) {
+ return (
+ <LemonBanner type="error" action={{ children: 'Retry', onClick: loadOverview }}>
+ Couldn't load data quality checks.
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <BindLogic logic={dataQualityCheckEditorLogic} props={editorProps}>
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
+ <div className="flex flex-col md:flex-row md:items-center gap-2 w-full md:w-auto">
+ <LemonInput
+ type="search"
+ placeholder="Search checks"
+ value={filters.search}
+ onChange={(search) => setFilters({ search })}
+ className="w-full md:w-64"
+ />
+ <LemonSegmentedButton
+ size="small"
+ value={filters.status}
+ onChange={(status) => setFilters({ status })}
+ options={STATUS_FILTERS}
+ className="w-full md:w-auto"
+ />
+ </div>
+ <LemonButton
+ type="primary"
+ onClick={() => runChecks({ kind: 'all' })}
+ loading={runningAll}
+ disabledReason={
+ checks.length === 0
+ ? 'There are no checks to run'
+ : anyRunActive && !runningAll
+ ? 'Checks are already running'
+ : undefined
+ }
+ data-attr="data-quality-overview-run-all"
+ >
+ Run all checks
+ </LemonButton>
+ </div>
+
+ {overviewSummary && <p className="mb-0 text-secondary">{overviewSummary}</p>}
+
+ {overviewError && snapshotLoaded && (
+ <LemonBanner type="warning" action={{ children: 'Retry', onClick: loadOverview }}>
+ Couldn't refresh checks. Showing the latest available results.
+ </LemonBanner>
+ )}
+ {runningAll && (
+ <LemonBanner type="info" icon={<Spinner />}>
+ Running checks...
+ </LemonBanner>
+ )}
+ {pollTimedOut && runTarget?.kind === 'all' && (
+ <LemonBanner type="warning" action={{ children: 'Refresh', onClick: loadOverview }}>
+ Checks are still running. Check back in a few minutes.
+ </LemonBanner>
+ )}
+ {runError && runTarget?.kind === 'all' && (
+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => runChecks({ kind: 'all' }) }}>
+ {runError}
+ </LemonBanner>
+ )}
+
+ {checks.length === 0 ? (
+ <NoChecksYet />
+ ) : subjectGroups.length === 0 ? (
+ <div className="flex items-center gap-2">
+ <span className="text-secondary">No checks match these filters.</span>
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={() => setFilters({ search: '', status: 'all' })}
+ disabledReason={filtersActive ? undefined : 'No filters are set'}
+ >
+ Clear filters
+ </LemonButton>
+ </div>
+ ) : (
+ subjectGroups.map((group) => <SubjectSection key={group.subjectKey} group={group} />)
+ )}
+
+ <CheckEditorModal />
+ </div>
+ </BindLogic>
+ )
+}
+
+function NoChecksYet(): 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">Add a check from a table or view to monitor data quality here.</p>
+ <LemonButton
+ id={BROWSE_ACTION_ID}
+ type="primary"
+ size="small"
+ to={urls.database()}
+ data-attr="data-quality-overview-browse"
+ >
+ Browse tables and views
+ </LemonButton>
+ </div>
+ )
+}
+
+function SubjectSection({ group }: { group: SubjectGroup }): JSX.Element {
+ const { expandedSubjectKeys, startingRun, isRunning, runningSubjectKey, runTarget, runError, pollTimedOut } =
+ useValues(dataQualityOverviewLogic)
+ const { toggleSubjectExpanded, runChecks, loadOverview } = useActions(dataQualityOverviewLogic)
+
+ const subjectType = SUBJECT_TYPE_TAGS[group.subjectType]
+ const expanded = expandedSubjectKeys.includes(group.subjectKey)
+ const regionId = `data-quality-subject-checks-${group.subjectKey}`
+ const running = runningSubjectKey === group.subjectKey
+ const anyRunActive = startingRun || isRunning
+ const scopedToThisSubject = runTarget?.kind === 'subject' && runTarget.subjectKey === group.subjectKey
+
+ return (
+ <div className="border rounded">
+ {/* Separate controls rather than one collapse header: a link and a button inside a
+ header button are not reachable by keyboard in the order they are read. */}
+ <div className="flex flex-wrap items-center gap-2 p-2">
+ <LemonButton
+ id={subjectDisclosureId(group.subjectKey)}
+ size="small"
+ icon={<IconChevronRight className={expanded ? 'rotate-90' : undefined} />}
+ onClick={() => toggleSubjectExpanded(group.subjectKey)}
+ aria-expanded={expanded}
+ aria-controls={regionId}
+ aria-label={`${expanded ? 'Collapse' : 'Expand'} checks for ${group.subjectName}`}
+ data-attr="data-quality-subject-disclosure"
+ />
+ <div className="flex flex-wrap items-center gap-2 flex-1">
+ {group.detailUrl ? (
+ // A new tab, and the external-link icon that comes with it: this page is a
+ // watchlist people work down, so opening a subject must not lose their place.
+ <Link
+ to={group.detailUrl}
+ target="_blank"
+ className="font-semibold"
+ tooltip={`Open ${group.subjectName} in a new tab`}
+ >
+ {group.subjectName}
+ </Link>
+ ) : (
+ <span className="font-semibold">{group.subjectName}</span>
+ )}
+ <LemonTag type={HEALTH_TAG_TYPES[group.health] ?? 'default'}>{group.health}</LemonTag>
+ {subjectType && <LemonTag type={subjectType.type}>{subjectType.label}</LemonTag>}
+ <span className="text-secondary text-sm">
+ {group.checksFailing > 0
+ ? `${group.checksFailing} of ${group.checksTotal} failing`
+ : `${group.checks.length} ${group.checks.length === 1 ? 'check' : 'checks'}`}
+ </span>
+ </div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={running}
+ disabledReason={anyRunActive && !running ? 'Checks are already running' : undefined}
+ onClick={() =>
+ runChecks(
+ { kind: 'subject', subjectKey: group.subjectKey },
+ group.checks.map((check) => check.id)
+ )
+ }
+ data-attr="data-quality-overview-run-subject"
+ >
+ Run these checks
+ </LemonButton>
+ </div>
+
+ {scopedToThisSubject && running && (
+ <p className="px-2 pb-2 mb-0 text-secondary text-sm">Running checks...</p>
+ )}
+ {scopedToThisSubject && pollTimedOut && (
+ <div className="px-2 pb-2">
+ <LemonBanner type="warning" action={{ children: 'Refresh', onClick: loadOverview }}>
+ Checks are still running. Check back in a few minutes.
+ </LemonBanner>
+ </div>
+ )}
+ {scopedToThisSubject && runError && (
+ <div className="px-2 pb-2">
+ <LemonBanner
+ type="error"
+ action={{
+ children: 'Retry',
+ onClick: () =>
+ runChecks(
+ { kind: 'subject', subjectKey: group.subjectKey },
+ group.checks.map((check) => check.id)
+ ),
+ }}
+ >
+ {runError}
+ </LemonBanner>
+ </div>
+ )}
+
+ {/* Mounted only while open: a collapsed subject rendering its rows would put every
+ check's controls in the tab order of a panel nobody can see. */}
+ {expanded && (
+ <div id={regionId} className="overflow-x-auto">
+ <SubjectChecks group={group} />
+ </div>
+ )}
+ </div>
+ )
+}
+
+function SubjectChecks({ group }: { group: SubjectGroup }): JSX.Element {
+ const { checkRunsByCheckId, runsLoadingByCheckId, deletingCheckIds, subjectGroups, startingRun, isRunning } =
+ useValues(dataQualityOverviewLogic)
+ const { loadCheckRuns, deleteCheck, setLastActionCheck, openFailingRows, runChecks } =
+ useActions(dataQualityOverviewLogic)
+ const { openEditor } = useActions(dataQualityCheckEditorLogic)
+
+ const confirmDelete = (check: DataQualityOverviewCheckApi): void => {
+ const fallbacks = focusCandidatesAfterDelete(subjectGroups, group.subjectKey, check.id)
+ LemonDialog.open({
+ title: 'Delete this check?',
+ description: 'Past run history is kept.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => {
+ deleteCheck(check)
+ focusFirstAvailable(fallbacks)
+ },
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ onClick: () => focusFirstAvailable([rowActionsId(check.id)]),
+ },
+ })
+ }
+
+ return (
+ <LemonTable
+ size="small"
+ dataSource={group.checks}
+ rowKey="id"
+ nouns={['check', 'checks']}
+ expandable={{
+ onRowExpand: (check) => loadCheckRuns(check),
+ 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={runsLoadingByCheckId[check.id]}
+ />
+ </div>
+ ),
+ }}
+ columns={[
+ { title: 'Check', key: 'name', render: (_, check) => checkDisplayName(check) },
+ { title: 'Type', key: 'check_type', render: (_, check) => checkTypeLabel(check.check_type) },
+ { title: 'Column', key: 'column_name', render: (_, check) => check.column_name || '-' },
+ {
+ title: 'Last status',
+ key: 'last_status',
+ render: (_, check) => <CheckStatusCell check={check} />,
+ },
+ {
+ 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={[
+ {
+ // Reported into this subject's panel, since that is where its
+ // result lands either way.
+ label: 'Run now',
+ onClick: () =>
+ runChecks({ kind: 'subject', subjectKey: group.subjectKey }, [check.id]),
+ disabledReason: startingRun || isRunning ? 'Checks are already running' : undefined,
+ },
+ {
+ label: 'Edit',
+ onClick: () => {
+ setLastActionCheck(check.id)
+ openEditor(check, {
+ subjectType: check.subject_type,
+ subjectId: check.subject_uuid ?? '',
+ })
+ },
+ },
+ {
+ label: 'Open failing rows in SQL editor',
+ tooltip: "The query behind this check's latest run",
+ onClick: () => openFailingRows(check),
+ },
+ {
+ label: 'Delete',
+ status: 'danger',
+ onClick: () => confirmDelete(check),
+ disabledReason: deletingCheckIds[check.id]
+ ? 'This check is being deleted'
+ : undefined,
+ },
+ ]}
+ >
+ <LemonButton
+ id={rowActionsId(check.id)}
+ size="small"
+ icon={<IconEllipsis />}
+ data-attr="data-quality-overview-check-actions"
+ aria-label={`Actions for check ${checkDisplayName(check)}`}
+ />
+ </LemonMenu>
+ ),
+ },
+ ]}
+ />
+ )
+}
diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts
new file mode 100644
index 000000000000..8b49a6484c0e
--- /dev/null
+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts
@@ -0,0 +1,547 @@
+import { router } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { initKeaTests } from '~/test/init'
+import { expectLogic } from '~/test/keaTestUtils'
+
+import {
+ dataQualityChecksHealthList,
+ dataQualityChecksList,
+ dataQualityRunsCreate,
+ dataQualityRunsRetrieve,
+ warehouseSavedQueriesChecksDestroy,
+ warehouseSavedQueriesChecksRunsList,
+} from 'products/data_quality/frontend/generated/api'
+import type {
+ DataQualityOverviewCheckApi,
+ DataQualitySuiteRunApi,
+} from 'products/data_quality/frontend/generated/api.schemas'
+
+import {
+ dataQualityOverviewLogic,
+ focusCandidatesAfterDelete,
+ rowActionsId,
+ subjectDetailUrl,
+ subjectDisclosureId,
+} from './dataQualityOverviewLogic'
+
+jest.mock('lib/api', () => ({
+ __esModule: true,
+ default: {},
+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },
+ ApiError: class ApiError extends Error {},
+}))
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: { success: jest.fn(), error: jest.fn(), info: jest.fn(), warning: jest.fn() },
+}))
+
+jest.mock('products/data_quality/frontend/generated/api', () => ({
+ dataQualityChecksList: jest.fn(),
+ dataQualityChecksHealthList: jest.fn(),
+ dataQualityRunsCreate: jest.fn(),
+ dataQualityRunsRetrieve: jest.fn(),
+ warehouseSavedQueriesChecksDestroy: jest.fn(),
+ warehouseTablesChecksDestroy: jest.fn(),
+ warehouseSavedQueriesChecksRunsList: jest.fn(),
+ warehouseTablesChecksRunsList: jest.fn(),
+}))
+
+function buildCheck(
+ id: string,
+ subject: string,
+ lastStatus: string | null,
+ overrides: Partial<DataQualityOverviewCheckApi> = {}
+): DataQualityOverviewCheckApi {
+ return {
+ id,
+ name: `${subject}_check`,
+ subject_type: 'view',
+ subject_uuid: `uuid-${subject}`,
+ subject_name: subject,
+ check_type: 'not_null',
+ column_name: 'id',
+ severity: 'error',
+ enabled: true,
+ last_status: lastStatus ?? '',
+ last_run_at: null,
+ subject_node_id: null,
+ subject_source_id: null,
+ subject_schema_id: null,
+ ...overrides,
+ } as DataQualityOverviewCheckApi
+}
+
+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
+}
+
+const HEALTH = [
+ { subject_type: 'view', subject_uuid: 'uuid-orders', health: 'failing', checks_total: 2, checks_failing: 1 },
+ { subject_type: 'view', subject_uuid: 'uuid-customers', health: 'healthy', checks_total: 1, checks_failing: 0 },
+]
+
+describe('dataQualityOverviewLogic', () => {
+ let logic: ReturnType<typeof dataQualityOverviewLogic.build>
+
+ async function mountLogic(): Promise<void> {
+ initKeaTests()
+ logic = dataQualityOverviewLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ silenceKeaLoadersErrors()
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({
+ results: [
+ buildCheck('check-1', 'orders', 'failed'),
+ buildCheck('check-2', 'orders', 'passed'),
+ buildCheck('check-3', 'customers', null),
+ ],
+ })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue(HEALTH)
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ resumeKeaLoadersErrors()
+ logic?.unmount()
+ })
+
+ it('keys subjects by type and uuid together, since the two kinds can collide', async () => {
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({
+ results: [
+ buildCheck('check-1', 'orders', 'failed'),
+ buildCheck('check-2', 'orders_table', 'passed', {
+ subject_type: 'table',
+ subject_uuid: 'uuid-orders',
+ }),
+ ],
+ })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([
+ {
+ subject_type: 'view',
+ subject_uuid: 'uuid-orders',
+ health: 'failing',
+ checks_total: 1,
+ checks_failing: 1,
+ },
+ {
+ subject_type: 'table',
+ subject_uuid: 'uuid-orders',
+ health: 'healthy',
+ checks_total: 1,
+ checks_failing: 0,
+ },
+ ])
+ await mountLogic()
+
+ expect(logic.values.subjectGroups.map((group) => [group.subjectKey, group.health])).toEqual([
+ ['view:uuid-orders', 'failing'],
+ ['table:uuid-orders', 'healthy'],
+ ])
+ })
+
+ it('groups checks by subject, worst health first', async () => {
+ // The rollup belongs to the subject, so it has to be carried on the group rather than on
+ // every row; and a healthy subject must not push a failing one down the page.
+ await mountLogic()
+
+ expect(
+ logic.values.subjectGroups.map((group) => [group.subjectName, group.health, group.checks.length])
+ ).toEqual([
+ ['orders', 'failing', 2],
+ ['customers', 'healthy', 1],
+ ])
+ })
+
+ it('opens only the subjects that need attention, once', async () => {
+ await mountLogic()
+
+ expect(logic.values.expandedSubjectKeys).toEqual(['view:uuid-orders'])
+ })
+
+ it.each<[string, Record<string, unknown>, string[]]>([
+ ['failing only', { status: 'failing' }, ['check-1']],
+ ['never run', { status: 'never_run' }, ['check-3']],
+ ['a search over the subject', { search: 'customers' }, ['check-3']],
+ ])('filters to %s', async (_case, filters, expectedIds) => {
+ await mountLogic()
+
+ logic.actions.setFilters(filters)
+
+ expect(logic.values.filteredChecks.map((check) => check.id)).toEqual(expectedIds)
+ })
+
+ it('draws the failing ratio from the rollup, not the filtered rows, so it cannot invert', async () => {
+ // Filtering to never-run checks leaves fewer rows than the subject has failing, so a
+ // denominator taken from the filtered rows would print an impossible "2 of 1 failing".
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({
+ results: [
+ buildCheck('check-1', 'orders', 'failed'),
+ buildCheck('check-2', 'orders', 'failed'),
+ buildCheck('check-3', 'orders', null),
+ ],
+ })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([
+ {
+ subject_type: 'view',
+ subject_uuid: 'uuid-orders',
+ health: 'failing',
+ checks_total: 3,
+ checks_failing: 2,
+ },
+ ])
+ await mountLogic()
+ logic.actions.setFilters({ status: 'never_run' })
+
+ const [group] = logic.values.subjectGroups
+ expect(group.checks).toHaveLength(1)
+ expect(group.checksFailing).toEqual(2)
+ expect(group.checksTotal).toEqual(3)
+ })
+
+ it('keeps subjects the user opened through filtering and refreshing', async () => {
+ await mountLogic()
+ logic.actions.toggleSubjectExpanded('view:uuid-customers')
+
+ logic.actions.setFilters({ search: 'orders' })
+ logic.actions.loadOverview()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.expandedSubjectKeys).toEqual(['view:uuid-orders', 'view:uuid-customers'])
+ })
+
+ it('drops expanded subjects that no longer exist', async () => {
+ await mountLogic()
+ logic.actions.toggleSubjectExpanded('view:uuid-customers')
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({
+ results: [buildCheck('check-1', 'orders', 'failed')],
+ })
+
+ logic.actions.loadOverview()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.expandedSubjectKeys).toEqual(['view:uuid-orders'])
+ })
+
+ it.each<[string, boolean, boolean]>([
+ ['the checks call', true, false],
+ ['the health call', false, true],
+ ])('shows the retry state when %s fails on first load', async (_case, checksFails, healthFails) => {
+ if (checksFails) {
+ ;(dataQualityChecksList as jest.Mock).mockRejectedValue(new Error('down'))
+ }
+ if (healthFails) {
+ ;(dataQualityChecksHealthList as jest.Mock).mockRejectedValue(new Error('down'))
+ }
+ await mountLogic()
+
+ expect(logic.values.snapshotLoaded).toBe(false)
+ expect(logic.values.overviewError).toBeTruthy()
+ expect(logic.values.checks).toEqual([])
+ })
+
+ it.each<[string, boolean, boolean]>([
+ ['the checks call', true, false],
+ ['the health call', false, true],
+ ])('keeps the last consistent snapshot when %s fails on refresh', async (_case, checksFails, healthFails) => {
+ await mountLogic()
+ if (checksFails) {
+ ;(dataQualityChecksList as jest.Mock).mockRejectedValue(new Error('down'))
+ }
+ if (healthFails) {
+ ;(dataQualityChecksHealthList as jest.Mock).mockRejectedValue(new Error('down'))
+ }
+
+ logic.actions.loadOverview()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.snapshotLoaded).toBe(true)
+ expect(logic.values.overviewError).toBeTruthy()
+ expect(logic.values.checks).toHaveLength(3)
+ expect(logic.values.subjectHealth).toHaveLength(2)
+ })
+
+ it('summarises a project that has failing checks', async () => {
+ await mountLogic()
+
+ expect(logic.values.overviewSummary).toEqual('1 of 3 checks failing, across 1 tables and views.')
+ })
+
+ it('counts a subject whose only failure is warning-only among the failing subjects', async () => {
+ // A warn-severity failure raises the failing-check count but leaves the subject's health at
+ // 'warn', so a subject count taken from the health rollup read "1 of 1 checks failing,
+ // across 0 tables and views".
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({
+ results: [buildCheck('check-1', 'orders', 'failed', { severity: 'warn' })],
+ })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([
+ { subject_type: 'view', subject_uuid: 'uuid-orders', health: 'warn', checks_total: 1, checks_failing: 0 },
+ ])
+ await mountLogic()
+
+ expect(logic.values.failingCheckCount).toEqual(1)
+ expect(logic.values.failingSubjectCount).toEqual(1)
+ expect(logic.values.overviewSummary).toEqual('1 of 1 checks failing, across 1 tables and views.')
+ })
+
+ it.each<[string, (string | null)[], string]>([
+ // The regression: a not-failing check was reported as passed, so a page of never-run checks
+ // read as an all-clear the moment they were created.
+ ['never-run checks as not run, never as passed', [null, null], 'None of your checks have run yet.'],
+ ['a fully passing project as all passed', ['passed', 'passed'], 'All 2 checks passed on their last run.'],
+ [
+ 'a mix without claiming the unrun ones passed',
+ ['passed', null],
+ '1 of 2 checks passed on their last run, 1 not run yet.',
+ ],
+ ])('summarises %s', async (_case, statuses, expected) => {
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({
+ results: statuses.map((status, index) => buildCheck(`check-${index}`, 'orders', status)),
+ })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([])
+ await mountLogic()
+
+ expect(logic.values.overviewSummary).toEqual(expected)
+ })
+
+ it('sends no ids when running everything', async () => {
+ // An empty list is what the endpoint reads as "every enabled check", so it must not be
+ // replaced by the currently filtered rows.
+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(
+ buildSuiteRun({ status: 'completed', checks_passed: 3 })
+ )
+ await mountLogic()
+ logic.actions.setFilters({ status: 'failing' })
+
+ logic.actions.runChecks({ kind: 'all' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataQualityRunsCreate).toHaveBeenCalledWith('1', { check_ids: [] })
+ })
+
+ it('reports a subject run into that subject alone', async () => {
+ // The regression: one global spinner meant every run control span every panel.
+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())
+ await mountLogic()
+
+ logic.actions.runChecks({ kind: 'subject', subjectKey: 'view:uuid-orders' }, ['check-1', 'check-2'])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataQualityRunsCreate).toHaveBeenCalledWith('1', { check_ids: ['check-1', 'check-2'] })
+ expect(logic.values.runningSubjectKey).toEqual('view:uuid-orders')
+ expect(logic.values.runTarget).toEqual({ kind: 'subject', subjectKey: 'view:uuid-orders' })
+ })
+
+ it('runs one check without pulling in the rest of its subject', async () => {
+ // Fixing one broken check and re-running just that check is the loop this page exists for.
+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())
+ await mountLogic()
+
+ logic.actions.runChecks({ kind: 'subject', subjectKey: 'view:uuid-orders' }, ['check-1'])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataQualityRunsCreate).toHaveBeenCalledWith('1', { check_ids: ['check-1'] })
+ expect(logic.values.runningSubjectKey).toEqual('view:uuid-orders')
+ })
+
+ it('offers a retry instead of a toast when a run cannot start', async () => {
+ ;(dataQualityRunsCreate as jest.Mock).mockRejectedValue(new Error('down'))
+ await mountLogic()
+
+ logic.actions.runChecks({ kind: 'all' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.runError).toEqual("Couldn't run checks.")
+ expect(logic.values.startingRun).toBe(false)
+ expect(logic.values.runningSubjectKey).toBeNull()
+ })
+
+ it('removes a deleted check and refreshes the snapshot', async () => {
+ ;(warehouseSavedQueriesChecksDestroy as jest.Mock).mockResolvedValue(undefined)
+ await mountLogic()
+ const loadsBeforeDelete = (dataQualityChecksList as jest.Mock).mock.calls.length
+
+ logic.actions.deleteCheck(buildCheck('check-1', 'orders', 'failed'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warehouseSavedQueriesChecksDestroy).toHaveBeenCalledWith('1', 'uuid-orders', 'check-1')
+ expect((dataQualityChecksList as jest.Mock).mock.calls.length).toBeGreaterThan(loadsBeforeDelete)
+ expect(lemonToast.success).toHaveBeenCalledWith('Check deleted')
+ })
+
+ it('keeps the row and says so when a delete fails', async () => {
+ ;(warehouseSavedQueriesChecksDestroy as jest.Mock).mockRejectedValue(new Error('down'))
+ await mountLogic()
+
+ logic.actions.deleteCheck(buildCheck('check-1', 'orders', 'failed'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.checks.map((check) => check.id)).toEqual(['check-1', 'check-2', 'check-3'])
+ expect(lemonToast.error).toHaveBeenCalled()
+ expect(logic.values.deletingCheckIds['check-1']).toBe(false)
+ })
+
+ it('deletes a check once when the confirmation is submitted twice', async () => {
+ ;(warehouseSavedQueriesChecksDestroy as jest.Mock).mockResolvedValue(undefined)
+ await mountLogic()
+ const check = buildCheck('check-1', 'orders', 'failed')
+
+ logic.actions.deleteCheck(check)
+ logic.actions.deleteCheck(check)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(warehouseSavedQueriesChecksDestroy).toHaveBeenCalledTimes(1)
+ })
+
+ it('reloads the rows once the polled run finishes', async () => {
+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())
+ ;(dataQualityRunsRetrieve as jest.Mock)
+ .mockResolvedValueOnce(buildSuiteRun())
+ .mockResolvedValue(buildSuiteRun({ status: 'completed', checks_passed: 2, checks_failed: 1 }))
+ await mountLogic()
+ const loadsBeforeRun = (dataQualityChecksList as jest.Mock).mock.calls.length
+
+ jest.useFakeTimers()
+ logic.actions.runChecks({ kind: 'all' })
+ await drainListeners()
+ expect(logic.values.isRunning).toBe(true)
+
+ await advancePoll(3000)
+ await advancePoll(3000)
+
+ expect(logic.values.isRunning).toBe(false)
+ expect((dataQualityChecksList as jest.Mock).mock.calls.length).toBeGreaterThan(loadsBeforeRun)
+ expect(lemonToast.warning).toHaveBeenCalledWith('2 passed, 1 failed')
+ })
+
+ it('refreshes the run history cached under expanded rows when a run finishes', async () => {
+ // A row expanded before the run caches its history; loadOverview refreshes status and
+ // rollups but not those runs, so without a reload the just-finished run is missing until a
+ // collapse and re-expand.
+ ;(warehouseSavedQueriesChecksRunsList as jest.Mock).mockResolvedValue([{ compiled_query: 'SELECT 1' }])
+ await mountLogic()
+ logic.actions.loadCheckRuns(buildCheck('check-1', 'orders', 'failed'))
+ await expectLogic(logic).toFinishAllListeners()
+ const runsLoadsBeforeFinish = (warehouseSavedQueriesChecksRunsList as jest.Mock).mock.calls.length
+
+ logic.actions.finishSuiteRun(buildSuiteRun({ status: 'completed', checks_passed: 3 }))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect((warehouseSavedQueriesChecksRunsList as jest.Mock).mock.calls.length).toBeGreaterThan(
+ runsLoadsBeforeFinish
+ )
+ })
+
+ it('stops polling a run that never finishes', async () => {
+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())
+ ;(dataQualityRunsRetrieve as jest.Mock).mockResolvedValue(buildSuiteRun())
+ await mountLogic()
+
+ jest.useFakeTimers()
+ logic.actions.runChecks({ kind: 'all' })
+ await drainListeners()
+
+ 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.isRunning).toBe(false)
+ })
+
+ it.each<[string, Record<string, string>[], string | null]>([
+ // Retention clears the compiled query of older runs first, so "latest" is not always [0].
+ [
+ 'the newest run that still has one',
+ [{ compiled_query: 'SELECT 2' }, { compiled_query: 'SELECT 1' }],
+ 'SELECT 2',
+ ],
+ ['past runs whose query was cleared', [{ compiled_query: '' }, { compiled_query: 'SELECT 1' }], 'SELECT 1'],
+ ])('opens the failing rows of %s', async (_case, runs, expected) => {
+ ;(warehouseSavedQueriesChecksRunsList as jest.Mock).mockResolvedValue(runs)
+ await mountLogic()
+
+ logic.actions.openFailingRows(buildCheck('check-1', 'orders', 'failed'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toMatch(/\/sql$/)
+ expect(router.values.searchParams.open_query).toEqual(expected)
+ })
+
+ it.each<[string, Record<string, string>[]]>([
+ ['the check has never run', []],
+ ['every run has lost its query to retention', [{ compiled_query: '' }]],
+ ])('says why there is nothing to open when %s', async (_case, runs) => {
+ ;(warehouseSavedQueriesChecksRunsList as jest.Mock).mockResolvedValue(runs)
+ await mountLogic()
+
+ logic.actions.openFailingRows(buildCheck('check-1', 'orders', 'failed'))
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(lemonToast.info).toHaveBeenCalled()
+ expect(router.values.location.pathname).not.toMatch(/\/sql$/)
+ })
+
+ it.each<[string, Partial<DataQualityOverviewCheckApi>, string | null]>([
+ ['a view on a DAG node', { subject_type: 'view', subject_node_id: 'node-1' }, '/models/node-1'],
+ ['a view on no DAG', { subject_type: 'view', subject_node_id: null }, null],
+ [
+ 'a synced table',
+ { subject_type: 'table', subject_source_id: 'source-1', subject_schema_id: 'schema-1' },
+ '/data-management/sources/source-1/schemas/schema-1',
+ ],
+ [
+ 'a table linked by hand rather than synced',
+ { subject_type: 'table', subject_uuid: 'uuid-table', subject_source_id: null },
+ '/data-management/sources/self-managed-uuid-table/schemas',
+ ],
+ ])('links %s', (_case, overrides, expected) => {
+ expect(subjectDetailUrl(buildCheck('check-1', 'orders', null, overrides))).toEqual(expected)
+ })
+
+ it.each<[string, string, string]>([
+ ['the next check in the same subject', 'check-1', rowActionsId('check-2')],
+ ['the previous check when the last one goes', 'check-2', rowActionsId('check-1')],
+ ])('restores focus to %s', async (_case, deletedId, expectedFirst) => {
+ await mountLogic()
+
+ const candidates = focusCandidatesAfterDelete(logic.values.subjectGroups, 'view:uuid-orders', deletedId)
+
+ expect(candidates[0]).toEqual(expectedFirst)
+ })
+
+ it('falls back past the emptied subject to its neighbour, then the empty state', async () => {
+ await mountLogic()
+
+ const candidates = focusCandidatesAfterDelete(logic.values.subjectGroups, 'view:uuid-customers', 'check-3')
+
+ expect(candidates).toEqual([subjectDisclosureId('view:uuid-orders'), 'data-quality-browse-subjects'])
+ })
+
+ async function drainListeners(): Promise<void> {
+ for (let tick = 0; tick < 20; tick++) {
+ await Promise.resolve()
+ }
+ }
+
+ async function advancePoll(ms: number): Promise<void> {
+ jest.advanceTimersByTime(ms)
+ await drainListeners()
+ }
+})
diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts
new file mode 100644
index 000000000000..2127a491510b
--- /dev/null
+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts
@@ -0,0 +1,682 @@
+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { urls } from 'scenes/urls'
+
+import { DataQualitySubjectRef, apiErrorDetail, checksApi } from 'products/data_quality/frontend/checksApi'
+import {
+ dataQualityChecksHealthList,
+ dataQualityChecksList,
+ dataQualityRunsCreate,
+ dataQualityRunsRetrieve,
+} from 'products/data_quality/frontend/generated/api'
+import type {
+ DataQualityCheckRunApi,
+ DataQualityOverviewCheckApi,
+ DataQualitySubjectHealthApi,
+ DataQualitySuiteRunApi,
+} from 'products/data_quality/frontend/generated/api.schemas'
+import { openFailingRowsInSqlEditor } from 'products/data_quality/frontend/openFailingRows'
+import {
+ isTerminalSuiteRun,
+ suiteRunOutcome,
+ suiteRunPollListeners,
+ suiteRunSummary,
+} from 'products/data_quality/frontend/suiteRuns'
+
+const CHECKS_LIMIT = 500
+
+export type OverviewStatusFilter = 'all' | 'failing' | 'never_run'
+
+export interface OverviewFilters {
+ search: string
+ status: OverviewStatusFilter
+}
+
+export const DEFAULT_OVERVIEW_FILTERS: OverviewFilters = { search: '', status: 'all' }
+
+/** Checks and rollups from one refresh, committed together so rows and health always agree. */
+export interface OverviewSnapshot {
+ checks: DataQualityOverviewCheckApi[]
+ health: DataQualitySubjectHealthApi[]
+}
+
+/** What a run is reporting into: the page, or exactly one subject panel. */
+export type OverviewRunTarget = { kind: 'all' } | { kind: 'subject'; subjectKey: string }
+
+/** One table or view, with the checks on it and its rollup. What the overview renders a section per. */
+export interface SubjectGroup {
+ /** Composite: a table and a view can hold the same uuid, and do collide in practice. */
+ subjectKey: string
+ subjectType: string
+ subjectUuid: string
+ subjectName: string
+ detailUrl: string | null
+ checks: DataQualityOverviewCheckApi[]
+ health: string
+ checksFailing: number
+ // Denominator of the failing ratio. From the subject's rollup, not checks.length, since a filter
+ // shows only a subset of the subject's checks and would otherwise read as "2 of 1 failing".
+ checksTotal: number
+}
+
+// Worst first: someone opening this is looking for what is broken, not for an alphabet.
+const HEALTH_ORDER: Record<string, number> = { failing: 0, erroring: 1, warn: 2, healthy: 3, unknown: 4 }
+
+const UNHEALTHY = ['failing', 'erroring', 'warn']
+
+export function subjectKeyOf(subjectType: string, subjectUuid: string | null | undefined): string {
+ return `${subjectType}:${subjectUuid ?? ''}`
+}
+
+function subjectRefOf(check: DataQualityOverviewCheckApi): DataQualitySubjectRef {
+ return { subjectType: check.subject_type, subjectId: check.subject_uuid ?? '' }
+}
+
+/** Where the subject's own page lives, or null when it has none and the name renders as text. */
+export function subjectDetailUrl(check: DataQualityOverviewCheckApi): string | null {
+ if (check.subject_type === 'view') {
+ return check.subject_node_id ? urls.nodeDetail(check.subject_node_id) : null
+ }
+ if (check.subject_source_id && check.subject_schema_id) {
+ return urls.dataWarehouseSourceSchema(check.subject_source_id, check.subject_schema_id)
+ }
+ // A table linked by hand rather than synced has no source schema to sit under; its own id is
+ // the route.
+ return check.subject_uuid ? urls.dataWarehouseSource(`self-managed-${check.subject_uuid}`) : null
+}
+
+export const ROW_ACTIONS_ID_PREFIX = 'data-quality-check-actions-'
+export const SUBJECT_DISCLOSURE_ID_PREFIX = 'data-quality-subject-disclosure-'
+export const BROWSE_ACTION_ID = 'data-quality-browse-subjects'
+
+export function rowActionsId(checkId: string): string {
+ return `${ROW_ACTIONS_ID_PREFIX}${checkId}`
+}
+
+export function subjectDisclosureId(subjectKey: string): string {
+ return `${SUBJECT_DISCLOSURE_ID_PREFIX}${subjectKey}`
+}
+
+/**
+ * Where focus goes once a deleted row takes its own trigger with it, best first.
+ *
+ * Computed against the groups as they were before the row went, since that is the order the user
+ * was looking at.
+ */
+export function focusCandidatesAfterDelete(groups: SubjectGroup[], subjectKey: string, checkId: string): string[] {
+ const groupIndex = groups.findIndex((group) => group.subjectKey === subjectKey)
+ const group = groups[groupIndex]
+ const checkIndex = group?.checks.findIndex((check) => check.id === checkId) ?? -1
+ const siblings = (group?.checks ?? []).filter((check) => check.id !== checkId)
+ const next = checkIndex >= 0 ? siblings[checkIndex] : undefined
+ const previous = checkIndex > 0 ? siblings[checkIndex - 1] : undefined
+
+ return [
+ ...(next ? [rowActionsId(next.id)] : []),
+ ...(previous ? [rowActionsId(previous.id)] : []),
+ ...(siblings.length ? [subjectDisclosureId(subjectKey)] : []),
+ ...(groups[groupIndex + 1] ? [subjectDisclosureId(groups[groupIndex + 1].subjectKey)] : []),
+ ...(groupIndex > 0 ? [subjectDisclosureId(groups[groupIndex - 1].subjectKey)] : []),
+ BROWSE_ACTION_ID,
+ ]
+}
+
+function projectId(): string {
+ return String(ApiConfig.getCurrentTeamId())
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityOverviewLogicValues {
+ activeSuiteRun: DataQualitySuiteRunApi | null
+ allSubjectKeys: string[]
+ checkRunsByCheckId: Record<string, DataQualityCheckRunApi[]>
+ checks: DataQualityOverviewCheckApi[]
+ deletingCheckIds: Record<string, boolean>
+ expandedSubjectKeys: string[]
+ expansionInitialized: boolean
+ failingCheckCount: number
+ failingSubjectCount: number
+ filteredChecks: DataQualityOverviewCheckApi[]
+ filters: OverviewFilters
+ filtersActive: boolean
+ healthBySubjectKey: {
+ [k: string]: DataQualitySubjectHealthApi
+ }
+ isRunning: boolean
+ lastActionCheckId: string | null
+ overview: OverviewSnapshot | null
+ overviewError: string | null
+ overviewLoading: boolean
+ overviewSummary: string | null
+ pollTimedOut: boolean
+ runError: string | null
+ runTarget: OverviewRunTarget | null
+ runningSubjectKey: string | null
+ runsLoadingByCheckId: Record<string, boolean>
+ snapshotLoaded: boolean
+ startingRun: boolean
+ subjectGroups: SubjectGroup[]
+ subjectHealth: DataQualitySubjectHealthApi[]
+ unhealthySubjectKeys: string[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityOverviewLogicActions {
+ deleteCheck: (check: DataQualityOverviewCheckApi) => {
+ check: DataQualityOverviewCheckApi
+ }
+ finishSuiteRun: (suiteRun: DataQualitySuiteRunApi) => {
+ suiteRun: DataQualitySuiteRunApi
+ }
+ loadCheckRuns: (check: DataQualityOverviewCheckApi) => {
+ check: DataQualityOverviewCheckApi
+ }
+ loadOverview: () => any
+ loadOverviewFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadOverviewSuccess: (
+ overview: {
+ checks: DataQualityOverviewCheckApi[]
+ health: DataQualitySubjectHealthApi[]
+ },
+ payload?: any
+ ) => {
+ overview: {
+ checks: DataQualityOverviewCheckApi[]
+ health: DataQualitySubjectHealthApi[]
+ }
+ payload?: any
+ }
+ openFailingRows: (check: DataQualityOverviewCheckApi) => {
+ check: DataQualityOverviewCheckApi
+ }
+ pollActiveSuiteRun: () => {
+ value: true
+ }
+ removeCheck: (checkId: string) => {
+ checkId: string
+ }
+ runChecks: (
+ target: OverviewRunTarget,
+ checkIds?: string[]
+ ) => {
+ checkIds: string[]
+ target: OverviewRunTarget
+ }
+ scheduleSuiteRunPoll: () => {
+ value: true
+ }
+ setActiveSuiteRun: (suiteRun: DataQualitySuiteRunApi | null) => {
+ suiteRun: DataQualitySuiteRunApi | null
+ }
+ setCheckDeleting: (
+ checkId: string,
+ deleting: boolean
+ ) => {
+ checkId: string
+ deleting: boolean
+ }
+ setCheckRuns: (
+ checkId: string,
+ runs: DataQualityCheckRunApi[]
+ ) => {
+ checkId: string
+ runs: DataQualityCheckRunApi[]
+ }
+ setExpandedSubjects: (subjectKeys: string[]) => {
+ subjectKeys: string[]
+ }
+ setFilters: (filters: Partial<OverviewFilters>) => {
+ filters: Partial<OverviewFilters>
+ }
+ setLastActionCheck: (checkId: string | null) => {
+ checkId: string | null
+ }
+ setPollTimedOut: () => {
+ value: true
+ }
+ setRunError: (error: string | null) => {
+ error: string | null
+ }
+ setRunsLoading: (
+ checkId: string,
+ loading: boolean
+ ) => {
+ checkId: string
+ loading: boolean
+ }
+ setStartingRun: (starting: boolean) => {
+ starting: boolean
+ }
+ toggleSubjectExpanded: (subjectKey: string) => {
+ subjectKey: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dataQualityOverviewLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ checks: (overview: OverviewSnapshot | null) => DataQualityOverviewCheckApi[]
+ subjectHealth: (overview: OverviewSnapshot | null) => DataQualitySubjectHealthApi[]
+ healthBySubjectKey: (subjectHealth: DataQualitySubjectHealthApi[]) => {
+ [k: string]: DataQualitySubjectHealthApi
+ }
+ isRunning: (activeSuiteRun: DataQualitySuiteRunApi | null, pollTimedOut: boolean) => boolean
+ runningSubjectKey: (
+ runTarget: OverviewRunTarget | null,
+ isRunning: boolean,
+ startingRun: boolean
+ ) => string | null
+ filtersActive: (filters: OverviewFilters) => boolean
+ filteredChecks: (
+ checks: DataQualityOverviewCheckApi[],
+ filters: OverviewFilters
+ ) => DataQualityOverviewCheckApi[]
+ failingCheckCount: (checks: DataQualityOverviewCheckApi[]) => number
+ failingSubjectCount: (checks: DataQualityOverviewCheckApi[]) => number
+ overviewSummary: (
+ checks: DataQualityOverviewCheckApi[],
+ failingCheckCount: number,
+ failingSubjectCount: number
+ ) => string | null
+ subjectGroups: (
+ filteredChecks: DataQualityOverviewCheckApi[],
+ healthBySubjectKey: {
+ [k: string]: DataQualitySubjectHealthApi
+ }
+ ) => SubjectGroup[]
+ allSubjectKeys: (checks: DataQualityOverviewCheckApi[]) => string[]
+ unhealthySubjectKeys: (subjectGroups: SubjectGroup[]) => string[]
+ }
+}
+
+export type dataQualityOverviewLogicType = MakeLogicType<
+ dataQualityOverviewLogicValues,
+ dataQualityOverviewLogicActions,
+ Record<string, any>,
+ dataQualityOverviewLogicMeta
+>
+
+export const dataQualityOverviewLogic = kea<dataQualityOverviewLogicType>([
+ path(['products', 'data_quality', 'frontend', 'overview', 'dataQualityOverviewLogic']),
+ actions({
+ setFilters: (filters: Partial<OverviewFilters>) => ({ filters }),
+ toggleSubjectExpanded: (subjectKey: string) => ({ subjectKey }),
+ setExpandedSubjects: (subjectKeys: string[]) => ({ subjectKeys }),
+ loadCheckRuns: (check: DataQualityOverviewCheckApi) => ({ check }),
+ openFailingRows: (check: DataQualityOverviewCheckApi) => ({ check }),
+ setCheckRuns: (checkId: string, runs: DataQualityCheckRunApi[]) => ({ checkId, runs }),
+ setRunsLoading: (checkId: string, loading: boolean) => ({ checkId, loading }),
+ runChecks: (target: OverviewRunTarget, checkIds: string[] = []) => ({ target, checkIds }),
+ setStartingRun: (starting: boolean) => ({ starting }),
+ setActiveSuiteRun: (suiteRun: DataQualitySuiteRunApi | null) => ({ suiteRun }),
+ scheduleSuiteRunPoll: true,
+ pollActiveSuiteRun: true,
+ finishSuiteRun: (suiteRun: DataQualitySuiteRunApi) => ({ suiteRun }),
+ setPollTimedOut: true,
+ deleteCheck: (check: DataQualityOverviewCheckApi) => ({ check }),
+ setCheckDeleting: (checkId: string, deleting: boolean) => ({ checkId, deleting }),
+ removeCheck: (checkId: string) => ({ checkId }),
+ setLastActionCheck: (checkId: string | null) => ({ checkId }),
+ setRunError: (error: string | null) => ({ error }),
+ }),
+ loaders(() => ({
+ overview: [
+ null as OverviewSnapshot | null,
+ {
+ // Fetched in parallel but committed as one value: rows and rollups that disagree
+ // read as a bug, so a half-refresh keeps the last snapshot the user already has.
+ loadOverview: async () => {
+ const [checks, health] = await Promise.all([
+ dataQualityChecksList(projectId(), { limit: CHECKS_LIMIT }),
+ dataQualityChecksHealthList(projectId()),
+ ])
+ return { checks: checks.results, health }
+ },
+ },
+ ],
+ })),
+ reducers({
+ filters: [
+ DEFAULT_OVERVIEW_FILTERS,
+ {
+ setFilters: (state, { filters }) => ({ ...state, ...filters }),
+ },
+ ],
+ overview: {
+ removeCheck: (state: OverviewSnapshot | null, { checkId }: { checkId: string }) =>
+ state ? { ...state, checks: state.checks.filter((check) => check.id !== checkId) } : state,
+ },
+ snapshotLoaded: [
+ false,
+ {
+ loadOverviewSuccess: () => true,
+ },
+ ],
+ overviewError: [
+ null as string | null,
+ {
+ loadOverview: () => null,
+ loadOverviewSuccess: () => null,
+ loadOverviewFailure: (_, { error }) => error || 'Failed to load',
+ },
+ ],
+ expandedSubjectKeys: [
+ [] as string[],
+ {
+ setExpandedSubjects: (_, { subjectKeys }) => subjectKeys,
+ toggleSubjectExpanded: (state, { subjectKey }) =>
+ state.includes(subjectKey) ? state.filter((key) => key !== subjectKey) : [...state, subjectKey],
+ },
+ ],
+ expansionInitialized: [
+ false,
+ {
+ setExpandedSubjects: () => true,
+ },
+ ],
+ startingRun: [
+ false,
+ {
+ runChecks: () => true,
+ setStartingRun: (_, { starting }) => starting,
+ },
+ ],
+ runTarget: [
+ null as OverviewRunTarget | null,
+ {
+ runChecks: (_, { target }) => target,
+ },
+ ],
+ runError: [
+ null as string | null,
+ {
+ runChecks: () => null,
+ setRunError: (_, { error }) => error,
+ setActiveSuiteRun: () => null,
+ },
+ ],
+ 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 }),
+ },
+ ],
+ runsLoadingByCheckId: [
+ {} as Record<string, boolean>,
+ {
+ setRunsLoading: (state, { checkId, loading }) => ({ ...state, [checkId]: loading }),
+ },
+ ],
+ deletingCheckIds: [
+ {} as Record<string, boolean>,
+ {
+ setCheckDeleting: (state, { checkId, deleting }) => ({ ...state, [checkId]: deleting }),
+ },
+ ],
+ lastActionCheckId: [
+ null as string | null,
+ {
+ setLastActionCheck: (_, { checkId }) => checkId,
+ },
+ ],
+ }),
+ selectors({
+ checks: [(s) => [s.overview], (overview: OverviewSnapshot | null) => overview?.checks ?? []],
+ subjectHealth: [(s) => [s.overview], (overview: OverviewSnapshot | null) => overview?.health ?? []],
+ healthBySubjectKey: [
+ (s) => [s.subjectHealth],
+ (subjectHealth: DataQualitySubjectHealthApi[]) =>
+ Object.fromEntries(
+ subjectHealth.map((entry) => [subjectKeyOf(entry.subject_type, entry.subject_uuid), entry])
+ ),
+ ],
+ isRunning: [
+ (s) => [s.activeSuiteRun, s.pollTimedOut],
+ (activeSuiteRun: DataQualitySuiteRunApi | null, pollTimedOut: boolean) =>
+ !!activeSuiteRun && !isTerminalSuiteRun(activeSuiteRun) && !pollTimedOut,
+ ],
+ runningSubjectKey: [
+ (s) => [s.runTarget, s.isRunning, s.startingRun],
+ (runTarget: OverviewRunTarget | null, isRunning: boolean, startingRun: boolean) =>
+ (isRunning || startingRun) && runTarget?.kind === 'subject' ? runTarget.subjectKey : null,
+ ],
+ filtersActive: [
+ (s) => [s.filters],
+ (filters: OverviewFilters) => !!filters.search.trim() || filters.status !== 'all',
+ ],
+ filteredChecks: [
+ (s) => [s.checks, s.filters],
+ (checks: DataQualityOverviewCheckApi[], filters: OverviewFilters) => {
+ const search = filters.search.trim().toLowerCase()
+ return checks.filter((check) => {
+ if (filters.status === 'failing' && !['failed', 'errored'].includes(check.last_status ?? '')) {
+ return false
+ }
+ if (filters.status === 'never_run' && check.last_status) {
+ return false
+ }
+ if (!search) {
+ return true
+ }
+ return [check.name, check.subject_name, check.check_type, check.column_name]
+ .filter(Boolean)
+ .some((field) => String(field).toLowerCase().includes(search))
+ })
+ },
+ ],
+ failingCheckCount: [
+ (s) => [s.checks],
+ (checks: DataQualityOverviewCheckApi[]) =>
+ checks.filter((check) => ['failed', 'errored'].includes(check.last_status ?? '')).length,
+ ],
+ // Counted from the same checks as failingCheckCount, not the health rollup: a warn-severity
+ // or disabled failure raises the check count but leaves the subject's health short of
+ // 'failing', which would read as "N checks failing, across 0 tables and views".
+ failingSubjectCount: [
+ (s) => [s.checks],
+ (checks: DataQualityOverviewCheckApi[]) =>
+ new Set(
+ checks
+ .filter((check) => ['failed', 'errored'].includes(check.last_status ?? ''))
+ .map((check) => subjectKeyOf(check.subject_type, check.subject_uuid))
+ ).size,
+ ],
+ // A not-failing check is not a passed check: a never-run or skipped one also has no failure.
+ // Only claim every check passed when every check actually passed, so a fresh page of unrun
+ // checks does not read as an all-clear.
+ overviewSummary: [
+ (s) => [s.checks, s.failingCheckCount, s.failingSubjectCount],
+ (
+ checks: DataQualityOverviewCheckApi[],
+ failingCheckCount: number,
+ failingSubjectCount: number
+ ): string | null => {
+ if (checks.length === 0) {
+ return null
+ }
+ if (failingCheckCount > 0) {
+ return `${failingCheckCount} of ${checks.length} checks failing, across ${failingSubjectCount} tables and views.`
+ }
+ const passed = checks.filter((check) => check.last_status === 'passed').length
+ if (passed === checks.length) {
+ return `All ${checks.length} checks passed on their last run.`
+ }
+ if (passed === 0) {
+ return 'None of your checks have run yet.'
+ }
+ const notRun = checks.filter((check) => !check.last_status).length
+ return `${passed} of ${checks.length} checks passed on their last run, ${notRun} not run yet.`
+ },
+ ],
+ subjectGroups: [
+ (s) => [s.filteredChecks, s.healthBySubjectKey],
+ (
+ filteredChecks: DataQualityOverviewCheckApi[],
+ healthBySubjectKey: Record<string, DataQualitySubjectHealthApi>
+ ): SubjectGroup[] => {
+ const groups = new Map<string, SubjectGroup>()
+ for (const check of filteredChecks) {
+ const subjectKey = subjectKeyOf(check.subject_type, check.subject_uuid)
+ const group = groups.get(subjectKey) ?? {
+ subjectKey,
+ subjectType: check.subject_type,
+ subjectUuid: check.subject_uuid ?? '',
+ subjectName: check.subject_name,
+ detailUrl: subjectDetailUrl(check),
+ checks: [],
+ health: healthBySubjectKey[subjectKey]?.health ?? 'unknown',
+ checksFailing: healthBySubjectKey[subjectKey]?.checks_failing ?? 0,
+ checksTotal: healthBySubjectKey[subjectKey]?.checks_total ?? 0,
+ }
+ group.checks.push(check)
+ groups.set(subjectKey, group)
+ }
+ return [...groups.values()].sort(
+ (left, right) =>
+ (HEALTH_ORDER[left.health] ?? 9) - (HEALTH_ORDER[right.health] ?? 9) ||
+ left.subjectName.localeCompare(right.subjectName)
+ )
+ },
+ ],
+ allSubjectKeys: [
+ (s) => [s.checks],
+ (checks: DataQualityOverviewCheckApi[]) => [
+ ...new Set(checks.map((check) => subjectKeyOf(check.subject_type, check.subject_uuid))),
+ ],
+ ],
+ // Someone opening this wants the broken ones open; healthy subjects stay collapsed.
+ unhealthySubjectKeys: [
+ (s) => [s.subjectGroups],
+ (subjectGroups: SubjectGroup[]) =>
+ subjectGroups.filter((group) => UNHEALTHY.includes(group.health)).map((group) => group.subjectKey),
+ ],
+ }),
+ listeners(({ actions, values, cache }) => {
+ // Assigned one by one rather than spread: kea-typegen walks this object literal and crashes
+ // on a spread element, which has no property name.
+ const poll = suiteRunPollListeners({
+ retrieve: (suiteRunId) => dataQualityRunsRetrieve(projectId(), suiteRunId),
+ cache,
+ values,
+ actions,
+ })
+ return {
+ setActiveSuiteRun: poll.setActiveSuiteRun,
+ scheduleSuiteRunPoll: poll.scheduleSuiteRunPoll,
+ pollActiveSuiteRun: poll.pollActiveSuiteRun,
+ loadOverviewSuccess: () => {
+ if (!values.expansionInitialized) {
+ actions.setExpandedSubjects(values.unhealthySubjectKeys)
+ return
+ }
+ // Pruned against every subject, not the filtered ones, so a filter never collapses a
+ // panel the user opened.
+ const present = new Set(values.allSubjectKeys)
+ const kept = values.expandedSubjectKeys.filter((key) => present.has(key))
+ if (kept.length !== values.expandedSubjectKeys.length) {
+ actions.setExpandedSubjects(kept)
+ }
+ },
+ loadCheckRuns: async ({ check }) => {
+ if (values.runsLoadingByCheckId[check.id]) {
+ return
+ }
+ actions.setRunsLoading(check.id, true)
+ try {
+ actions.setCheckRuns(check.id, await checksApi.runs(subjectRefOf(check), check.id))
+ } catch (error) {
+ lemonToast.error(apiErrorDetail(error) ?? 'Could not load the run history. Try again.')
+ } finally {
+ actions.setRunsLoading(check.id, false)
+ }
+ },
+ openFailingRows: async ({ check }) => {
+ await openFailingRowsInSqlEditor({
+ cachedRuns: values.checkRunsByCheckId[check.id],
+ fetchRuns: () => checksApi.runs(subjectRefOf(check), check.id),
+ onRunsFetched: (runs) => actions.setCheckRuns(check.id, runs),
+ })
+ },
+ runChecks: async ({ checkIds }) => {
+ try {
+ // An empty selection is the "everything" case, which the endpoint reads as no filter.
+ actions.setActiveSuiteRun(await dataQualityRunsCreate(projectId(), { check_ids: checkIds }))
+ } catch (error) {
+ actions.setRunError(apiErrorDetail(error) ?? "Couldn't run checks.")
+ } finally {
+ actions.setStartingRun(false)
+ }
+ },
+ deleteCheck: async ({ check }) => {
+ if (values.deletingCheckIds[check.id]) {
+ return
+ }
+ actions.setCheckDeleting(check.id, true)
+ try {
+ await checksApi.destroy(
+ { subjectType: check.subject_type, subjectId: check.subject_uuid ?? '' },
+ check.id
+ )
+ actions.removeCheck(check.id)
+ actions.loadOverview()
+ lemonToast.success('Check deleted')
+ } catch (error) {
+ lemonToast.error(apiErrorDetail(error) ?? 'Could not delete the check. Try again.')
+ } finally {
+ actions.setCheckDeleting(check.id, false)
+ }
+ },
+ finishSuiteRun: ({ suiteRun }) => {
+ cache.disposables.dispose('suiteRunPoll')
+ actions.loadOverview()
+ // loadOverview refreshes status and rollups but not the runs cached under an expanded
+ // row, so reload each; without this a row expanded before the run keeps showing the
+ // pre-run history, and openFailingRows opens the stale query.
+ const checksById = new Map(values.checks.map((check) => [check.id, check]))
+ Object.keys(values.checkRunsByCheckId).forEach((checkId) => {
+ const check = checksById.get(checkId)
+ if (check) {
+ actions.loadCheckRuns(check)
+ }
+ })
+ const outcome = suiteRunOutcome(suiteRun)
+ if (outcome === 'empty') {
+ lemonToast.info('No enabled checks to run')
+ } else if (outcome === 'errored') {
+ // An inline banner rather than a toast: this page has a retry control for it.
+ actions.setRunError(suiteRun.error || "Couldn't run checks. Try again.")
+ } else if (outcome === 'warning') {
+ lemonToast.warning(suiteRunSummary(suiteRun))
+ } else {
+ lemonToast.success(suiteRunSummary(suiteRun))
+ }
+ },
+ }
+ }),
+ afterMount(({ actions }) => {
+ actions.loadOverview()
+ }),
+])
diff --git a/products/data_quality/frontend/suiteRuns.ts b/products/data_quality/frontend/suiteRuns.ts
new file mode 100644
index 000000000000..e7c5d88fe49a
--- /dev/null
+++ b/products/data_quality/frontend/suiteRuns.ts
@@ -0,0 +1,160 @@
+import { pluralize } from 'lib/utils/strings'
+
+import type { DataQualityCheckRunApi, DataQualitySuiteRunApi } from './generated/api.schemas'
+
+const TERMINAL_SUITE_RUN_STATUSES = ['completed', 'failed', 'empty']
+const FAST_POLL_INTERVAL_MS = 3000
+const SLOW_POLL_INTERVAL_MS = 15000
+const FAST_POLL_WINDOW_MS = 60_000
+
+/** How long a run may stay 'running' before the UI stops asking and offers a manual refresh. */
+export const POLL_TIMEOUT_MS = 15 * 60_000
+
+export function isTerminalSuiteRun(suiteRun: DataQualitySuiteRunApi | null): boolean {
+ return !!suiteRun && TERMINAL_SUITE_RUN_STATUSES.includes(suiteRun.status)
+}
+
+/** Tight while a run is likely to finish, then backed off so a long one costs little. */
+export function pollDelayMs(elapsedMs: number): number {
+ return elapsedMs < FAST_POLL_WINDOW_MS ? FAST_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS
+}
+
+/** The newest run that still has its query. Retention clears the compiled query after 30 days. */
+export function latestFailingRowsQuery(runs: DataQualityCheckRunApi[]): string | null {
+ return runs.find((run) => run.compiled_query)?.compiled_query || null
+}
+
+export type SuiteRunOutcome = 'empty' | 'errored' | 'warning' | 'success'
+
+/** What a finished run amounts to. A 'failed' suite that failed no check errored on its own way in. */
+export function suiteRunOutcome(suiteRun: DataQualitySuiteRunApi): SuiteRunOutcome {
+ if (suiteRun.status === 'empty') {
+ return 'empty'
+ }
+ if (suiteRun.status === 'failed' && !suiteRun.checks_failed) {
+ return 'errored'
+ }
+ return suiteRun.checks_failed || suiteRun.checks_errored ? 'warning' : 'success'
+}
+
+interface SuiteRunPollCache {
+ pollElapsedMs: number
+ disposables: {
+ add: (create: () => () => void, key: string) => void
+ dispose: (key: string) => void
+ isDisposed: boolean
+ }
+}
+
+interface SuiteRunPollActions {
+ finishSuiteRun: (suiteRun: DataQualitySuiteRunApi) => unknown
+ scheduleSuiteRunPoll: () => unknown
+ pollActiveSuiteRun: () => unknown
+ setPollTimedOut: () => unknown
+}
+
+interface SuiteRunPollListeners {
+ setActiveSuiteRun: (payload: { suiteRun: DataQualitySuiteRunApi | null }) => void
+ scheduleSuiteRunPoll: () => void
+ pollActiveSuiteRun: () => Promise<void>
+}
+
+/**
+ * The three listeners that drive a suite run to its terminal state, for a logic that supplies its
+ * own retrieve. Both surfaces poll the same way against different endpoints, so the schedule, the
+ * backoff and the timeout live here rather than in each logic.
+ */
+export function suiteRunPollListeners({
+ retrieve,
+ onPollError,
+ cache: untypedCache,
+ values,
+ actions,
+}: {
+ retrieve: (suiteRunId: string) => Promise<DataQualitySuiteRunApi>
+ /** Handle a surface-specific failure. Return true to stop polling instead of retrying. */
+ onPollError?: (error: unknown) => boolean
+ // kea types `cache` as Record<string, any>, so the shape this needs is asserted once here
+ // rather than at both call sites.
+ cache: Record<string, any>
+ values: { activeSuiteRun: DataQualitySuiteRunApi | null }
+ actions: SuiteRunPollActions
+}): SuiteRunPollListeners {
+ const cache = untypedCache as SuiteRunPollCache
+ return {
+ setActiveSuiteRun: ({ suiteRun }: { suiteRun: DataQualitySuiteRunApi | null }): void => {
+ cache.disposables.dispose('suiteRunPoll')
+ cache.pollElapsedMs = 0
+ if (!suiteRun) {
+ return
+ }
+ if (isTerminalSuiteRun(suiteRun)) {
+ actions.finishSuiteRun(suiteRun)
+ return
+ }
+ actions.scheduleSuiteRunPoll()
+ },
+ scheduleSuiteRunPoll: (): void => {
+ const delay = pollDelayMs(cache.pollElapsedMs)
+ cache.disposables.add(() => {
+ const timeoutId = setTimeout(() => {
+ cache.pollElapsedMs += delay
+ actions.pollActiveSuiteRun()
+ }, delay)
+ return () => clearTimeout(timeoutId)
+ }, 'suiteRunPoll')
+ },
+ pollActiveSuiteRun: async (): Promise<void> => {
+ const running = values.activeSuiteRun
+ if (!running) {
+ return
+ }
+ let polled: DataQualitySuiteRunApi
+ try {
+ polled = await retrieve(running.id)
+ } catch (error) {
+ if (onPollError?.(error)) {
+ return
+ }
+ // Other failures are transient and not worth a toast, but they still count toward the
+ // cap, so a request that keeps failing stops rather than retrying 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()
+ },
+ }
+}
+
+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(', ')
+}
diff --git a/products/data_quality/mcp/tools.yaml b/products/data_quality/mcp/tools.yaml
index fe4aa2bfa42f..bf35922b3541 100644
--- a/products/data_quality/mcp/tools.yaml
+++ b/products/data_quality/mcp/tools.yaml
@@ -189,8 +189,11 @@ tools:
idempotent: true
title: Update a data quality check on a table
description: >
- Change a check's presentation (name, description, severity, enabled, tags). The assertion itself —
- check_type, column_name, config — is immutable; create a new check and delete this one instead.
+ Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it
+ asserts (check_type, column_name, config). The table it audits is fixed. The check keeps its id, run
+ history, latest status, and latest run time. A definition or name another active check already holds comes
+ back as a field error, with nothing written. Deleted checks release their definition, so it can be authored
+ again as a new check.
feature_flag: data-quality-checks
data-quality-check-update-on-view:
operation: warehouse_saved_queries_checks_partial_update
@@ -204,9 +207,27 @@ tools:
idempotent: true
title: Update a data quality check on a view
description: >
- Change a check's presentation (name, description, severity, enabled, tags). The assertion itself —
- check_type, column_name, config — is immutable; create a new check and delete this one instead.
+ Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it
+ asserts (check_type, column_name, config). The view it audits is fixed. The check keeps its id, run history,
+ latest status, and latest run time. A definition or name another active check already holds comes back as a
+ field error, with nothing written. Deleted checks release their definition, so it can be authored again as a
+ new check.
feature_flag: data-quality-checks
+ data-quality-checks-health-list:
+ operation: data_quality_checks_health_list
+ enabled: false
+ data-quality-checks-list:
+ operation: data_quality_checks_list
+ enabled: false
+ data-quality-runs-create:
+ operation: data_quality_runs_create
+ enabled: false
+ data-quality-runs-list:
+ operation: data_quality_runs_list
+ enabled: false
+ data-quality-runs-retrieve:
+ operation: data_quality_runs_retrieve
+ enabled: false
warehouse-saved-queries-check-suite-runs-check-runs-list:
operation: warehouse_saved_queries_check_suite_runs_check_runs_list
enabled: false
diff --git a/products/data_quality/package.json b/products/data_quality/package.json
index e9f312755a7f..101a56cf7b27 100644
--- a/products/data_quality/package.json
+++ b/products/data_quality/package.json
@@ -6,7 +6,8 @@
"dependencies": {
"kea": "catalog:",
"kea-forms": "catalog:",
- "kea-loaders": "catalog:"
+ "kea-loaders": "catalog:",
+ "kea-router": "catalog:"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.17.0",
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index 75d277e22f23..56e4d75f5945 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -34,7 +34,7 @@
e.`$window_id` AS `$window_id`,
if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
if(equals(e.event, 'user did things'), 1, 0) AS step_1,
- ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
+ ([e__person.properties___fish] AS value) AS prop_basic,
prop_basic AS prop
FROM events AS e
LEFT OUTER JOIN
@@ -44,6 +44,16 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -111,7 +121,17 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
GROUP BY breakdown
@@ -168,8 +188,8 @@
e.uuid AS uuid,
e.`$session_id` AS `$session_id`,
e.`$window_id` AS `$window_id`,
- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,
- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1
+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,
+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1
FROM events AS e
LEFT OUTER JOIN
(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
@@ -178,6 +198,16 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -294,7 +324,24 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -326,7 +373,24 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index c657af18789f..8909eb3e5d28 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -64,6 +64,7 @@ __all__ = [
"list_revenue_source_settings",
"get_schema",
"list_schemas_for_source",
+ "source_locations_for_tables",
"get_table",
"get_queryable_table",
"list_tables_for_source",
@@ -301,6 +302,19 @@ def list_schemas_for_source(source_id: UUID, team_id: int) -> list[contracts.Ext
return [_to_schema(s) for s in qs]
+def source_locations_for_tables(team_id: int, table_ids: Collection[UUID]) -> dict[UUID, contracts.TableSourceLocation]:
+ """Where each of these tables is administered. One query, and tables with no schema are absent."""
+ if not table_ids:
+ return {}
+ rows = _ExternalDataSchema.objects.filter(
+ team_id=team_id, table_id__in=list(table_ids), source_id__isnull=False
+ ).values_list("table_id", "source_id", "id")
+ return {
+ table_id: contracts.TableSourceLocation(source_id=source_id, schema_id=schema_id)
+ for table_id, source_id, schema_id in rows
+ }
+
+
def get_table(table_id: UUID, team_id: int) -> contracts.DataWarehouseTable:
return _to_table(_DataWarehouseTable.objects.get(id=table_id, team_id=team_id))
diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.py
index 2f6cba8b71a6..4343349a4ea5 100644
--- a/products/warehouse_sources/backend/facade/contracts.py
+++ b/products/warehouse_sources/backend/facade/contracts.py
@@ -137,6 +137,14 @@ class DataWarehouseTable:
created_at: datetime
+@dataclass(frozen=True)
+class TableSourceLocation:
+ """Where a synced table is administered: the source and schema its detail page hangs off."""
+
+ source_id: UUID
+ schema_id: UUID
+
+
# --- Job ---
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 385396955346..abbbe1a17381 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2850,7 +2850,7 @@
"feature_flag": "data-quality-checks"
},
"data-quality-check-update-on-table": {
- "description": "Change a check's presentation (name, description, severity, enabled, tags). The assertion itself — check_type, column_name, config — is immutable; create a new check and delete this one instead.",
+ "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The table it audits is fixed. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.",
"category": "Data quality",
"feature": "data_quality",
"summary": "Update a data quality check on a table",
@@ -2865,7 +2865,7 @@
"feature_flag": "data-quality-checks"
},
"data-quality-check-update-on-view": {
- "description": "Change a check's presentation (name, description, severity, enabled, tags). The assertion itself — check_type, column_name, config — is immutable; create a new check and delete this one instead.",
+ "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The view it audits is fixed. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.",
"category": "Data quality",
"feature": "data_quality",
"summary": "Update a data quality check on a view",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d6af57a1ecc5..c9235cddf597 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2865,7 +2865,7 @@
"feature_flag": "data-quality-checks"
},
"data-quality-check-update-on-table": {
- "description": "Change a check's presentation (name, description, severity, enabled, tags). The assertion itself — check_type, column_name, config — is immutable; create a new check and delete this one instead.",
+ "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The table it audits is fixed. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.",
"category": "Data quality",
"feature": "data_quality",
"summary": "Update a data quality check on a table",
@@ -2880,7 +2880,7 @@
"feature_flag": "data-quality-checks"
},
"data-quality-check-update-on-view": {
- "description": "Change a check's presentation (name, description, severity, enabled, tags). The assertion itself — check_type, column_name, config — is immutable; create a new check and delete this one instead.",
+ "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The view it audits is fixed. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.",
"category": "Data quality",
"feature": "data_quality",
"summary": "Update a data quality check on a view",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 98b44ab8a5fb..b3ab3eaf12b9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21150,6 +21150,11 @@ export namespace Schemas {
readonly last_run_at: string | null;
/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */
readonly last_status: string;
+ /**
+ * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.
+ * @nullable
+ */
+ readonly last_succeeded_at: string | null;
/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */
readonly fingerprint: string;
/** Whether a human ('user') or an agent ('ai_generated') authored this check.
@@ -21178,6 +21183,12 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ /**
+ * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.
+ * @nullable
+ */
+ export type DataQualityCheckRunCheckConfig = { [key: string]: unknown } | null;
+
export interface DataQualityCheckRun {
readonly id: string;
/**
@@ -21200,6 +21211,16 @@ export namespace Schemas {
* * `custom_sql` - custom_sql */
readonly check_type: CheckTypeEnum;
readonly column_name: string;
+ /**
+ * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.
+ * @nullable
+ */
+ readonly check_config: DataQualityCheckRunCheckConfig;
+ /** Severity this run was judged at. Null for runs recorded before snapshots existed.
+ *
+ * * `error` - error
+ * * `warn` - warn */
+ readonly check_severity: DataQualityCheckSeverityEnum | null;
/** passed, failed, errored, or skipped. */
readonly status: string;
/**
@@ -21252,6 +21273,136 @@ export namespace Schemas {
gate_materialization_on_checks: boolean;
}
+ /**
+ * Type-specific configuration, validated against the check type's JSON schema.
+ */
+ export type DataQualityOverviewCheckConfig = { [key: string]: unknown };
+
+ /**
+ * A check plus where its subject can be opened, for the project-wide list.
+ *
+ * The per-subject surfaces already know their parent; only this one lists checks across every
+ * table and view, so only this one needs to say where each subject lives. The ids are resolved
+ * for a whole page at once and handed in through ``subject_locations`` in the context.
+ */
+ export interface DataQualityOverviewCheck {
+ readonly id: string;
+ /**
+ * Optional identifier-safe handle, unique per project. Omit to address the check by id.
+ * @maxLength 128
+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$
+ */
+ name?: string;
+ /** Why this check exists and what a failure means. */
+ description?: string;
+ /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).
+ *
+ * * `table` - table
+ * * `view` - view */
+ readonly subject_type: SubjectTypeEnum;
+ /**
+ * Id of the table or view being checked -- the parent resource in the URL.
+ * @nullable
+ */
+ readonly subject_uuid: string | null;
+ /** Queryable name of the subject, refreshed on every run. */
+ readonly subject_name: string;
+ /** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */
+ readonly subject_status: string;
+ /**
+ * Column the check applies to. Omit for table-scoped types like row_count.
+ * @maxLength 400
+ */
+ column_name?: string;
+ /** Which assertion to make. Determines the shape of config; see /check_types/.
+ *
+ * * `not_null` - not_null
+ * * `unique` - unique
+ * * `accepted_values` - accepted_values
+ * * `relationships` - relationships
+ * * `row_count` - row_count
+ * * `freshness` - freshness
+ * * `custom_sql` - custom_sql */
+ check_type: CheckTypeEnum;
+ /** Type-specific configuration, validated against the check type's JSON schema. */
+ config?: DataQualityOverviewCheckConfig;
+ /** 'error' failures mark the subject failing and notify; 'warn' failures only surface.
+ *
+ * * `error` - error
+ * * `warn` - warn */
+ severity?: DataQualityCheckSeverityEnum;
+ /** Disabled checks are never run by any trigger. */
+ enabled?: boolean;
+ /** Free-form string labels for grouping and filtering. */
+ tags?: string[];
+ /**
+ * Email of the human accountable for this check, or null.
+ * @nullable
+ */
+ readonly owner: string | null;
+ /**
+ * When the check last executed.
+ * @nullable
+ */
+ readonly last_run_at: string | null;
+ /** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */
+ readonly last_status: string;
+ /**
+ * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.
+ * @nullable
+ */
+ readonly last_succeeded_at: string | null;
+ /** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */
+ readonly fingerprint: string;
+ /** Whether a human ('user') or an agent ('ai_generated') authored this check.
+ *
+ * * `user` - user
+ * * `ai_generated` - ai_generated */
+ created_source?: CreatedSourceEnum;
+ /**
+ * Model that generated the check, if AI-authored.
+ * @maxLength 128
+ */
+ ai_model?: string;
+ /**
+ * AI author's confidence in the check, 0-1.
+ * @minimum 0
+ * @maximum 1
+ * @nullable
+ */
+ confidence?: number | null;
+ /** AI author's reasoning, surfaced as review context. */
+ reasoning?: string;
+ /** User who first created this check. */
+ readonly created_by: UserBasic;
+ readonly created_at: string;
+ /** @nullable */
+ readonly updated_at: string | null;
+ /**
+ * Data modeling node of the view this check audits, or null when it is on no DAG or the subject is a table.
+ * @nullable
+ */
+ readonly subject_node_id: string | null;
+ /**
+ * Warehouse source of the table this check audits, or null when the subject is a view.
+ * @nullable
+ */
+ readonly subject_source_id: string | null;
+ /**
+ * Warehouse source schema of the table this check audits, or null when the subject is a view.
+ * @nullable
+ */
+ readonly subject_schema_id: string | null;
+ }
+
+ /**
+ * What to run in a project-wide suite run.
+ */
+ export interface DataQualityRunRequest {
+ /** Ids of the checks to run. Omit to run every enabled check in the project. */
+ check_ids?: string[];
+ }
+
/**
* Per-subject rollup, the same rule the information_schema.data_quality_health table uses.
*/
@@ -52260,6 +52411,15 @@ export namespace Schemas {
results: DataQualityCheck[];
}
+ export interface PaginatedDataQualityOverviewCheckList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: DataQualityOverviewCheck[];
+ }
+
export interface PaginatedDataQualitySuiteRunList {
count: number;
/** @nullable */
@@ -58976,6 +59136,11 @@ export namespace Schemas {
readonly last_run_at?: string | null;
/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */
readonly last_status?: string;
+ /**
+ * When the check last passed, so a failing check can say how long it has been failing. Null means it has not passed within the run retention window.
+ * @nullable
+ */
+ readonly last_succeeded_at?: string | null;
/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */
readonly fingerprint?: string;
/** Whether a human ('user') or an agent ('ai_generated') authored this check.
@@ -89267,6 +89432,28 @@ export namespace Schemas {
saved_query_id?: string;
};
+ export type DataQualityChecksListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type DataQualityRunsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type DataWarehouseCheckDatabaseNameRetrieveParams = {
/**
* Database name to check
diff --git a/services/mcp/src/generated/data_quality/api.ts b/services/mcp/src/generated/data_quality/api.ts
index 99dd40e471bd..d66243a697ce 100644
--- a/services/mcp/src/generated/data_quality/api.ts
+++ b/services/mcp/src/generated/data_quality/api.ts
@@ -88,7 +88,7 @@ export const WarehouseSavedQueriesChecksCreateBody = /* @__PURE__ */ zod
.describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const WarehouseSavedQueriesChecksPartialUpdateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this data quality check.'),
@@ -299,7 +299,7 @@ export const WarehouseTablesChecksCreateBody = /* @__PURE__ */ zod
.describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')
/**
- * CRUD for one subject's checks, plus the actions that run them and report on them.
+ * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.
*/
export const WarehouseTablesChecksPartialUpdateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this data quality check.'),
diff --git a/tools/playwright_area_map.json b/tools/playwright_area_map.json
index 9757e9f079c8..9a928d7dc2ca 100644
--- a/tools/playwright_area_map.json
+++ b/tools/playwright_area_map.json
@@ -78,7 +78,7 @@
"experiments": ["playwright/e2e/experiments/"],
"cohorts": ["playwright/e2e/product-analytics/cohorts.spec.ts"],
"trends": ["playwright/e2e/product-analytics/"],
- "data-warehouse": ["playwright/e2e/sql-editor*.spec.ts"],
+ "data-warehouse": ["playwright/e2e/sql-editor*.spec.ts", "playwright/e2e/data-quality-overview.spec.ts"],
"dashboard": [
"playwright/e2e/product-analytics/dashboards.spec.ts",
"playwright/e2e/shared-dashboard-styling.spec.ts",
@@ -140,7 +140,11 @@
"products/early_access_features/frontend/**": ["playwright/e2e/early-access-management.spec.ts"],
"products/event_definitions/frontend/**": ["playwright/e2e/event-definitions.spec.ts"],
"products/annotations/frontend/**": ["playwright/e2e/annotations.spec.ts"],
- "products/data_warehouse/frontend/**": ["playwright/e2e/sql-editor*.spec.ts"],
+ "products/data_warehouse/frontend/**": [
+ "playwright/e2e/sql-editor*.spec.ts",
+ "playwright/e2e/data-quality-overview.spec.ts"
+ ],
+ "products/data_quality/frontend/**": ["playwright/e2e/data-quality-overview.spec.ts"],
"products/workflows/frontend/**": [
"playwright/e2e/workflows-hidden-templates-load.spec.ts",
"playwright/e2e/workflows-property-filter-category-dropdown.spec.ts"