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): pick posthog tables in the check editor (#102497)

Thiago Salvatore410cbebf5025
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index 9aecb0781df1..636a6f466617 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -33,6 +33,7 @@ _LAZY = {
"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_node_ids_for_posthog_tables": "logic.saved_query_reads",
"dependent_saved_query_ids": "logic.saved_query_reads",
"get_saved_query_columns": "logic.saved_query_reads",
"get_saved_query_ids_for_nodes": "logic.saved_query_reads",
diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.py
index 8e23321d2f1c..ddf1290309c8 100644
--- a/products/data_modeling/backend/logic/saved_query_reads.py
+++ b/products/data_modeling/backend/logic/saved_query_reads.py
@@ -9,9 +9,11 @@ from django.conf import settings
from ..facade.contracts import SavedQuerySummary
from ..models.datawarehouse_saved_query import DataWarehouseSavedQuery
from ..models.edge import Edge
-from ..models.node import Node
+from ..models.node import Node, NodeType
from .saved_query_freshness import saved_query_materialized_at
+POSTHOG_TABLE_ORIGIN = "posthog"
+
if TYPE_CHECKING:
from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl
@@ -182,6 +184,28 @@ def get_node_ids_for_saved_queries(team_id: int, saved_query_ids: Iterable[UUID
return nodes
+def get_node_ids_for_posthog_tables(team_id: int, table_names: Iterable[str]) -> dict[str, str]:
+ """The DAG node each of these PostHog tables sits on, as one query. A table no view reads has none."""
+ names = list(table_names)
+ if not names:
+ return {}
+ rows = (
+ Node.objects.filter(
+ team_id=team_id,
+ type=NodeType.TABLE,
+ name__in=names,
+ saved_query__isnull=True,
+ properties__origin=POSTHOG_TABLE_ORIGIN,
+ )
+ .order_by("id")
+ .values_list("name", "id")
+ )
+ nodes: dict[str, str] = {}
+ for name, node_id in rows:
+ nodes.setdefault(name, 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/facade/api.py b/products/data_quality/backend/facade/api.py
index c3b797d1a4a5..064fbac4b8a3 100644
--- a/products/data_quality/backend/facade/api.py
+++ b/products/data_quality/backend/facade/api.py
@@ -32,7 +32,13 @@ from ..logic.output_schema import metric_output_schema
from ..logic.permissions import authorized_subject_types, restrict_subject_types, sql_denial_context, writable_subjects
from ..logic.registry import UnknownCheckTypeError, list_check_types
from ..logic.run_records import record_check_run
-from ..logic.schedule_service import get_schedule_with_history, schedule_with_history, update_schedule
+from ..logic.schedule_service import (
+ SubjectSchedule,
+ get_schedule_with_history,
+ list_schedules_with_history,
+ schedule_with_history,
+ update_schedule,
+)
from ..logic.schedules import CheckSchedule, ScheduleUnavailableError, ScheduleUpdateResult, get_schedule, set_schedule
from ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entry
from ..logic.subject_access import (
@@ -61,6 +67,7 @@ __all__ = [
"CheckSchedule",
"ScheduleUnavailableError",
"ScheduleUpdateResult",
+ "SubjectSchedule",
"CheckConfigError",
"CheckEditConflict",
"CheckStatusRow",
@@ -98,6 +105,7 @@ __all__ = [
"get_gate_config",
"get_schedule",
"get_schedule_with_history",
+ "list_schedules_with_history",
"list_check_types",
"metric_output_schema",
"notify_materialization_blocked",
diff --git a/products/data_quality/backend/facade/contracts.py b/products/data_quality/backend/facade/contracts.py
index db67d1ab0a38..8a8532894038 100644
--- a/products/data_quality/backend/facade/contracts.py
+++ b/products/data_quality/backend/facade/contracts.py
@@ -85,6 +85,7 @@ class SelectableSubject:
id: str
name: str
display_name: str = ""
+ time_column: str = ""
columns: dict[str, str] = field(default_factory=dict)
editable: bool = True
diff --git a/products/data_quality/backend/logic/navigation.py b/products/data_quality/backend/logic/navigation.py
index d91e9a28f079..6ad16b7b61c9 100644
--- a/products/data_quality/backend/logic/navigation.py
+++ b/products/data_quality/backend/logic/navigation.py
@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.facade import api as warehouse_facade
from ..facade.enums import SubjectType
from ..models import DataQualityCheck
+from . import posthog_tables
@frozen
@@ -55,4 +56,11 @@ def subject_locations(team_id: int, checks: Iterable[DataQualityCheck]) -> dict[
locations[SubjectKey(subject_type=SubjectType.METRIC, subject_uuid=str(metric_id))] = SubjectLocation(
metric_name=metric_name
)
+ posthog_table_names = {check.posthog_table for check in checks if check.posthog_table}
+ for name, node_id in data_modeling_facade.get_node_ids_for_posthog_tables(team_id, posthog_table_names).items():
+ entry = posthog_tables.by_name(name)
+ if entry is not None:
+ locations[SubjectKey(subject_type=SubjectType.POSTHOG_TABLE, subject_uuid=str(entry.id))] = SubjectLocation(
+ node_id=node_id
+ )
return locations
diff --git a/products/data_quality/backend/logic/schedule_service.py b/products/data_quality/backend/logic/schedule_service.py
index 2a57272e3b96..fe4eae050522 100644
--- a/products/data_quality/backend/logic/schedule_service.py
+++ b/products/data_quality/backend/logic/schedule_service.py
@@ -1,19 +1,21 @@
from __future__ import annotations
+from collections.abc import Sequence
from dataclasses import replace
from typing import TYPE_CHECKING
from uuid import UUID
+from posthog.dataclasses import frozen
+
from ..activity_logging import log_schedule_change
-from ..facade.enums import SuiteRunTrigger
+from ..facade.enums import SubjectType, SuiteRunTrigger
from ..models import DataQualitySuiteRun
-from .schedules import CheckSchedule, get_schedule, update_schedule_with_snapshots
+from .schedules import CheckSchedule, get_schedule, get_schedules, update_schedule_with_snapshots
from .subject_access import suites_backing_unreadable_runs_q, unreadable_suites_q
if TYPE_CHECKING:
from posthog.models import User
- from ..facade.enums import SubjectType
from .subject_access import DenialContext
@@ -39,6 +41,44 @@ def schedule_with_history(
return replace(schedule, last_run_at=last_suite.started_at, last_suite_run=last_suite.id)
+@frozen
+class SubjectSchedule:
+ subject_type: SubjectType
+ subject_uuid: UUID
+ schedule: CheckSchedule
+
+
+def list_schedules_with_history(
+ team_id: int,
+ subjects: Sequence[tuple[SubjectType, UUID]],
+ authorization_context: DenialContext | None = None,
+) -> list[SubjectSchedule]:
+ """Every subject's schedule with its last visible scheduled run, over one Temporal round trip and one query."""
+ schedules = get_schedules(team_id, subjects)
+ suites = DataQualitySuiteRun.objects.for_team(team_id).filter(
+ trigger=SuiteRunTrigger.SCHEDULED,
+ subject_type__in={str(subject_type) for subject_type, _ in subjects},
+ subject_uuid__in=[subject_uuid for _, subject_uuid in subjects],
+ )
+ if authorization_context is not None:
+ suites = suites.exclude(unreadable_suites_q(authorization_context)).exclude(
+ suites_backing_unreadable_runs_q(team_id, authorization_context)
+ )
+ last_suites = {
+ (suite.subject_type, suite.subject_uuid): suite
+ for suite in suites.order_by("subject_type", "subject_uuid", "-started_at", "-id").distinct(
+ "subject_type", "subject_uuid"
+ )
+ }
+ rows: list[SubjectSchedule] = []
+ for key, schedule in schedules.items():
+ last_suite = last_suites.get((str(key.subject_type), key.subject_uuid))
+ if last_suite is not None:
+ schedule = replace(schedule, last_run_at=last_suite.started_at, last_suite_run=last_suite.id)
+ rows.append(SubjectSchedule(subject_type=key.subject_type, subject_uuid=key.subject_uuid, schedule=schedule))
+ return rows
+
+
def get_schedule_with_history(
team_id: int,
subject_type: SubjectType,
diff --git a/products/data_quality/backend/logic/schedules.py b/products/data_quality/backend/logic/schedules.py
index 6796e3178582..6bdf5030652c 100644
--- a/products/data_quality/backend/logic/schedules.py
+++ b/products/data_quality/backend/logic/schedules.py
@@ -1,4 +1,5 @@
import asyncio
+from collections.abc import Sequence
from datetime import datetime
from uuid import UUID
@@ -116,6 +117,25 @@ async def get_schedule(team_id: int, subject_type: str, subject_uuid: str | UUID
raise ScheduleUnavailableError() from error
+@async_to_sync
+async def get_schedules(
+ team_id: int, subjects: Sequence[tuple[str, str | UUID]]
+) -> dict[SubjectScheduleKey, CheckSchedule]:
+ keys = [
+ await sync_to_async(schedule_key)(team_id, subject_type, subject_uuid)
+ for subject_type, subject_uuid in subjects
+ ]
+ if not keys:
+ return {}
+ try:
+ async with asyncio.timeout(SCHEDULE_REQUEST_TIMEOUT_SECONDS):
+ schedules = SubjectSchedules(await async_connect())
+ snapshots = await asyncio.gather(*(_describe_schedule(schedules, key) for key in keys))
+ except Exception as error:
+ raise ScheduleUnavailableError() from error
+ return {key: snapshot for key, snapshot in zip(keys, snapshots) if snapshot is not None}
+
+
@async_to_sync
async def set_schedule(
team_id: int,
diff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.py
index 6dedaf6d7875..03e5bc7e420a 100644
--- a/products/data_quality/backend/logic/subjects.py
+++ b/products/data_quality/backend/logic/subjects.py
@@ -102,6 +102,7 @@ def selectable_subjects(team_id: int, kinds: Collection[SubjectType]) -> list[Se
subject_type=SubjectType.POSTHOG_TABLE,
id=str(entry.id),
name=entry.name,
+ time_column=entry.time_column,
columns=entry.columns,
)
for entry in posthog_tables.TABLES
diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.py
index 5cf378bbd5fa..8535d23195a6 100644
--- a/products/data_quality/backend/presentation/serializers.py
+++ b/products/data_quality/backend/presentation/serializers.py
@@ -5,6 +5,8 @@ per-type ``config`` shape is validated against the registry's JSON schema rather
union: a new check type must not need a serializer change.
"""
+from typing import Any
+
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field, extend_schema_serializer
from rest_framework import serializers
@@ -54,6 +56,10 @@ class DataQualitySubjectSerializer(serializers.Serializer):
display_name = serializers.CharField(
allow_blank=True, help_text="Label shown in the data catalog. Blank for tables and views."
)
+ time_column = serializers.CharField(
+ allow_blank=True,
+ help_text="Column a lookback window bounds, or blank for a subject that has none.",
+ )
columns = serializers.DictField(
child=serializers.CharField(),
help_text="Column name to ClickHouse type. Empty for a metric, and for a view that has not run yet.",
@@ -267,8 +273,8 @@ class DataQualityOverviewCheckSerializer(DataQualityCheckSerializer):
"""
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."
+ help_text="Data modeling node of the view or PostHog table this check audits, or null when it is on "
+ "no DAG or the subject is a warehouse table."
)
subject_source_id = serializers.SerializerMethodField(
help_text="Warehouse source of the table this check audits, or null when the subject is a view."
@@ -344,6 +350,21 @@ class DataQualityCheckScheduleSerializer(serializers.Serializer):
)
+class DataQualitySubjectScheduleSerializer(DataQualityCheckScheduleSerializer):
+ """One subject's schedule, in the project-wide listing."""
+
+ subject_type = serializers.ChoiceField(
+ choices=[(t.value, t.value) for t in SubjectType], read_only=True, help_text="'metric' or 'posthog_table'."
+ )
+ subject_uuid = serializers.UUIDField(read_only=True, help_text="Id of the metric or PostHog table.")
+
+ def to_representation(self, instance: api.SubjectSchedule) -> dict[str, Any]:
+ row = super().to_representation(instance.schedule)
+ row["subject_type"] = str(instance.subject_type)
+ row["subject_uuid"] = str(instance.subject_uuid)
+ return row
+
+
@extend_schema_serializer(component_name="DataQualityCheckRun")
class DataQualityCheckRunSerializer(serializers.ModelSerializer):
status = serializers.CharField(read_only=True, help_text="passed, failed, errored, or skipped.")
diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.py
index 9ca3fa21c2c8..b68db08b4129 100644
--- a/products/data_quality/backend/presentation/views.py
+++ b/products/data_quality/backend/presentation/views.py
@@ -49,6 +49,7 @@ from .serializers import (
DataQualityOverviewCheckSerializer,
DataQualityRunRequestSerializer,
DataQualitySubjectRefSerializer,
+ DataQualitySubjectScheduleSerializer,
DataQualitySubjectSerializer,
DataQualitySuiteRunSerializer,
SubjectHealthSerializer,
@@ -391,7 +392,7 @@ class DataQualityCheckViewSet(_ProjectQualityViewSet, viewsets.ModelViewSet):
"metric_subjects",
}
)
- SUBJECT_FILTERED_ACTIONS = frozenset({"list", "health"})
+ SUBJECT_FILTERED_ACTIONS = frozenset({"list", "health", "schedules"})
serializer_class = DataQualityCheckSerializer
queryset = DataQualityCheck.objects.unscoped()
@@ -747,6 +748,26 @@ class DataQualityCheckViewSet(_ProjectQualityViewSet, viewsets.ModelViewSet):
raise ScheduleUnavailableAPIError() from error
return Response(DataQualityCheckScheduleSerializer(schedule).data)
+ @extend_schema(
+ description="The schedule of every subject in the project whose checks run on one, for the checks "
+ "the caller may read. One request for the overview instead of one per subject.",
+ request=None,
+ responses={200: DataQualitySubjectScheduleSerializer(many=True)},
+ )
+ @action(methods=["GET"], detail=False, pagination_class=None)
+ def schedules(self, request: Request, **kwargs) -> Response:
+ scheduled_kinds = [kind for kind in SubjectType if api.runs_on_a_schedule(kind)]
+ checks = self.filter_queryset(self.get_queryset()).filter(subject_type__in=scheduled_kinds)
+ subjects = sorted(
+ {(SubjectType(check.subject_type), check.subject_uuid) for check in checks if check.subject_uuid}
+ )
+ authorization_context = self._denial_context() if self._can_be_object_denied() else None
+ try:
+ schedules = api.list_schedules_with_history(self.team_id, subjects, authorization_context)
+ except api.ScheduleUnavailableError as error:
+ raise ScheduleUnavailableAPIError() from error
+ return Response(DataQualitySubjectScheduleSerializer(schedules, many=True).data)
+
def _scheduled_checks(self, subject: api.SubjectIdentity) -> QuerySet[DataQualityCheck]:
return api.checks_for_subject(self.team_id, subject.subject_type, subject.subject_uuid, include_deleted=True)
diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.py
index 3f5604c8ec13..aba1b419c406 100644
--- a/products/data_quality/backend/tests/test_api.py
+++ b/products/data_quality/backend/tests/test_api.py
@@ -171,6 +171,34 @@ class TestMetricCheckAPI(APIBaseTest):
assert self.client.delete(f"{self.url}/{check['id']}/").status_code == 204
assert self.client.get(f"{self.url}/schedule/?{self.subject_query}").status_code == 200
+ def test_the_schedule_listing_covers_every_scheduled_subject_in_one_round_trip(self) -> None:
+ events = by_name("events")
+ assert events is not None
+ self._create()
+ with self.captureOnCommitCallbacks(execute=True):
+ events_check = self.client.post(
+ f"{self.url}/",
+ {
+ "subject_type": SubjectType.POSTHOG_TABLE,
+ "subject_uuid": str(events.id),
+ "check_type": CheckType.NOT_NULL,
+ "column_name": "distinct_id",
+ "config": {},
+ },
+ )
+ assert events_check.status_code == status.HTTP_201_CREATED, events_check.json()
+ self.connect.reset_mock()
+
+ response = self.client.get(f"{self.url}/schedules/")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert sorted((row["subject_type"], row["subject_uuid"]) for row in response.json()) == [
+ ("metric", str(self.metric.id)),
+ ("posthog_table", str(events.id)),
+ ]
+ assert {row["interval"] for row in response.json()} == {"24hour"}
+ assert self.connect.await_count == 1
+
def test_schedule_patch_reuses_one_connection_and_records_snapshots(self) -> None:
self._create()
self.connect.reset_mock()
diff --git a/products/data_quality/backend/tests/test_runs_api.py b/products/data_quality/backend/tests/test_runs_api.py
index dcf4a3ebc460..f9c619477972 100644
--- a/products/data_quality/backend/tests/test_runs_api.py
+++ b/products/data_quality/backend/tests/test_runs_api.py
@@ -951,17 +951,28 @@ class TestDataQualityRunAPI(APIBaseTest):
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)
+ dag = DAG.get_or_create_default(self.team)
+ node = Node.objects.create(team=self.team, dag=dag, saved_query=self.orders)
+ events_node = Node.objects.create(team=self.team, dag=dag, name="events", properties={"origin": "posthog"})
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
)
+ self._check(
+ self.orders,
+ subject_type=SubjectType.POSTHOG_TABLE,
+ saved_query_id=None,
+ posthog_table="events",
+ subject_name="events",
+ column_name="distinct_id",
+ )
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["events"]["subject_node_id"] == str(events_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)
diff --git a/products/data_quality/frontend/CheckEditorModal.tsx b/products/data_quality/frontend/CheckEditorModal.tsx
index 65546c62602f..8453057f0c93 100644
--- a/products/data_quality/frontend/CheckEditorModal.tsx
+++ b/products/data_quality/frontend/CheckEditorModal.tsx
@@ -25,9 +25,9 @@ import { urls } from 'scenes/urls'
import { escapePropertyAsHogQLIdentifier } from '~/queries/utils'
import type { DataQualitySubjectRef } from './checksApi'
-import { checkTypeLabel } from './checksConstants'
+import { checkTypeLabel, subjectTypeLabel } from './checksConstants'
import { dataQualityCheckEditorLogic } from './dataQualityCheckEditorLogic'
-import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi, SubjectTypeEnumApi } from './generated/api.schemas'
+import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi } from './generated/api.schemas'
import { formatPreviewCell } from './previewCell'
type CodeEditorInstance = Parameters<NonNullable<CodeEditorProps['onMount']>>[0]
@@ -42,12 +42,10 @@ export function CheckEditorModal(): JSX.Element {
checkTypesLoading,
requiresColumn,
availableColumns,
- databaseLoading,
- databaseLoadError,
openedWithoutSubject,
selectableSubjects,
- metricSubjectsLoading,
- metricSubjectsError,
+ checkSubjectsLoading,
+ checkSubjectsError,
subject,
isCheckFormSubmitting,
serverError,
@@ -57,16 +55,9 @@ export function CheckEditorModal(): JSX.Element {
const formShapeLoading = checkTypesLoading && !checkTypes.length
const awaitingSubject = openedWithoutSubject && !subject
const checkTypesFailedEmpty = checkTypesError && !checkTypesLoading && !checkTypes.length
- const subjectCatalogLoading = databaseLoading || metricSubjectsLoading
- const {
- loadCheckTypes,
- loadDatabase,
- loadMetricSubjects,
- requestClose,
- setCheckFormValues,
- setSubject,
- submitCheckForm,
- } = useActions(dataQualityCheckEditorLogic)
+ const catalogFailed = !!checkSubjectsError && !checkSubjectsLoading
+ const { loadCheckTypes, loadCheckSubjects, requestClose, setCheckFormValues, setSubject, submitCheckForm } =
+ useActions(dataQualityCheckEditorLogic)
return (
<LemonModal
@@ -94,7 +85,9 @@ export function CheckEditorModal(): JSX.Element {
? 'Loading the check types'
: checkTypesFailedEmpty
? 'Load the check types to continue'
- : undefined
+ : catalogFailed && !openedWithoutSubject
+ ? 'Load the columns to continue'
+ : undefined
}
data-attr="data-quality-check-save"
>
@@ -123,11 +116,7 @@ export function CheckEditorModal(): JSX.Element {
<div className="flex items-center justify-between gap-2 w-full">
<span>{candidate.name}</span>
<LemonTag type="muted" size="small">
- {candidate.type === SubjectTypeEnumApi.Metric
- ? 'Metric'
- : candidate.type === SubjectTypeEnumApi.View
- ? 'View'
- : 'Table'}
+ {subjectTypeLabel(candidate.type)}
</LemonTag>
</div>
),
@@ -145,28 +134,20 @@ export function CheckEditorModal(): JSX.Element {
}
setSubject(selectedSubject)
}}
- loading={subjectCatalogLoading}
+ loading={checkSubjectsLoading}
placeholder="Search tables, views, and metrics"
data-attr="data-quality-check-subject"
/>
</LemonField.Pure>
- {databaseLoadError && !databaseLoading ? (
- <div className="flex items-center gap-2 text-secondary text-sm">
- <span>Couldn't load your tables and views.</span>
- <LemonButton size="small" type="secondary" onClick={() => loadDatabase()}>
- Retry
- </LemonButton>
- </div>
- ) : null}
- {metricSubjectsError && !metricSubjectsLoading ? (
+ {catalogFailed ? (
<div className="flex items-center gap-2 text-secondary text-sm">
- <span>Couldn't load your metrics.</span>
- <LemonButton size="small" type="secondary" onClick={loadMetricSubjects}>
+ <span>Couldn't load what you can check.</span>
+ <LemonButton size="small" type="secondary" onClick={loadCheckSubjects}>
Retry
</LemonButton>
</div>
) : null}
- {!subjectCatalogLoading && selectableSubjects.length === 0 ? (
+ {!checkSubjectsLoading && selectableSubjects.length === 0 ? (
<p className="mb-0 text-secondary text-sm">
<Link to={urls.database()}>Browse tables and views</Link> or{' '}
<Link to={urls.metrics()}>create a HogQL metric</Link> first.
@@ -174,6 +155,14 @@ export function CheckEditorModal(): JSX.Element {
) : null}
</div>
)}
+ {catalogFailed && !openedWithoutSubject && (
+ <div className="flex items-center gap-2 mb-3 text-secondary text-sm">
+ <span>Couldn't load the columns for this subject.</span>
+ <LemonButton size="small" type="secondary" onClick={loadCheckSubjects}>
+ Retry
+ </LemonButton>
+ </div>
+ )}
{checkTypesFailedEmpty && (
<div className="flex items-center gap-2 py-8 justify-center text-secondary">
<span>Couldn't load check types.</span>
@@ -221,7 +210,7 @@ export function CheckEditorModal(): JSX.Element {
{requiresColumn && (
<LemonField name="columnName" label="Column">
<LemonSelect
- loading={databaseLoading && !availableColumns.length}
+ loading={checkSubjectsLoading && !availableColumns.length}
options={availableColumns.map((column) => ({ value: column, label: column }))}
/>
</LemonField>
@@ -229,6 +218,8 @@ export function CheckEditorModal(): JSX.Element {
<CheckConfigFields checkType={checkForm.checkType} />
+ <LookbackField />
+
<LemonField
name="name"
label="Name"
@@ -502,7 +493,8 @@ function CustomSqlField(): JSX.Element {
}
function RelationshipFields(): JSX.Element {
- const { checkForm, relationshipSubjects, databaseLoading } = useValues(dataQualityCheckEditorLogic)
+ const { checkForm, relationshipSubjects, checkSubjectsLoading, relationshipTargetTimeColumn } =
+ useValues(dataQualityCheckEditorLogic)
const { setCheckFormValues } = useActions(dataQualityCheckEditorLogic)
const selected = relationshipSubjects.find((subject) => subject.id === checkForm.toSubjectUuid)
@@ -512,7 +504,7 @@ function RelationshipFields(): JSX.Element {
<LemonField name="toSubjectUuid" label="References table or view">
<LemonInputSelect
mode="single"
- loading={databaseLoading}
+ loading={checkSubjectsLoading}
value={checkForm.toSubjectUuid ? [checkForm.toSubjectUuid] : []}
options={relationshipSubjects.map((subject) => ({ key: subject.id, label: subject.name }))}
onChange={(selectedIds) => {
@@ -524,6 +516,10 @@ function RelationshipFields(): JSX.Element {
toSubjectUuid,
toSubjectType: relationshipSubjects.find((subject) => subject.id === toSubjectUuid)?.type,
toColumn: '',
+ // The window belongs to the target it was set on, and the field hides
+ // itself for a target with no time column. A kept value would reach
+ // the request where nobody can see or clear it.
+ toLookbackHours: null,
})
}}
/>
@@ -534,6 +530,34 @@ function RelationshipFields(): JSX.Element {
options={(selected?.fields ?? []).map((field) => ({ value: field, label: field }))}
/>
</LemonField>
+ {relationshipTargetTimeColumn ? (
+ <LemonField
+ name="toLookbackHours"
+ label="Only look for a match in recent rows"
+ showOptional
+ help={`Hours of ${selected?.name ?? 'the referenced table'} to look in, by ${relationshipTargetTimeColumn}. Leave empty to look in all of it.`}
+ >
+ <LemonInput type="number" min={1} placeholder="24" />
+ </LemonField>
+ ) : null}
</>
)
}
+
+function LookbackField(): JSX.Element | null {
+ const { checkForm, subjectTimeColumn } = useValues(dataQualityCheckEditorLogic)
+
+ if (!subjectTimeColumn || checkForm.checkType === CheckTypeEnumApi.CustomSql) {
+ return null
+ }
+ return (
+ <LemonField
+ name="lookbackHours"
+ label="Only check recent rows"
+ showOptional
+ help={`Hours to check, by ${subjectTimeColumn}. Leave empty to check the whole table, which costs more to run.`}
+ >
+ <LemonInput type="number" min={1} placeholder="24" />
+ </LemonField>
+ )
+}
diff --git a/products/data_quality/frontend/DataQualitySchedule.tsx b/products/data_quality/frontend/DataQualitySchedule.tsx
index 77f2e720ad18..3fb067cec583 100644
--- a/products/data_quality/frontend/DataQualitySchedule.tsx
+++ b/products/data_quality/frontend/DataQualitySchedule.tsx
@@ -26,8 +26,9 @@ function NextRunTime({ nextRunAt }: { nextRunAt: string }): JSX.Element {
}
export function DataQualitySchedule(props: DataQualityScheduleLogicProps): JSX.Element {
- const { schedule, scheduleLoading, scheduleError } = useValues(dataQualityScheduleLogic(props))
- const { loadSchedule, updateSchedule } = useActions(dataQualityScheduleLogic(props))
+ const logic = dataQualityScheduleLogic(props)
+ const { schedule, scheduleLoading, scheduleError } = useValues(logic)
+ const { loadSchedule, updateSchedule } = useActions(logic)
if (!schedule) {
return scheduleError ? (
diff --git a/products/data_quality/frontend/checksApi.ts b/products/data_quality/frontend/checksApi.ts
index ea9138d90f51..0334926fa3b6 100644
--- a/products/data_quality/frontend/checksApi.ts
+++ b/products/data_quality/frontend/checksApi.ts
@@ -13,6 +13,7 @@ import {
dataQualityChecksRunsList,
dataQualityChecksSchedulePartialUpdate,
dataQualityChecksScheduleRetrieve,
+ dataQualityChecksSchedulesList,
dataQualityChecksSubjectsList,
dataQualityRunsCheckRunsList,
dataQualityRunsCreate,
@@ -28,6 +29,7 @@ import type {
DataQualityOutputSchemaApi,
DataQualitySubjectApi,
DataQualitySubjectHealthApi,
+ DataQualitySubjectScheduleApi,
DataQualitySuiteRunApi,
PatchedDataQualityCheckScheduleUpdateApi,
PaginatedDataQualityOverviewCheckListApi,
@@ -109,6 +111,8 @@ export const checksApi = {
schedule: (ref: DataQualitySubjectRef): Promise<DataQualityCheckScheduleApi> =>
dataQualityChecksScheduleRetrieve(projectId(), subjectParams(ref)),
+ schedules: (): Promise<DataQualitySubjectScheduleApi[]> => dataQualityChecksSchedulesList(projectId()),
+
updateSchedule: (
ref: DataQualitySubjectRef,
patch: PatchedDataQualityCheckScheduleUpdateApi
diff --git a/products/data_quality/frontend/checksConstants.ts b/products/data_quality/frontend/checksConstants.ts
index 69108c5f2654..f6211be480a7 100644
--- a/products/data_quality/frontend/checksConstants.ts
+++ b/products/data_quality/frontend/checksConstants.ts
@@ -68,6 +68,7 @@ export const SUBJECT_TYPE_TAGS: Record<string, { label: string; type: LemonTagTy
table: { label: 'Table', type: 'default' },
view: { label: 'View', type: 'primary' },
metric: { label: 'Metric', type: 'option' },
+ posthog_table: { label: 'PostHog', type: 'highlight' },
}
export const SEVERITY_TAG_TYPES: Record<string, LemonTagType> = {
@@ -98,6 +99,10 @@ export function checkTypeLabel(checkType: string): string {
return CHECK_TYPE_LABELS[checkType] ?? checkType
}
+export function subjectTypeLabel(subjectType: string): string {
+ return SUBJECT_TYPE_TAGS[subjectType]?.label ?? subjectType
+}
+
interface NamedCheck {
name?: string | null
check_type: string
diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts
index 068311a936d2..44fd52be7f96 100644
--- a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts
+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts
@@ -1,6 +1,5 @@
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 { performQuery } from '~/queries/query'
@@ -12,7 +11,7 @@ import { DataQualityCheckEditorLogicProps, dataQualityCheckEditorLogic } from '.
import {
dataQualityChecksCheckTypesList,
dataQualityChecksCreate,
- dataQualityChecksMetricSubjectsList,
+ dataQualityChecksSubjectsList,
dataQualityChecksOutputSchemaRetrieve,
dataQualityChecksPartialUpdate,
} from './generated/api'
@@ -58,37 +57,10 @@ jest.mock('~/queries/query', () => ({
performQuery: 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({ ensureAllTableFields: true, loadDatabase: true }),
- reducers({
- views: [[{ id: 'view-7', name: 'orders_view', fields: { order_id: { type: 'string' } } }]],
- dataWarehouseTables: [
- [
- {
- id: 'table-9',
- name: 'stripe_charges',
- fields: { customer_id: { type: 'string' }, amount: { type: 'decimal' } },
- },
- ],
- ],
- databaseLoading: [false],
- databaseLoadError: [null],
- loadCount: [0, { ensureAllTableFields: (state: number) => state + 1 }],
- }),
- ]),
- }
-})
-
jest.mock('./generated/api', () => ({
dataQualityChecksCheckTypesList: jest.fn(),
dataQualityChecksCreate: jest.fn(),
- dataQualityChecksMetricSubjectsList: jest.fn(),
+ dataQualityChecksSubjectsList: jest.fn(),
dataQualityChecksOutputSchemaRetrieve: jest.fn(),
dataQualityChecksPartialUpdate: jest.fn(),
}))
@@ -96,6 +68,45 @@ jest.mock('./generated/api', () => ({
const VIEW_SUBJECT: DataQualitySubjectRef = { subjectType: 'view', subjectId: 'view-1' }
const COLUMNS = ['customer_id', 'status', 'created_at', 'total']
+const SUBJECT_CATALOG = [
+ {
+ subject_type: 'view',
+ id: 'view-7',
+ name: 'orders_view',
+ display_name: '',
+ time_column: '',
+ columns: { order_id: 'string' },
+ editable: true,
+ },
+ {
+ subject_type: 'table',
+ id: 'table-9',
+ name: 'stripe_charges',
+ display_name: '',
+ time_column: '',
+ columns: { customer_id: 'string', amount: 'decimal' },
+ editable: false,
+ },
+ {
+ subject_type: 'metric',
+ id: 'metric-1',
+ name: 'daily_signups',
+ display_name: 'Daily signups',
+ time_column: '',
+ columns: {},
+ editable: true,
+ },
+ {
+ subject_type: 'posthog_table',
+ id: 'events-1',
+ name: 'events',
+ display_name: '',
+ time_column: 'timestamp',
+ columns: { distinct_id: 'string', timestamp: 'datetime' },
+ editable: true,
+ },
+]
+
const CHECK_TYPE_CATALOG = [
{ check_type: 'not_null', description: '', requires_column: true, config_schema: {} },
{ check_type: 'unique', description: '', requires_column: true, config_schema: {} },
@@ -159,10 +170,7 @@ describe('dataQualityCheckEditorLogic', () => {
jest.clearAllMocks()
silenceKeaLoadersErrors()
;(dataQualityChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG)
- ;(dataQualityChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG)
- ;(dataQualityChecksMetricSubjectsList as jest.Mock).mockResolvedValue([
- { id: 'metric-1', name: 'daily_signups', display_name: 'Daily signups' },
- ])
+ ;(dataQualityChecksSubjectsList as jest.Mock).mockResolvedValue(SUBJECT_CATALOG)
;(dataQualityChecksOutputSchemaRetrieve as jest.Mock).mockResolvedValue({
columns: [
{ name: 'day', type: 'Nullable(Date)' },
@@ -191,7 +199,7 @@ describe('dataQualityCheckEditorLogic', () => {
})
expect(logic.values.checkTypes.map((type) => type.check_type)).toEqual(['custom_sql'])
expect(logic.values.requiresColumn).toBe(false)
- expect(logic.values.needsWarehouseCatalog).toBe(false)
+ expect(logic.values.needsSubjectCatalog).toBe(false)
expect(logic.values.isMetricSubject).toBe(true)
expect(logic.values.availableOutputSchema).toEqual([
{ name: 'day', type: 'Nullable(Date)' },
@@ -406,6 +414,41 @@ describe('dataQualityCheckEditorLogic', () => {
})
})
+ it.each<[string, Partial<DataQualityCheckApi>]>([
+ [
+ 'a relationships check with no target window',
+ {
+ check_type: CheckTypeEnumApi.Relationships,
+ config: {
+ to_subject_type: 'table',
+ to_subject_uuid: 'table-9',
+ to_column: 'customer_id',
+ to_lookback_hours: null,
+ },
+ },
+ ],
+ [
+ 'a row_count check with only a minimum',
+ { check_type: CheckTypeEnumApi.RowCount, column_name: '', config: { min: 10, max: null } },
+ ],
+ ])('leaves the assertion out of a metadata-only edit of %s', async (_case, storedCheck) => {
+ // The stored config writes an unset value as null, so a comparison that counts keys reads
+ // every rename as an assertion edit and sends a definition the backend then revalidates.
+ ;(dataQualityChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())
+ await mountLogic()
+ await openWith(buildCheck(storedCheck), { description: 'renamed' })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataQualityChecksPartialUpdate).toHaveBeenCalledWith('1', 'check-1', {
+ severity: 'error',
+ name: '',
+ description: 'renamed',
+ tags: [],
+ })
+ })
+
it('does not submit before the check-type catalog arrives', async () => {
// Enter can submit while the catalog request is still pending. Without it there is no column
// requirement to validate against, so the payload would omit column_name and be rejected.
@@ -458,6 +501,52 @@ describe('dataQualityCheckEditorLogic', () => {
expect(logic.values.isOpen).toBe(true)
})
+ it.each<[string, Record<string, unknown>, 'lookbackHours' | 'toLookbackHours']>([
+ [
+ 'a window of zero hours',
+ { checkType: 'not_null', columnName: 'customer_id', lookbackHours: 0 },
+ 'lookbackHours',
+ ],
+ [
+ 'a window of half an hour',
+ { checkType: 'not_null', columnName: 'customer_id', lookbackHours: 0.5 },
+ 'lookbackHours',
+ ],
+ [
+ 'a target window of zero hours',
+ {
+ checkType: 'relationships',
+ columnName: 'customer_id',
+ toSubjectUuid: 'table-9',
+ toColumn: 'customer_id',
+ toLookbackHours: 0,
+ },
+ 'toLookbackHours',
+ ],
+ ])('refuses to submit %s and says so beside that window', async (_case, formValues, field) => {
+ await mountLogic()
+ await openWith(null, formValues)
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataQualityChecksCreate).not.toHaveBeenCalled()
+ expect(logic.values.checkFormErrors[field as 'name']).toEqual('Set a whole number of hours, at least one.')
+ })
+
+ it('reads a cleared window as no window rather than a bad one', async () => {
+ ;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(buildCheck())
+ await mountLogic()
+ // What the number input emits once its content is deleted.
+ await openWith(null, { checkType: 'not_null', columnName: 'customer_id', lookbackHours: NaN })
+
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.checkFormErrors.lookbackHours).toBeUndefined()
+ expect(dataQualityChecksCreate).toHaveBeenCalledWith('1', expect.objectContaining({ config: {} }))
+ })
+
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.
;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ id: 'check-new' }))
@@ -745,7 +834,7 @@ describe('dataQualityCheckEditorLogic', () => {
await expectLogic(logic).toFinishAllListeners()
expect(dataQualityChecksCheckTypesList).not.toHaveBeenCalled()
- expect((databaseTableListLogic.values as unknown as { loadCount: number }).loadCount).toEqual(1)
+ expect((dataQualityChecksSubjectsList as jest.Mock).mock.calls.length).toEqual(1)
logic.actions.setSubject(subject)
await expectLogic(logic).toFinishAllListeners()
@@ -883,18 +972,127 @@ describe('dataQualityCheckEditorLogic', () => {
expect(logic.values.checkFormChanged).toBe(false)
})
+ it('offers every editable subject as a parent and a read-only one only as a target', async () => {
+ await mountLogic({ surface: 'overview' })
+
+ logic.actions.openEditor(null, null)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.selectableSubjects).toEqual([
+ { id: 'view-7', name: 'orders_view', type: 'view' },
+ { id: 'metric-1', name: 'Daily signups', type: 'metric' },
+ { id: 'events-1', name: 'events', type: 'posthog_table' },
+ ])
+ expect(logic.values.relationshipSubjects.map((subject) => subject.id)).toEqual([
+ 'view-7',
+ 'table-9',
+ 'events-1',
+ ])
+ })
+
+ it.each<[Record<string, unknown>, string | null]>([
+ [{ subjectType: 'posthog_table', subjectId: 'events-1' }, 'timestamp'],
+ [{ subjectType: 'table', subjectId: 'table-9' }, null],
+ ])('offers a lookback window only for a subject with a time column (%o)', async (subject, expected) => {
+ await mountLogic({ surface: 'overview' })
+ logic.actions.openEditor(null, null)
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setSubject(subject as never)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.subjectTimeColumn).toEqual(expected)
+ })
+
+ it('sends the window it was given, and drops it for custom SQL', async () => {
+ ;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(buildCheck())
+ await mountLogic({ surface: 'overview' })
+ logic.actions.openEditor(null, null)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setSubject({ subjectType: 'posthog_table', subjectId: 'events-1' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setCheckFormValues({ checkType: 'not_null', columnName: 'distinct_id', lookbackHours: 24 })
+ logic.actions.submitCheckForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataQualityChecksCreate).toHaveBeenCalledWith(
+ '1',
+ expect.objectContaining({ config: { lookback_hours: 24 } })
+ )
+ })
+
+ it('offers a target window only when the referenced subject has a time column', async () => {
+ await mountLogic({ surface: 'overview' })
+ logic.actions.openEditor(null, { subjectType: 'view', subjectId: 'view-7' }, COLUMNS)
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setCheckFormValues({ checkType: 'relationships' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setCheckFormValues({ toSubjectUuid: 'table-9' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.relationshipTargetTimeColumn).toBeNull()
+
+ logic.actions.setCheckFormValues({ toSubjectUuid: 'events-1' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.relationshipTargetTimeColumn).toEqual('timestamp')
+ })
+
+ it('asks again after a failed subject catalog load', async () => {
+ ;(dataQualityChecksSubjectsList as jest.Mock).mockRejectedValueOnce(new Error('down'))
+ await mountLogic({ surface: 'overview' })
+ logic.actions.openEditor(null, null)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.checkSubjectsError).toEqual('down')
+
+ logic.actions.setCheckFormValues({ checkType: 'not_null' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect((dataQualityChecksSubjectsList as jest.Mock).mock.calls.length).toEqual(2)
+ expect(logic.values.checkSubjectsError).toBeNull()
+ })
+
+ it.each<[string, DataQualitySubjectRef, CheckTypeEnumApi, string[], string | null]>([
+ [
+ 'a PostHog table not_null check',
+ { subjectType: 'posthog_table', subjectId: 'events-1' },
+ CheckTypeEnumApi.NotNull,
+ ['distinct_id', 'timestamp'],
+ 'timestamp',
+ ],
+ [
+ 'a PostHog table row_count check',
+ { subjectType: 'posthog_table', subjectId: 'events-1' },
+ CheckTypeEnumApi.RowCount,
+ ['distinct_id', 'timestamp'],
+ 'timestamp',
+ ],
+ ['a view check', { subjectType: 'view', subjectId: 'view-7' }, CheckTypeEnumApi.NotNull, ['order_id'], null],
+ ])(
+ 'resolves the columns and time column of %s opened for edit',
+ async (_case, subject, checkType, expectedColumns, expectedTimeColumn) => {
+ await mountLogic({ surface: 'overview' })
+
+ logic.actions.openEditor(buildCheck({ check_type: checkType, config: { lookback_hours: 24 } }), subject)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.availableColumns).toEqual(expectedColumns)
+ expect(logic.values.subjectTimeColumn).toEqual(expectedTimeColumn)
+ }
+ )
+
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) => {
+ ])('loads the subject 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)
+ expect((dataQualityChecksSubjectsList as jest.Mock).mock.calls.length).toEqual(expected)
})
- it('loads the warehouse catalog once across type switches', async () => {
+ it('loads the subject catalog once across type switches', async () => {
await mountLogic()
await openWith(null, { checkType: 'relationships' })
@@ -902,10 +1100,10 @@ describe('dataQualityCheckEditorLogic', () => {
logic.actions.setCheckFormValues({ checkType: 'relationships' })
await expectLogic(logic).toFinishAllListeners()
- expect((databaseTableListLogic.values as unknown as { loadCount: number }).loadCount).toEqual(1)
+ expect((dataQualityChecksSubjectsList as jest.Mock).mock.calls.length).toEqual(1)
})
- it('keeps the warehouse catalog loaded when reopening an unscoped draft', async () => {
+ it('reloads the subject catalog when reopening an unscoped draft', async () => {
await mountLogic({ surface: 'overview' })
logic.actions.openEditor(null, null)
await expectLogic(logic).toFinishAllListeners()
@@ -914,6 +1112,6 @@ describe('dataQualityCheckEditorLogic', () => {
logic.actions.openEditor(null, null)
await expectLogic(logic).toFinishAllListeners()
- expect((databaseTableListLogic.values as unknown as { loadCount: number }).loadCount).toEqual(1)
+ expect((dataQualityChecksSubjectsList as jest.Mock).mock.calls.length).toEqual(2)
})
})
diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.ts
index df3e766ae5a5..b1ed8c0b6090 100644
--- a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts
+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, 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'
@@ -7,14 +7,10 @@ import { ApiError } from 'lib/api'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { objectsEqual } from 'lib/utils/objects'
-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { performQuery } from '~/queries/query'
import {
AccessControlFilterWarning,
- type DatabaseSchemaDataWarehouseTable,
- type DatabaseSchemaField,
- type DatabaseSchemaViewTable,
DataWarehouseSyncWarning,
HogQLQuery,
NodeKind,
@@ -24,9 +20,9 @@ import { DataQualitySubjectRef, checksApi } from './checksApi'
import type {
DataQualityCheckApi,
DataQualityCheckTypeApi,
- DataQualityMetricSubjectApi,
DataQualityOutputColumnApi,
DataQualityOutputSchemaApi,
+ DataQualitySubjectApi,
} from './generated/api.schemas'
import { CheckTypeEnumApi, DataQualityCheckSeverityEnumApi, SubjectTypeEnumApi } from './generated/api.schemas'
@@ -54,6 +50,8 @@ export interface CheckFormValues {
rowCountMax: number | null
maxAgeMinutes: number | null
customSql: string
+ lookbackHours: number | null
+ toLookbackHours: number | null
}
export const EMPTY_CHECK_FORM: CheckFormValues = {
@@ -71,6 +69,8 @@ export const EMPTY_CHECK_FORM: CheckFormValues = {
rowCountMax: null,
maxAgeMinutes: null,
customSql: '',
+ lookbackHours: null,
+ toLookbackHours: null,
}
/** A warehouse table or view a relationships check can point at. */
@@ -80,6 +80,7 @@ export interface RelationshipSubject {
type: SubjectTypeEnumApi
fields: string[]
outputSchema: DataQualityOutputColumnApi[]
+ timeColumn: string | null
}
export interface SelectableSubject {
@@ -106,6 +107,11 @@ export interface DataQualityCheckEditorLogicProps {
onClosed?: () => void
}
+/** A cleared number input reads as NaN, which means no window rather than a window of no length. */
+function isWindow(hours: number | null): hours is number {
+ return hours !== null && Number.isFinite(hours)
+}
+
function formToConfig(form: CheckFormValues): Record<string, unknown> {
switch (form.checkType) {
case CheckTypeEnumApi.AcceptedValues:
@@ -115,6 +121,7 @@ function formToConfig(form: CheckFormValues): Record<string, unknown> {
to_subject_type: form.toSubjectType,
to_subject_uuid: form.toSubjectUuid,
to_column: form.toColumn,
+ ...(isWindow(form.toLookbackHours) ? { to_lookback_hours: form.toLookbackHours } : {}),
}
case CheckTypeEnumApi.RowCount: {
const min = form.rowCountMin ?? null
@@ -132,10 +139,11 @@ function formToConfig(form: CheckFormValues): Record<string, unknown> {
/** Only the selected type's configuration, so switching type cannot leave stale values behind. */
function definitionPayload(form: CheckFormValues, requiresColumn: boolean): CheckDefinitionPayload {
+ const windowed = isWindow(form.lookbackHours) && form.checkType !== CheckTypeEnumApi.CustomSql
return {
check_type: form.checkType,
column_name: requiresColumn ? form.columnName : '',
- config: formToConfig(form),
+ config: { ...formToConfig(form), ...(windowed ? { lookback_hours: form.lookbackHours } : {}) },
}
}
@@ -153,12 +161,17 @@ export function checkCreatePayload(form: CheckFormValues, requiresColumn: boolea
}
}
+/** An unset config value is a missing key here and an explicit null as stored, so neither is compared. */
+function withoutUnset(config: Record<string, unknown>): Record<string, unknown> {
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== null && value !== undefined))
+}
+
/** Whether the form asserts something other than what the stored check already asserts. */
function assertionChanged(definition: CheckDefinitionPayload, check: DataQualityCheckApi): boolean {
return (
definition.check_type !== check.check_type ||
definition.column_name !== (check.column_name ?? '') ||
- !objectsEqual(definition.config, check.config ?? {})
+ !objectsEqual(withoutUnset(definition.config ?? {}), withoutUnset(check.config ?? {}))
)
}
@@ -199,7 +212,16 @@ export function checkToForm(check: DataQualityCheckApi): CheckFormValues {
rowCountMax: (config.max as number) ?? null,
maxAgeMinutes: (config.max_age_minutes as number) ?? null,
customSql: (config.query as string) ?? '',
+ lookbackHours: (config.lookback_hours as number) ?? null,
+ toLookbackHours: (config.to_lookback_hours as number) ?? null,
+ }
+}
+
+function lookbackHoursError(hours: number | null): string | undefined {
+ if (!isWindow(hours)) {
+ return undefined
}
+ return Number.isInteger(hours) && hours >= 1 ? undefined : 'Set a whole number of hours, at least one.'
}
/** Which form field a config-level server error belongs beside, per check type. */
@@ -263,10 +285,6 @@ function generalErrorMessage(error: unknown): string {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataQualityCheckEditorLogicValues {
- dataWarehouseTables: DatabaseSchemaDataWarehouseTable[] // databaseTableListLogic
- databaseLoadError: string | null // databaseTableListLogic
- databaseLoading: boolean // databaseTableListLogic
- views: DatabaseSchemaViewTable[] // databaseTableListLogic
availableColumns: string[]
availableOutputSchema: DataQualityOutputColumnApi[]
checkForm: CheckFormValues
@@ -278,6 +296,9 @@ export interface dataQualityCheckEditorLogicValues {
checkFormTouched: boolean
checkFormTouches: Record<string, boolean>
checkFormValidationErrors: DeepPartialMap<CheckFormValues, ValidationErrorType>
+ checkSubjects: DataQualitySubjectApi[]
+ checkSubjectsError: string | null
+ checkSubjectsLoading: boolean
checkTypeByName: {
[k: string]: DataQualityCheckTypeApi
}
@@ -301,41 +322,41 @@ export interface dataQualityCheckEditorLogicValues {
metricOutputSchema: DataQualityOutputSchemaApi | null
metricOutputSchemaError: string | null
metricOutputSchemaLoading: boolean
- metricSubjects: DataQualityMetricSubjectApi[]
- metricSubjectsError: string | null
- metricSubjectsLoading: boolean
- needsWarehouseCatalog: boolean
+ needsSubjectCatalog: boolean
openedWithoutSubject: boolean
relationshipSubjects: RelationshipSubject[]
+ relationshipTargetTimeColumn: string | null
requiresColumn: boolean
selectableSubjects: SelectableSubject[]
serverError: string | null
showCheckFormErrors: boolean
subject: DataQualitySubjectRef | null
+ subjectCatalogRequested: boolean
subjectColumns: string[]
subjectOutputSchema: DataQualityOutputColumnApi[]
- warehouseCatalogRequested: boolean
+ subjectTimeColumn: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataQualityCheckEditorLogicActions {
- ensureAllTableFields: () => {
- value: true
- } // databaseTableListLogic
- loadDatabase: (
- args_0?:
- | {
- force?: boolean
- shallow?: boolean
- }
- | undefined
- ) => {
- force?: boolean
- shallow?: boolean
- } // databaseTableListLogic
closeEditor: () => {
value: true
}
+ loadCheckSubjects: () => any
+ loadCheckSubjectsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadCheckSubjectsSuccess: (
+ checkSubjects: DataQualitySubjectApi[],
+ payload?: any
+ ) => {
+ checkSubjects: DataQualitySubjectApi[]
+ payload?: any
+ }
loadCheckTypes: () => {
value: true
}
@@ -372,24 +393,6 @@ export interface dataQualityCheckEditorLogicActions {
metricOutputSchema: DataQualityOutputSchemaApi | null
payload?: any
}
- loadMetricSubjects: () => any
- loadMetricSubjectsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadMetricSubjectsSuccess: (
- metricSubjects: DataQualityMetricSubjectApi[],
- payload?: any
- ) => {
- metricSubjects: DataQualityMetricSubjectApi[]
- payload?: any
- }
- loadWarehouseCatalog: () => {
- value: true
- }
openEditor: (
check: DataQualityCheckApi | null,
subject: DataQualitySubjectRef | null,
@@ -476,14 +479,12 @@ export interface dataQualityCheckEditorLogicMeta {
checkTypeByName: (checkTypes: DataQualityCheckTypeApi[]) => {
[k: string]: DataQualityCheckTypeApi
}
- relationshipSubjects: (
- views: DatabaseSchemaViewTable[],
- dataWarehouseTables: DatabaseSchemaDataWarehouseTable[]
- ) => RelationshipSubject[]
- selectableSubjects: (
- relationshipSubjects: RelationshipSubject[],
- metricSubjects: DataQualityMetricSubjectApi[]
- ) => SelectableSubject[]
+ relationshipSubjects: (checkSubjects: DataQualitySubjectApi[]) => RelationshipSubject[]
+ selectableSubjects: (checkSubjects: DataQualitySubjectApi[]) => SelectableSubject[]
+ subjectTimeColumn: (
+ subject: DataQualitySubjectRef | null,
+ checkSubjects: DataQualitySubjectApi[]
+ ) => string | null
availableOutputSchema: (
subjectColumns: string[],
subjectOutputSchema: DataQualityOutputColumnApi[],
@@ -495,13 +496,17 @@ export interface dataQualityCheckEditorLogicMeta {
customSqlSourceQuery: (checkForm: CheckFormValues) => HogQLQuery
customSqlPreviewStale: (customSqlPreview: CustomSqlPreview | null, checkForm: CheckFormValues) => boolean
customSqlPreviewVerdict: (customSqlPreview: CustomSqlPreview | null) => 'fail' | 'pass' | null
+ relationshipTargetTimeColumn: (
+ checkForm: CheckFormValues,
+ relationshipSubjects: RelationshipSubject[]
+ ) => string | null
requiresColumn: (
checkForm: CheckFormValues,
checkTypeByName: {
[k: string]: DataQualityCheckTypeApi
}
) => boolean
- needsWarehouseCatalog: (
+ needsSubjectCatalog: (
checkForm: CheckFormValues,
requiresColumn: boolean,
subjectColumns: string[],
@@ -528,10 +533,6 @@ 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', 'ensureAllTableFields']],
- values: [databaseTableListLogic, ['views', 'dataWarehouseTables', 'databaseLoading', 'databaseLoadError']],
- })),
actions({
loadCheckTypes: true,
openEditor: (
@@ -551,13 +552,12 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
setServerError: (serverError: string | null) => ({ serverError }),
setCustomSqlEditorError: (error: string | null) => ({ error }),
setCustomSqlValidationLoading: (loading: boolean) => ({ loading }),
- loadWarehouseCatalog: true,
}),
loaders(({ values }) => ({
- metricSubjects: [
- [] as DataQualityMetricSubjectApi[],
+ checkSubjects: [
+ [] as DataQualitySubjectApi[],
{
- loadMetricSubjects: async () => checksApi.metricSubjects(),
+ loadCheckSubjects: async () => checksApi.subjects(),
},
],
metricOutputSchema: [
@@ -675,10 +675,12 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
},
],
// Keep the full catalog available across modal opens, while avoiding refetches on type switches.
- warehouseCatalogRequested: [
+ subjectCatalogRequested: [
false,
{
- loadWarehouseCatalog: () => true,
+ loadCheckSubjects: () => true,
+ loadCheckSubjectsFailure: () => false,
+ closeEditor: () => false,
},
],
checkTypes: [
@@ -695,12 +697,12 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
setSubject: () => null,
},
],
- metricSubjectsError: [
+ checkSubjectsError: [
null as string | null,
{
- loadMetricSubjects: () => null,
- loadMetricSubjectsSuccess: () => null,
- loadMetricSubjectsFailure: (_, { error, errorObject }) => errorObject?.detail ?? error,
+ loadCheckSubjects: () => null,
+ loadCheckSubjectsSuccess: () => null,
+ loadCheckSubjectsFailure: (_, { error, errorObject }) => errorObject?.detail ?? error,
openEditor: () => null,
},
],
@@ -783,44 +785,36 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
Object.fromEntries(checkTypes.map((checkType) => [checkType.check_type, checkType])),
],
relationshipSubjects: [
- (s) => [s.views, s.dataWarehouseTables],
- (
- views: DatabaseSchemaViewTable[],
- dataWarehouseTables: DatabaseSchemaDataWarehouseTable[]
- ): 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)
+ (s) => [s.checkSubjects],
+ (checkSubjects: DataQualitySubjectApi[]): RelationshipSubject[] =>
+ checkSubjects
+ .filter((subject) => subject.subject_type !== SubjectTypeEnumApi.Metric)
.map((subject) => ({
id: subject.id,
name: subject.name,
- type: subject.type,
- fields: Object.keys(subject.fields ?? {}),
- outputSchema: Object.entries(subject.fields ?? {}).map(
- ([name, field]: [string, DatabaseSchemaField]) => ({
- name,
- type: field.type ?? null,
- })
- ),
+ type: subject.subject_type,
+ fields: Object.keys(subject.columns ?? {}),
+ outputSchema: Object.entries(subject.columns ?? {}).map(([name, type]) => ({ name, type })),
+ timeColumn: subject.time_column || null,
})),
],
selectableSubjects: [
- (s) => [s.relationshipSubjects, s.metricSubjects],
- (
- relationshipSubjects: RelationshipSubject[],
- metricSubjects: DataQualityMetricSubjectApi[]
- ): SelectableSubject[] => [
- ...relationshipSubjects.map(({ id, name, type }) => ({ id, name, type })),
- ...metricSubjects.map((metric) => ({
- id: metric.id,
- name: metric.display_name || metric.name,
- type: SubjectTypeEnumApi.Metric,
- })),
- ],
+ (s) => [s.checkSubjects],
+ (checkSubjects: DataQualitySubjectApi[]): SelectableSubject[] =>
+ checkSubjects
+ .filter((subject) => subject.editable)
+ .map((subject) => ({
+ id: subject.id,
+ name: subject.display_name || subject.name,
+ type: subject.subject_type,
+ })),
+ ],
+ subjectTimeColumn: [
+ (s) => [s.subject, s.checkSubjects],
+ (subject: DataQualitySubjectRef | null, checkSubjects: DataQualitySubjectApi[]): string | null =>
+ checkSubjects.find(
+ (candidate) => candidate.id === subject?.subjectId && candidate.subject_type === subject.subjectType
+ )?.time_column || null,
],
availableOutputSchema: [
(s) => [s.subjectColumns, s.subjectOutputSchema, s.subject, s.relationshipSubjects, s.metricOutputSchema],
@@ -901,6 +895,16 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
form.checkType === CheckTypeEnumApi.Freshness && (form.maxAgeMinutes ?? 0) < 1
? 'Set an age of at least one minute.'
: undefined,
+ // Gated on what the payload builders actually send, so nothing reaches the
+ // request unvalidated and no message lands on a field the form drops.
+ lookbackHours:
+ form.checkType !== CheckTypeEnumApi.CustomSql
+ ? lookbackHoursError(form.lookbackHours)
+ : undefined,
+ toLookbackHours:
+ form.checkType === CheckTypeEnumApi.Relationships
+ ? lookbackHoursError(form.toLookbackHours)
+ : undefined,
customSql:
form.checkType === CheckTypeEnumApi.CustomSql
? !form.customSql.trim()
@@ -970,12 +974,17 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
(customSqlPreview: CustomSqlPreview | null) =>
customSqlPreview ? (customSqlPreview.rowCount === 0 ? 'pass' : 'fail') : null,
],
+ relationshipTargetTimeColumn: [
+ (s) => [s.checkForm, s.relationshipSubjects],
+ (checkForm: CheckFormValues, relationshipSubjects: RelationshipSubject[]): string | null =>
+ relationshipSubjects.find((candidate) => candidate.id === checkForm.toSubjectUuid)?.timeColumn ?? null,
+ ],
requiresColumn: [
(s) => [s.checkForm, s.checkTypeByName],
(checkForm: CheckFormValues, checkTypeByName: Record<string, DataQualityCheckTypeApi>) =>
!!checkTypeByName[checkForm.checkType]?.requires_column,
],
- needsWarehouseCatalog: [
+ needsSubjectCatalog: [
(s) => [s.checkForm, s.requiresColumn, s.subjectColumns, s.subject],
(
checkForm: CheckFormValues,
@@ -983,19 +992,22 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
subjectColumns: string[],
subject: DataQualitySubjectRef | null
) =>
- // 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.
+ // Relationships needs every subject to point at. A PostHog table needs the
+ // catalog for its time column, which no surface supplies and which the lookback
+ // window reads. Anything else only needs the catalog when the surface that
+ // opened the editor could not supply the columns.
subject === null ||
checkForm.checkType === CheckTypeEnumApi.Relationships ||
+ subject.subjectType === SubjectTypeEnumApi.PosthogTable ||
(requiresColumn && !subjectColumns.length),
],
}),
listeners(({ props, values, actions }) => {
- const ensureWarehouseCatalog = (): void => {
- if (values.warehouseCatalogRequested || !values.needsWarehouseCatalog) {
+ const ensureSubjectCatalog = (): void => {
+ if (values.subjectCatalogRequested || !values.needsSubjectCatalog) {
return
}
- actions.loadWarehouseCatalog()
+ actions.loadCheckSubjects()
}
return {
@@ -1015,10 +1027,7 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
if (subject?.subjectType === SubjectTypeEnumApi.Metric) {
actions.loadMetricOutputSchema(undefined)
}
- if (subject === null) {
- actions.loadMetricSubjects()
- }
- ensureWarehouseCatalog()
+ ensureSubjectCatalog()
},
setSubject: ({ subject }) => {
actions.resetCheckForm(
@@ -1037,14 +1046,17 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(
actions.setServerError(null)
actions.setCheckFormManualErrors({})
},
+ // Opening the editor clears the check-type catalog, so the column requirement is
+ // unknown while the first request runs. Ask again once it arrives, or a check that
+ // needs a column has no column to pick until the person edits the form.
+ loadCheckTypesSuccess: () => {
+ ensureSubjectCatalog()
+ },
setCheckFormValues: () => {
if (values.isOpen) {
- ensureWarehouseCatalog()
+ ensureSubjectCatalog()
}
},
- loadWarehouseCatalog: () => {
- actions.ensureAllTableFields()
- },
requestClose: () => {
if (!values.checkFormChanged) {
actions.closeEditor()
diff --git a/products/data_quality/frontend/dataQualityScheduleLogic.test.ts b/products/data_quality/frontend/dataQualityScheduleLogic.test.ts
index 5a13d0b90365..de4b3c71db93 100644
--- a/products/data_quality/frontend/dataQualityScheduleLogic.test.ts
+++ b/products/data_quality/frontend/dataQualityScheduleLogic.test.ts
@@ -6,16 +6,18 @@ import { expectLogic } from '~/test/keaTestUtils'
import { dataQualityScheduleLogic } from './dataQualityScheduleLogic'
import { dataQualityChecksScheduleRetrieve, dataQualityChecksSchedulePartialUpdate } from './generated/api'
+import { DataQualityScheduleIntervalEnumApi } from './generated/api.schemas'
+import type { DataQualityCheckScheduleApi } from './generated/api.schemas'
jest.mock('./generated/api', () => ({
dataQualityChecksScheduleRetrieve: jest.fn(),
dataQualityChecksSchedulePartialUpdate: jest.fn(),
}))
-const SCHEDULE = {
+const SCHEDULE: DataQualityCheckScheduleApi = {
id: 'schedule-1',
enabled: true,
- interval: '24hour',
+ interval: DataQualityScheduleIntervalEnumApi['24hour'],
next_run_at: '2026-09-05T00:00:00Z',
last_run_at: null,
last_suite_run: null,
@@ -124,6 +126,63 @@ describe('dataQualityScheduleLogic', () => {
expect(logic.values.schedule?.enabled).toBe(false)
})
+ it('starts from a schedule it was handed without fetching or polling', async () => {
+ const setIntervalSpy = jest.spyOn(window, 'setInterval')
+ logic = dataQualityScheduleLogic.build({
+ subjectType: 'metric',
+ subjectId: 'metric-1',
+ initialSchedule: SCHEDULE,
+ poll: false,
+ })
+
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.schedule).toEqual(SCHEDULE)
+ expect(dataQualityChecksScheduleRetrieve).not.toHaveBeenCalled()
+ expect(setIntervalSpy).not.toHaveBeenCalled()
+ setIntervalSpy.mockRestore()
+ })
+
+ it('waits while the surface loads the listing and fetches its own only if none arrives', async () => {
+ logic = dataQualityScheduleLogic.build({
+ subjectType: 'metric',
+ subjectId: 'metric-1',
+ initialSchedule: null,
+ poll: false,
+ })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(dataQualityChecksScheduleRetrieve).not.toHaveBeenCalled()
+
+ dataQualityScheduleLogic.build({
+ subjectType: 'metric',
+ subjectId: 'metric-1',
+ initialSchedule: SCHEDULE,
+ poll: false,
+ })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.schedule).toEqual(SCHEDULE)
+ expect(dataQualityChecksScheduleRetrieve).not.toHaveBeenCalled()
+
+ const orphan = dataQualityScheduleLogic.build({
+ subjectType: 'metric',
+ subjectId: 'metric-2',
+ initialSchedule: null,
+ poll: false,
+ })
+ orphan.mount()
+ dataQualityScheduleLogic.build({
+ subjectType: 'metric',
+ subjectId: 'metric-2',
+ initialSchedule: undefined,
+ poll: false,
+ })
+ await expectLogic(orphan).toFinishAllListeners()
+ expect(dataQualityChecksScheduleRetrieve).toHaveBeenCalledTimes(1)
+ orphan.unmount()
+ })
+
it('refreshes the schedule while the frequency controls are open', async () => {
let refreshSchedule: (() => void) | undefined
const setIntervalSpy = jest.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler) => {
diff --git a/products/data_quality/frontend/dataQualityScheduleLogic.ts b/products/data_quality/frontend/dataQualityScheduleLogic.ts
index 00b0d36b7fe5..ea702f2ee7bb 100644
--- a/products/data_quality/frontend/dataQualityScheduleLogic.ts
+++ b/products/data_quality/frontend/dataQualityScheduleLogic.ts
@@ -1,4 +1,16 @@
-import { LogicWrapper, MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+} from 'kea'
import { loaders } from 'kea-loaders'
import { ApiError } from 'lib/api'
@@ -8,7 +20,14 @@ import type { DataQualityCheckScheduleApi, PatchedDataQualityCheckScheduleUpdate
const SCHEDULE_REFRESH_INTERVAL_MS = 30_000
-export type DataQualityScheduleLogicProps = DataQualitySubjectRef
+export interface DataQualityScheduleLogicProps extends DataQualitySubjectRef {
+ initialSchedule?: DataQualityCheckScheduleApi | null
+ poll?: boolean
+}
+
+function surfaceStillLoading(initialSchedule: DataQualityCheckScheduleApi | null | undefined): boolean {
+ return initialSchedule === null
+}
export interface DataQualityScheduleError {
message: string
@@ -144,8 +163,24 @@ export const dataQualityScheduleLogic: LogicWrapper<dataQualityScheduleLogicType
}
},
})),
- afterMount(({ actions, cache }) => {
- actions.loadSchedule()
+ propsChanged(({ actions, props, values }, oldProps) => {
+ if (props.initialSchedule && props.initialSchedule !== oldProps.initialSchedule && !values.scheduleLoading) {
+ actions.refreshScheduleSuccess(props.initialSchedule)
+ return
+ }
+ if (surfaceStillLoading(oldProps.initialSchedule) && props.initialSchedule === undefined && !values.schedule) {
+ actions.loadSchedule()
+ }
+ }),
+ afterMount(({ actions, props, cache }) => {
+ if (props.initialSchedule) {
+ actions.refreshScheduleSuccess(props.initialSchedule)
+ } else if (!surfaceStillLoading(props.initialSchedule)) {
+ actions.loadSchedule()
+ }
+ if (props.poll === false) {
+ return
+ }
cache.disposables.add(() => {
const refreshTimer = window.setInterval(actions.refreshSchedule, SCHEDULE_REFRESH_INTERVAL_MS)
return () => window.clearInterval(refreshTimer)
diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.ts
index 4ddc51df8e3e..ae6ae539eb9c 100644
--- a/products/data_quality/frontend/generated/api.schemas.ts
+++ b/products/data_quality/frontend/generated/api.schemas.ts
@@ -232,7 +232,7 @@ export interface DataQualityOverviewCheckApi {
/** @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.
+ * Data modeling node of the view or PostHog table this check audits, or null when it is on no DAG or the subject is a warehouse table.
* @nullable
*/
readonly subject_node_id: string | null
@@ -811,6 +811,48 @@ export interface PatchedDataQualityCheckScheduleUpdateApi {
enabled?: boolean
}
+/**
+ * One subject's schedule, in the project-wide listing.
+ */
+export interface DataQualitySubjectScheduleApi {
+ /** Schedule identifier. */
+ readonly id: string
+ /** How often the checks run.
+ *
+ * * `1hour` - 1hour
+ * * `6hour` - 6hour
+ * * `12hour` - 12hour
+ * * `24hour` - 24hour
+ * * `7day` - 7day */
+ readonly interval: DataQualityScheduleIntervalEnumApi
+ /** Whether the schedule runs automatically. */
+ readonly enabled: boolean
+ /**
+ * Next scheduled execution time, if enabled.
+ * @nullable
+ */
+ readonly next_run_at: string | null
+ /**
+ * Most recent visible scheduled suite execution time.
+ * @nullable
+ */
+ readonly last_run_at: string | null
+ /**
+ * Most recent visible scheduled suite.
+ * @nullable
+ */
+ readonly last_suite_run: string | null
+ /** 'metric' or 'posthog_table'.
+ *
+ * * `table` - table
+ * * `view` - view
+ * * `metric` - metric
+ * * `posthog_table` - posthog_table */
+ readonly subject_type: SubjectTypeEnumApi
+ /** Id of the metric or PostHog table. */
+ readonly subject_uuid: string
+}
+
/**
* Column name to ClickHouse type. Empty for a metric, and for a view that has not run yet.
*/
@@ -833,6 +875,8 @@ export interface DataQualitySubjectApi {
name: string
/** Label shown in the data catalog. Blank for tables and views. */
display_name: string
+ /** Column a lookback window bounds, or blank for a subject that has none. */
+ time_column: string
/** Column name to ClickHouse type. Empty for a metric, and for a view that has not run yet. */
columns: DataQualitySubjectApiColumns
/** Whether the caller may author a check on this subject. A subject that is only readable can still be the target of a relationships check. */
diff --git a/products/data_quality/frontend/generated/api.ts b/products/data_quality/frontend/generated/api.ts
index 88f230126f5f..33f64516dcdb 100644
--- a/products/data_quality/frontend/generated/api.ts
+++ b/products/data_quality/frontend/generated/api.ts
@@ -25,6 +25,7 @@ import type {
DataQualityRunsListParams,
DataQualitySubjectApi,
DataQualitySubjectHealthApi,
+ DataQualitySubjectScheduleApi,
DataQualitySuiteRunApi,
PaginatedDataQualityOverviewCheckListApi,
PaginatedDataQualitySuiteRunListApi,
@@ -375,6 +376,23 @@ export const dataQualityChecksSchedulePartialUpdate = async (
})
}
+export const getDataQualityChecksSchedulesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_quality_checks/schedules/`
+}
+
+/**
+ * The schedule of every subject in the project whose checks run on one, for the checks the caller may read. One request for the overview instead of one per subject.
+ */
+export const dataQualityChecksSchedulesList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<DataQualitySubjectScheduleApi[]> => {
+ return apiMutator<DataQualitySubjectScheduleApi[]>(getDataQualityChecksSchedulesListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getDataQualityChecksSubjectsListUrl = (projectId: string) => {
return `/api/projects/${projectId}/data_quality_checks/subjects/`
}
diff --git a/products/data_quality/frontend/overview/DataQualityOverview.test.tsx b/products/data_quality/frontend/overview/DataQualityOverview.test.tsx
index 0827b151eb64..2cc0296398fb 100644
--- a/products/data_quality/frontend/overview/DataQualityOverview.test.tsx
+++ b/products/data_quality/frontend/overview/DataQualityOverview.test.tsx
@@ -1,14 +1,13 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
-
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { initKeaTests } from '~/test/init'
import {
dataQualityChecksHealthList,
dataQualityChecksList,
- dataQualityChecksMetricSubjectsList,
+ dataQualityChecksScheduleRetrieve,
+ dataQualityChecksSubjectsList,
dataQualityRunsCreate,
dataQualityRunsRetrieve,
dataQualityChecksCheckTypesList,
@@ -19,29 +18,6 @@ import type { DataQualityOverviewCheckApi } from 'products/data_quality/frontend
import { DataQualityOverview } from './DataQualityOverview'
import { subjectDisclosureId } from './dataQualityOverviewLogic'
-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,
- ensureAllTableFields: true,
- setDatabaseLoadError: (error: string | null) => ({ error }),
- }),
- reducers({
- views: [[]],
- dataWarehouseTables: [[]],
- databaseLoading: [false],
- databaseLoadError: [
- null,
- { setDatabaseLoadError: (_: string | null, { error }: { error: string | null }) => error },
- ],
- }),
- ]),
- }
-})
-
jest.mock('lib/api', () => ({
__esModule: true,
default: {},
@@ -56,7 +32,7 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
jest.mock('products/data_quality/frontend/generated/api', () => ({
dataQualityChecksList: jest.fn(),
dataQualityChecksHealthList: jest.fn(),
- dataQualityChecksMetricSubjectsList: jest.fn(),
+
dataQualityRunsCreate: jest.fn(),
dataQualityRunsRetrieve: jest.fn(),
dataQualityChecksRunsList: jest.fn(),
@@ -64,6 +40,9 @@ jest.mock('products/data_quality/frontend/generated/api', () => ({
dataQualityChecksCheckTypesList: jest.fn(),
dataQualityChecksCreate: jest.fn(),
dataQualityChecksPartialUpdate: jest.fn(),
+ dataQualityChecksScheduleRetrieve: jest.fn(),
+ dataQualityChecksSchedulePartialUpdate: jest.fn(),
+ dataQualityChecksSchedulesList: jest.fn(() => Promise.resolve([])),
dataQualityChecksSubjectsList: jest.fn(),
}))
@@ -129,7 +108,7 @@ describe('DataQualityOverview', () => {
failingHealth('orders'),
failingHealth('customers'),
])
- ;(dataQualityChecksMetricSubjectsList as jest.Mock).mockResolvedValue([])
+ ;(dataQualityChecksSubjectsList as jest.Mock).mockResolvedValue([])
;(dataQualityRunsCreate as jest.Mock).mockResolvedValue({
id: 'suite-1',
status: 'running',
@@ -219,6 +198,33 @@ describe('DataQualityOverview', () => {
expect(screen.getAllByText('orders').length).toBeGreaterThan(0)
})
+ it('groups a PostHog table under its own tag, with a schedule and a link to its node', async () => {
+ const check = buildCheck('check-events', 'events', {
+ subject_type: 'posthog_table',
+ subject_uuid: 'uuid-events',
+ subject_node_id: 'node-events',
+ })
+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({ results: [check] })
+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([failingHealth('events')])
+ ;(dataQualityChecksScheduleRetrieve as jest.Mock).mockResolvedValue({
+ id: 'schedule-1',
+ enabled: true,
+ interval: '24hour',
+ next_run_at: null,
+ last_run_at: null,
+ last_suite_run: null,
+ })
+ render(<DataQualityOverview />)
+ await waitFor(() => expect(runSubjectButtons()).toHaveLength(1))
+
+ expect(screen.getByText('PostHog')).toBeTruthy()
+ expect(document.querySelector('a[href*="/models/node-events"]')).not.toBeNull()
+
+ fireEvent.click(queryAll('[data-attr="data-quality-subject-disclosure"]')[0])
+
+ expect(await screen.findByText('Run automatically')).toBeTruthy()
+ })
+
it('shows only the creation path from the illustrated first-use state', async () => {
;(dataQualityChecksList as jest.Mock).mockResolvedValue({ results: [] })
;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([])
@@ -265,15 +271,13 @@ describe('DataQualityOverview', () => {
it('shows a retry when the subject picker catalog cannot load', async () => {
;(dataQualityChecksList as jest.Mock).mockResolvedValue({ results: [] })
;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([])
+ ;(dataQualityChecksSubjectsList as jest.Mock).mockRejectedValue(new Error('down'))
render(<DataQualityOverview />)
await screen.findByText('No checks yet')
- fireEvent.click(document.querySelector('[data-attr="data-quality-overview-first-check"]')!)
- ;(
- databaseTableListLogic.actions as unknown as { setDatabaseLoadError: (error: string) => void }
- ).setDatabaseLoadError('down')
+ fireEvent.click(document.querySelector('[data-attr="data-quality-overview-first-check"]')!)
- expect(await screen.findByText("Couldn't load your tables and views.")).toBeTruthy()
+ expect(await screen.findByText("Couldn't load what you can check.")).toBeTruthy()
expect(screen.getByText('Retry')).toBeTruthy()
})
diff --git a/products/data_quality/frontend/overview/DataQualityOverview.tsx b/products/data_quality/frontend/overview/DataQualityOverview.tsx
index a5c2f9141eb4..55bb65e56ca7 100644
--- a/products/data_quality/frontend/overview/DataQualityOverview.tsx
+++ b/products/data_quality/frontend/overview/DataQualityOverview.tsx
@@ -29,7 +29,9 @@ import {
} from '../checksConstants'
import { CheckStatusCell } from '../CheckStatusCell'
import { DataQualityCheckEditorLogicProps, dataQualityCheckEditorLogic } from '../dataQualityCheckEditorLogic'
+import { DataQualitySchedule } from '../DataQualitySchedule'
import type { DataQualityOverviewCheckApi } from '../generated/api.schemas'
+import { SubjectTypeEnumApi } from '../generated/api.schemas'
import { DataQualityEmptyState } from './DataQualityEmptyState'
import {
NEW_CHECK_ACTION_ID,
@@ -237,9 +239,20 @@ export function DataQualityOverview(): JSX.Element {
)
}
+const SCHEDULED_SUBJECT_TYPES: string[] = [SubjectTypeEnumApi.Metric, SubjectTypeEnumApi.PosthogTable]
+
function SubjectSection({ group }: { group: SubjectGroup }): JSX.Element {
- const { expandedSubjectKeys, startingRun, isRunning, runningSubjectKey, runTarget, runError, pollTimedOut } =
- useValues(dataQualityOverviewLogic)
+ const {
+ expandedSubjectKeys,
+ startingRun,
+ isRunning,
+ runningSubjectKey,
+ runTarget,
+ runError,
+ pollTimedOut,
+ scheduleBySubjectKey,
+ subjectSchedulesLoading,
+ } = useValues(dataQualityOverviewLogic)
const { toggleSubjectExpanded, runChecks, loadOverview } = useActions(dataQualityOverviewLogic)
const subjectType = SUBJECT_TYPE_TAGS[group.subjectType]
@@ -335,6 +348,19 @@ function SubjectSection({ group }: { group: SubjectGroup }): JSX.Element {
check's controls in the tab order of a panel nobody can see. */}
{expanded && (
<div id={regionId} className="overflow-x-auto">
+ {SCHEDULED_SUBJECT_TYPES.includes(group.subjectType) && group.subjectUuid ? (
+ <div className="px-2 pt-2">
+ <DataQualitySchedule
+ subjectType={group.subjectType}
+ subjectId={group.subjectUuid}
+ initialSchedule={
+ scheduleBySubjectKey[group.subjectKey] ??
+ (subjectSchedulesLoading ? null : undefined)
+ }
+ poll={false}
+ />
+ </div>
+ ) : null}
<SubjectChecks group={group} />
</div>
)}
diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts
index 408c566105b1..93d82dff8a06 100644
--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts
+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts
@@ -11,6 +11,7 @@ import {
dataQualityChecksHealthList,
dataQualityChecksList,
dataQualityChecksRunsList,
+ dataQualityChecksSchedulesList,
dataQualityRunsCreate,
dataQualityRunsRetrieve,
} from 'products/data_quality/frontend/generated/api'
@@ -44,6 +45,7 @@ jest.mock('products/data_quality/frontend/generated/api', () => ({
dataQualityChecksHealthList: jest.fn(),
dataQualityChecksList: jest.fn(),
dataQualityChecksRunsList: jest.fn(),
+ dataQualityChecksSchedulesList: jest.fn(),
dataQualityRunsCreate: jest.fn(),
dataQualityRunsRetrieve: jest.fn(),
}))
@@ -113,6 +115,7 @@ describe('dataQualityOverviewLogic', () => {
],
})
;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue(HEALTH)
+ ;(dataQualityChecksSchedulesList as jest.Mock).mockResolvedValue([])
})
afterEach(() => {
@@ -121,6 +124,33 @@ describe('dataQualityOverviewLogic', () => {
logic?.unmount()
})
+ it('loads every schedule with the overview and keys it by subject', async () => {
+ ;(dataQualityChecksSchedulesList as jest.Mock).mockResolvedValue([
+ {
+ id: 'schedule-1',
+ subject_type: 'posthog_table',
+ subject_uuid: 'events-1',
+ enabled: true,
+ interval: '24hour',
+ next_run_at: null,
+ last_run_at: null,
+ last_suite_run: null,
+ },
+ ])
+ await mountLogic()
+
+ expect(dataQualityChecksSchedulesList).toHaveBeenCalledTimes(1)
+ expect(logic.values.scheduleBySubjectKey['posthog_table:events-1']).toMatchObject({ id: 'schedule-1' })
+ })
+
+ it('keeps the overview when the schedule listing fails', async () => {
+ ;(dataQualityChecksSchedulesList as jest.Mock).mockRejectedValue(new Error('down'))
+ await mountLogic()
+
+ expect(logic.values.subjectGroups.length).toBeGreaterThan(0)
+ expect(logic.values.scheduleBySubjectKey).toEqual({})
+ })
+
it('keys subjects by type and uuid together, since the two kinds can collide', async () => {
;(dataQualityChecksList as jest.Mock).mockResolvedValue({
results: [
@@ -498,6 +528,12 @@ describe('dataQualityOverviewLogic', () => {
it.each<[string, Partial<DataQualityOverviewCheckApi>, string | null]>([
['a view on a DAG node', { subject_type: 'view', subject_node_id: 'node-1' }, '/models/node-1/tests'],
['a view on no DAG', { subject_type: 'view', subject_node_id: null }, null],
+ [
+ 'a PostHog table on a DAG node',
+ { subject_type: 'posthog_table', subject_node_id: 'node-2' },
+ '/models/node-2',
+ ],
+ ['a PostHog table no view reads', { subject_type: 'posthog_table', subject_node_id: null }, null],
[
'a metric',
{ subject_type: 'metric', subject_metric_name: 'weekly_signups' },
diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts
index 97252f2e2c7e..b0e2935a9e22 100644
--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts
+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts
@@ -16,8 +16,10 @@ import type {
DataQualityCheckRunApi,
DataQualityOverviewCheckApi,
DataQualitySubjectHealthApi,
+ DataQualitySubjectScheduleApi,
DataQualitySuiteRunApi,
} from 'products/data_quality/frontend/generated/api.schemas'
+import { SubjectTypeEnumApi } from 'products/data_quality/frontend/generated/api.schemas'
import { openFailingRowsInSqlEditor } from 'products/data_quality/frontend/openFailingRows'
import {
isTerminalSuiteRun,
@@ -50,7 +52,7 @@ export type OverviewRunTarget = { kind: 'all' } | { kind: 'subject'; subjectKey:
export interface SubjectGroup {
/** Composite: a table and a view can hold the same uuid, and do collide in practice. */
subjectKey: string
- subjectType: string
+ subjectType: SubjectTypeEnumApi
subjectUuid: string
subjectName: string
detailUrl: string | null
@@ -73,6 +75,9 @@ export function subjectKeyOf(subjectType: string, subjectUuid: string | null | u
/** 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 === 'posthog_table') {
+ return check.subject_node_id ? urls.nodeDetail(check.subject_node_id) : null
+ }
if (check.subject_type === 'metric') {
// The catalog addresses a metric by name, so a row that came without one has no route.
return check.subject_metric_name ? urls.dataCatalogMetric(check.subject_metric_name, 'tests') : null
@@ -156,10 +161,13 @@ export interface dataQualityOverviewLogicValues {
runTarget: OverviewRunTarget | null
runningSubjectKey: string | null
runsLoadingByCheckId: Record<string, boolean>
+ scheduleBySubjectKey: Record<string, DataQualitySubjectScheduleApi>
snapshotLoaded: boolean
startingRun: boolean
subjectGroups: SubjectGroup[]
subjectHealth: DataQualitySubjectHealthApi[]
+ subjectSchedules: DataQualitySubjectScheduleApi[]
+ subjectSchedulesLoading: boolean
unhealthySubjectKeys: string[]
}
@@ -195,6 +203,21 @@ export interface dataQualityOverviewLogicActions {
}
payload?: any
}
+ loadSubjectSchedules: () => any
+ loadSubjectSchedulesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSubjectSchedulesSuccess: (
+ subjectSchedules: DataQualitySubjectScheduleApi[],
+ payload?: any
+ ) => {
+ subjectSchedules: DataQualitySubjectScheduleApi[]
+ payload?: any
+ }
openFailingRows: (check: DataQualityOverviewCheckApi) => {
check: DataQualityOverviewCheckApi
}
@@ -266,6 +289,9 @@ export interface dataQualityOverviewLogicMeta {
__keaTypeGenInternalSelectorTypes: {
checks: (overview: OverviewSnapshot | null) => DataQualityOverviewCheckApi[]
subjectHealth: (overview: OverviewSnapshot | null) => DataQualitySubjectHealthApi[]
+ scheduleBySubjectKey: (
+ subjectSchedules: DataQualitySubjectScheduleApi[]
+ ) => Record<string, DataQualitySubjectScheduleApi>
healthBySubjectKey: (subjectHealth: DataQualitySubjectHealthApi[]) => {
[k: string]: DataQualitySubjectHealthApi
}
@@ -343,6 +369,12 @@ export const dataQualityOverviewLogic = kea<dataQualityOverviewLogicType>([
},
},
],
+ subjectSchedules: [
+ [] as DataQualitySubjectScheduleApi[],
+ {
+ loadSubjectSchedules: async () => checksApi.schedules(),
+ },
+ ],
})),
reducers({
filters: [
@@ -446,6 +478,16 @@ export const dataQualityOverviewLogic = kea<dataQualityOverviewLogicType>([
selectors({
checks: [(s) => [s.overview], (overview: OverviewSnapshot | null) => overview?.checks ?? []],
subjectHealth: [(s) => [s.overview], (overview: OverviewSnapshot | null) => overview?.health ?? []],
+ scheduleBySubjectKey: [
+ (s) => [s.subjectSchedules],
+ (subjectSchedules: DataQualitySubjectScheduleApi[]): Record<string, DataQualitySubjectScheduleApi> =>
+ Object.fromEntries(
+ subjectSchedules.map((schedule) => [
+ subjectKeyOf(schedule.subject_type, schedule.subject_uuid),
+ schedule,
+ ])
+ ),
+ ],
healthBySubjectKey: [
(s) => [s.subjectHealth],
(subjectHealth: DataQualitySubjectHealthApi[]) =>
@@ -587,6 +629,9 @@ export const dataQualityOverviewLogic = kea<dataQualityOverviewLogicType>([
setActiveSuiteRun: poll.setActiveSuiteRun,
scheduleSuiteRunPoll: poll.scheduleSuiteRunPoll,
pollActiveSuiteRun: poll.pollActiveSuiteRun,
+ loadOverview: () => {
+ actions.loadSubjectSchedules()
+ },
loadOverviewSuccess: () => {
if (!values.expansionInitialized) {
actions.setExpandedSubjects(values.unhealthySubjectKeys)
diff --git a/products/data_quality/mcp/tools.yaml b/products/data_quality/mcp/tools.yaml
index f8ae907de1a2..def040822f21 100644
--- a/products/data_quality/mcp/tools.yaml
+++ b/products/data_quality/mcp/tools.yaml
@@ -20,9 +20,10 @@ tools:
idempotent: true
title: Create a data quality check
description: |
- Add a dbt-test-style assertion to a warehouse table, a saved query (view or materialized view), or a data
- catalog metric. Name the subject with subject_type ('table', 'view' or 'metric') and subject_uuid, both from
- data-quality-subjects. A check passes when it finds zero failing rows.
+ Add a dbt-test-style assertion to a warehouse table, a saved query (view or materialized view), a data
+ catalog metric, or a PostHog table (events, persons, groups). Name the subject with subject_type
+ ('table', 'view', 'metric' or 'posthog_table') and subject_uuid, both from data-quality-subjects. A check
+ passes when it finds zero failing rows.
Query `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,
but a near-duplicate with different config is noise for whoever reviews the results.
@@ -31,18 +32,26 @@ tools:
- not_null, unique: no config; set column_name.
- accepted_values: {"values": ["paid", "refunded"]}; set column_name.
- relationships: {"to_subject_type": "table", "to_subject_uuid": "<uuid>", "to_column": "id"}; set
- column_name.
+ column_name. to_subject_type takes 'table', 'view' or 'posthog_table'. Add "to_lookback_hours" to look
+ for a match only among the referenced subject's recent rows, which only a target with a time column
+ accepts.
- row_count: {"min": 1} and/or {"max": 1000000}; no column_name.
- freshness: {"max_age_minutes": 60}; set column_name to a timestamp column.
- custom_sql: {"query": "select 1 from orders where total < 0"}; every row it returns is a failure.
+ Add "lookback_hours" to any config to check only the rows from the last N hours, by the subject's own time
+ column: timestamp on events, created_at on persons and groups. Optional, and only for a subject that has
+ one -- a warehouse table, a view and a metric do not. Without it the check reads the whole table, which on
+ events is expensive. custom_sql takes no lookback_hours; put the time filter in the query. Changing the
+ window creates a new check, so update the existing one to keep its history.
+
A metric supports custom_sql only, and takes no column_name. Its query must read the {metric} relation
exactly once and cannot use CTEs: {"query": "select * from {metric} where orders < 100"}. Call
data-quality-check-types with the subject_type to see which types that kind of subject supports.
Use severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but
- not acting on. A check on a table runs after each sync of it, a check on a view when the view refreshes, and
- a check on a metric on the metric's schedule.
+ not acting on. A check on a warehouse table runs after each sync of it, a check on a view when the view
+ refreshes, and a check on a metric or a PostHog table on that subject's schedule.
inject_body:
created_source: ai_generated
feature_flag: data-quality-checks
@@ -158,6 +167,9 @@ tools:
data-quality-checks-schedule-retrieve:
operation: data_quality_checks_schedule_retrieve
enabled: false
+ data-quality-checks-schedules-list:
+ operation: data_quality_checks_schedules_list
+ enabled: false
data-quality-checks-update:
operation: data_quality_checks_update
enabled: false
@@ -184,7 +196,8 @@ tools:
idempotent: true
title: List what a data quality check can be authored on
description: >
- Every table, view and metric in this project you can read, with each one's columns and whether you can put a
- check on it. Start here: a check names its subject by the subject_type and id this returns, and a
- relationships check can point at a subject you can only read.
+ Every table, view, metric and PostHog table in this project you can read, with each one's columns and
+ whether you can put a check on it. Start here: a check names its subject by the subject_type and id this
+ returns, and a relationships check can point at a subject you can only read. A subject whose time_column is
+ set can take a lookback_hours window.
feature_flag: data-quality-checks
diff --git a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md b/products/data_quality/skills/authoring-data-quality-checks/SKILL.md
index c8b9223f3a99..bb821e3566f2 100644
--- a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md
+++ b/products/data_quality/skills/authoring-data-quality-checks/SKILL.md
@@ -76,6 +76,29 @@ views and metrics you can read, then pass the `subject_type` and `id` it gives y
`editable` can carry a check; the others can still be the target of a relationships check. After that a check is
addressed by its own id: `-update`, `-delete`, `-run` and `-results` take no subject.
+## Checks on PostHog tables
+
+`events`, `persons` and `groups` take checks like any other subject: pass
+`subject_type: "posthog_table"` with the id `posthog:data-quality-subjects` gives you. Every check
+type works on them, and `relationships` can point at one as its target too.
+
+These tables are large, so consider `lookback_hours` before you author a check on one. It bounds
+the rows the check reads by the table's own time column: `timestamp` on `events`, and `created_at`
+on `persons` and `groups`, which is when each was first seen rather than when it last changed.
+Without it the check reads the whole table, which is allowed and sometimes what you want -- an
+unbounded `unique` on `events.uuid` says something a windowed one cannot. A check that runs out of
+ClickHouse's execution budget reports `errored` with the message; adding a window is usually the fix.
+
+On a `relationships` check, `lookback_hours` bounds the rows it checks and `to_lookback_hours`
+bounds the rows it looks for a match among. Set the second one carefully: a narrow target window
+makes rows fail for being old rather than for being wrong.
+
+`custom_sql` takes no `lookback_hours`. Put the time filter in the query yourself, or it reads the
+whole table.
+
+Nothing triggers these tables the way a sync triggers a source table, so their checks run on a
+schedule, daily by default. Change it with `posthog:data-quality-check-schedule`.
+
## Checks on catalog metrics
Only metrics with a saved `HogQLQuery` definition support checks. Markdown, Trends, Funnels, event
@@ -116,8 +139,9 @@ refresh whose error-severity checks fail is not published), a source table's che
completed sync, and a plain view's checks run when its DAG runs. Checks on a view outside any DAG
only run on demand.
-**Metric schedules:** The first saved check creates an enabled daily schedule for all checks on the
-metric. The Tests tab lets you change the interval or turn automatic runs off. Manual runs remain
+**Subject schedules:** A metric and a PostHog table have no data-change event to run on, so their
+checks run on a schedule instead. The first saved check creates an enabled daily schedule for all
+checks on that subject. The Tests tab lets you change the interval or turn automatic runs off. Manual runs remain
available. Scheduled checks use the latest definition author's access, falling back to the creator;
manual runs use the initiating user's access. Underlying and additional tables must be readable.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index e56ec49bf25e..5810995690cf 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3124,7 +3124,7 @@
}
},
"data-quality-check-create": {
- "description": "Add a dbt-test-style assertion to a warehouse table, a saved query (view or materialized view), or a data\ncatalog metric. Name the subject with subject_type ('table', 'view' or 'metric') and subject_uuid, both from\ndata-quality-subjects. A check passes when it finds zero failing rows.\n\nQuery `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,\nbut a near-duplicate with different config is noise for whoever reviews the results.\n\nOn a table or a view, prefer a generic type over custom_sql. Config per type:\n - not_null, unique: no config; set column_name.\n - accepted_values: {\"values\": [\"paid\", \"refunded\"]}; set column_name.\n - relationships: {\"to_subject_type\": \"table\", \"to_subject_uuid\": \"<uuid>\", \"to_column\": \"id\"}; set\n column_name.\n - row_count: {\"min\": 1} and/or {\"max\": 1000000}; no column_name.\n - freshness: {\"max_age_minutes\": 60}; set column_name to a timestamp column.\n - custom_sql: {\"query\": \"select 1 from orders where total < 0\"}; every row it returns is a failure.\n\nA metric supports custom_sql only, and takes no column_name. Its query must read the {metric} relation\nexactly once and cannot use CTEs: {\"query\": \"select * from {metric} where orders < 100\"}. Call\ndata-quality-check-types with the subject_type to see which types that kind of subject supports.\n\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. A check on a table runs after each sync of it, a check on a view when the view refreshes, and\na check on a metric on the metric's schedule.",
+ "description": "Add a dbt-test-style assertion to a warehouse table, a saved query (view or materialized view), a data\ncatalog metric, or a PostHog table (events, persons, groups). Name the subject with subject_type\n('table', 'view', 'metric' or 'posthog_table') and subject_uuid, both from data-quality-subjects. A check\npasses when it finds zero failing rows.\n\nQuery `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,\nbut a near-duplicate with different config is noise for whoever reviews the results.\n\nOn a table or a view, prefer a generic type over custom_sql. Config per type:\n - not_null, unique: no config; set column_name.\n - accepted_values: {\"values\": [\"paid\", \"refunded\"]}; set column_name.\n - relationships: {\"to_subject_type\": \"table\", \"to_subject_uuid\": \"<uuid>\", \"to_column\": \"id\"}; set\n column_name. to_subject_type takes 'table', 'view' or 'posthog_table'. Add \"to_lookback_hours\" to look\n for a match only among the referenced subject's recent rows, which only a target with a time column\n accepts.\n - row_count: {\"min\": 1} and/or {\"max\": 1000000}; no column_name.\n - freshness: {\"max_age_minutes\": 60}; set column_name to a timestamp column.\n - custom_sql: {\"query\": \"select 1 from orders where total < 0\"}; every row it returns is a failure.\n\nAdd \"lookback_hours\" to any config to check only the rows from the last N hours, by the subject's own time\ncolumn: timestamp on events, created_at on persons and groups. Optional, and only for a subject that has\none -- a warehouse table, a view and a metric do not. Without it the check reads the whole table, which on\nevents is expensive. custom_sql takes no lookback_hours; put the time filter in the query. Changing the\nwindow creates a new check, so update the existing one to keep its history.\n\nA metric supports custom_sql only, and takes no column_name. Its query must read the {metric} relation\nexactly once and cannot use CTEs: {\"query\": \"select * from {metric} where orders < 100\"}. Call\ndata-quality-check-types with the subject_type to see which types that kind of subject supports.\n\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. A check on a warehouse table runs after each sync of it, a check on a view when the view\nrefreshes, and a check on a metric or a PostHog table on that subject's schedule.",
"category": "Data quality",
"feature": "data_quality",
"summary": "Create a data quality check",
@@ -3229,7 +3229,7 @@
"feature_flag": "data-quality-checks"
},
"data-quality-subjects": {
- "description": "Every table, view and metric in this project you can read, with each one's columns and whether you can put a check on it. Start here: a check names its subject by the subject_type and id this returns, and a relationships check can point at a subject you can only read.",
+ "description": "Every table, view, metric and PostHog table in this project you can read, with each one's columns and whether you can put a check on it. Start here: a check names its subject by the subject_type and id this returns, and a relationships check can point at a subject you can only read. A subject whose time_column is set can take a lookback_hours window.",
"category": "Data quality",
"feature": "data_quality",
"summary": "List what a data quality check can be authored on",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 904e70c4c7c4..46a2734fc5ac 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3139,7 +3139,7 @@
}
},
"data-quality-check-create": {
- "description": "Add a dbt-test-style assertion to a warehouse table, a saved query (view or materialized view), or a data\ncatalog metric. Name the subject with subject_type ('table', 'view' or 'metric') and subject_uuid, both from\ndata-quality-subjects. A check passes when it finds zero failing rows.\n\nQuery `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,\nbut a near-duplicate with different config is noise for whoever reviews the results.\n\nOn a table or a view, prefer a generic type over custom_sql. Config per type:\n - not_null, unique: no config; set column_name.\n - accepted_values: {\"values\": [\"paid\", \"refunded\"]}; set column_name.\n - relationships: {\"to_subject_type\": \"table\", \"to_subject_uuid\": \"<uuid>\", \"to_column\": \"id\"}; set\n column_name.\n - row_count: {\"min\": 1} and/or {\"max\": 1000000}; no column_name.\n - freshness: {\"max_age_minutes\": 60}; set column_name to a timestamp column.\n - custom_sql: {\"query\": \"select 1 from orders where total < 0\"}; every row it returns is a failure.\n\nA metric supports custom_sql only, and takes no column_name. Its query must read the {metric} relation\nexactly once and cannot use CTEs: {\"query\": \"select * from {metric} where orders < 100\"}. Call\ndata-quality-check-types with the subject_type to see which types that kind of subject supports.\n\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. A check on a table runs after each sync of it, a check on a view when the view refreshes, and\na check on a metric on the metric's schedule.",
+ "description": "Add a dbt-test-style assertion to a warehouse table, a saved query (view or materialized view), a data\ncatalog metric, or a PostHog table (events, persons, groups). Name the subject with subject_type\n('table', 'view', 'metric' or 'posthog_table') and subject_uuid, both from data-quality-subjects. A check\npasses when it finds zero failing rows.\n\nQuery `system.information_schema.data_quality_checks` first — re-creating an identical check is a no-op,\nbut a near-duplicate with different config is noise for whoever reviews the results.\n\nOn a table or a view, prefer a generic type over custom_sql. Config per type:\n - not_null, unique: no config; set column_name.\n - accepted_values: {\"values\": [\"paid\", \"refunded\"]}; set column_name.\n - relationships: {\"to_subject_type\": \"table\", \"to_subject_uuid\": \"<uuid>\", \"to_column\": \"id\"}; set\n column_name. to_subject_type takes 'table', 'view' or 'posthog_table'. Add \"to_lookback_hours\" to look\n for a match only among the referenced subject's recent rows, which only a target with a time column\n accepts.\n - row_count: {\"min\": 1} and/or {\"max\": 1000000}; no column_name.\n - freshness: {\"max_age_minutes\": 60}; set column_name to a timestamp column.\n - custom_sql: {\"query\": \"select 1 from orders where total < 0\"}; every row it returns is a failure.\n\nAdd \"lookback_hours\" to any config to check only the rows from the last N hours, by the subject's own time\ncolumn: timestamp on events, created_at on persons and groups. Optional, and only for a subject that has\none -- a warehouse table, a view and a metric do not. Without it the check reads the whole table, which on\nevents is expensive. custom_sql takes no lookback_hours; put the time filter in the query. Changing the\nwindow creates a new check, so update the existing one to keep its history.\n\nA metric supports custom_sql only, and takes no column_name. Its query must read the {metric} relation\nexactly once and cannot use CTEs: {\"query\": \"select * from {metric} where orders < 100\"}. Call\ndata-quality-check-types with the subject_type to see which types that kind of subject supports.\n\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. A check on a warehouse table runs after each sync of it, a check on a view when the view\nrefreshes, and a check on a metric or a PostHog table on that subject's schedule.",
"category": "Data quality",
"feature": "data_quality",
"summary": "Create a data quality check",
@@ -3244,7 +3244,7 @@
"feature_flag": "data-quality-checks"
},
"data-quality-subjects": {
- "description": "Every table, view and metric in this project you can read, with each one's columns and whether you can put a check on it. Start here: a check names its subject by the subject_type and id this returns, and a relationships check can point at a subject you can only read.",
+ "description": "Every table, view, metric and PostHog table in this project you can read, with each one's columns and whether you can put a check on it. Start here: a check names its subject by the subject_type and id this returns, and a relationships check can point at a subject you can only read. A subject whose time_column is set can take a lookback_hours window.",
"category": "Data quality",
"feature": "data_quality",
"summary": "List what a data quality check can be authored on",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e8f164ba2494..f260e0bf4db0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24379,7 +24379,7 @@ export namespace Schemas {
/** @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.
+ * Data modeling node of the view or PostHog table this check audits, or null when it is on no DAG or the subject is a warehouse table.
* @nullable
*/
readonly subject_node_id: string | null;
@@ -24439,6 +24439,8 @@ export namespace Schemas {
name: string;
/** Label shown in the data catalog. Blank for tables and views. */
display_name: string;
+ /** Column a lookback window bounds, or blank for a subject that has none. */
+ time_column: string;
/** Column name to ClickHouse type. Empty for a metric, and for a view that has not run yet. */
columns: DataQualitySubjectColumns;
/** Whether the caller may author a check on this subject. A subject that is only readable can still be the target of a relationships check. */
@@ -24461,6 +24463,48 @@ export namespace Schemas {
checks_failing: number;
}
+ /**
+ * One subject's schedule, in the project-wide listing.
+ */
+ export interface DataQualitySubjectSchedule {
+ /** Schedule identifier. */
+ readonly id: string;
+ /** How often the checks run.
+ *
+ * * `1hour` - 1hour
+ * * `6hour` - 6hour
+ * * `12hour` - 12hour
+ * * `24hour` - 24hour
+ * * `7day` - 7day */
+ readonly interval: DataQualityScheduleIntervalEnum;
+ /** Whether the schedule runs automatically. */
+ readonly enabled: boolean;
+ /**
+ * Next scheduled execution time, if enabled.
+ * @nullable
+ */
+ readonly next_run_at: string | null;
+ /**
+ * Most recent visible scheduled suite execution time.
+ * @nullable
+ */
+ readonly last_run_at: string | null;
+ /**
+ * Most recent visible scheduled suite.
+ * @nullable
+ */
+ readonly last_suite_run: string | null;
+ /** 'metric' or 'posthog_table'.
+ *
+ * * `table` - table
+ * * `view` - view
+ * * `metric` - metric
+ * * `posthog_table` - posthog_table */
+ readonly subject_type: SubjectTypeEnum;
+ /** Id of the metric or PostHog table. */
+ readonly subject_uuid: string;
+ }
+
export interface DataQualitySuiteRun {
readonly id: string;
/** manual, materialization, source_sync, or scheduled. */