:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-quality): author checks from the project-wide endpoint (#102493)
Thiago Salvatore86fcb5ed8b0c
diff --git a/docs/internal/data-quality-checks.md b/docs/internal/data-quality-checks.mdindex 57a2b283873e..c2db1aecaa0c 100644--- a/docs/internal/data-quality-checks.md+++ b/docs/internal/data-quality-checks.md@@ -4,7 +4,9 @@ Data quality checks audit warehouse tables, saved views, and catalog metrics. Ch## Authorization-Check and run routes require project membership, query access, and access to the subject. The static check-type catalog does not require query access. Metric checks use catalog permissions. Table and view checks use their respective warehouse object permissions, including explicit object grants and inherited source grants. A resource-wide denial does not discard a more specific grant that the canonical access-control rules permit.+Every check is authored, read, run and scheduled through the project-wide `data_quality_checks` and `data_quality_runs` routes, whichever kind of subject it audits. A request names its subject in the body on create, and by check id after that; `subject_type` and `subject_uuid` query parameters narrow a listing, a health rollup, a run history, or a schedule to one subject.++Check and run routes require project membership, query access, and access to the subject. The static check-type catalog needs no access to any subject. Metric checks use catalog permissions. Table and view checks use their respective warehouse object permissions, including explicit object grants and inherited source grants. A resource-wide denial does not discard a more specific grant that the canonical access-control rules permit.Reading checks, health, and run history requires viewer access. Creating, editing, deleting, or manually running checks requires editor access to their subject. Referenced subjects require viewer access. These checks apply even when the warehouse query-enforcement feature flag is disabled.@@ -18,17 +20,15 @@ A check that reads more than its own subject executes as a user. A manual run exAll routes below also require `query:read`. Write scopes include read access; read-only scopes do not authorize writes. Token scopes limit access independently of the user's grants, including for organization administrators.-| Route | Read scope | Write scope |-| ------------------------------------------------ | ------------------------ | ------------------------- |-| Nested warehouse table checks and suite runs | `warehouse_table:read` | `warehouse_table:write` |-| Nested warehouse view checks and suite runs | `warehouse_view:read` | `warehouse_view:write` |-| Nested catalog metric checks and suite runs | `data_catalog:read` | `data_catalog:write` |-| Project-wide checks and runs, warehouse subjects | `warehouse_objects:read` | `warehouse_objects:write` |-| Project-wide checks and runs, metric subjects | `data_catalog:read` | `data_catalog:write` |+| Subject kind | Read scope | Write scope |+| ---------------- | -------------------------------------------------- | ---------------------------------------------------- |+| Warehouse tables | `warehouse_objects:read` or `warehouse_table:read` | `warehouse_objects:write` or `warehouse_table:write` |+| Warehouse views | `warehouse_objects:read` or `warehouse_view:read` | `warehouse_objects:write` or `warehouse_view:write` |+| Catalog metrics | `data_catalog:read` | `data_catalog:write` |-A project-wide token may select only the subject types its scopes permit. An unnamed manual sweep skips inaccessible checks; an explicitly selected inaccessible check is rejected. Cross-subject references must also fall within the caller's permitted subject types.+The family scope `warehouse_objects` reaches every warehouse kind. A per-kind scope reaches its own kind only, which is what a key minted by the Agent CLI carries. A token may select only the subject kinds its scopes permit. An unnamed manual sweep skips inaccessible checks; an explicitly selected inaccessible check is rejected. Cross-subject references must also fall within the caller's permitted subject types.-The table above applies to the REST routes only. A raw HogQL query against `system.information_schema.data_quality_*` needs `query:read` and no other scope. The user's own permissions still apply to each row. A token with `query:read` reads metric checks only if its user has catalog access.+The table above applies to the REST routes only. The MCP tools declare `query:read` alone, because a tool's scope list must be met in full and the two subject families are authorized independently; a token with no subject family is refused by the route. A raw HogQL query against `system.information_schema.data_quality_*` needs `query:read` and no other scope. The user's own permissions still apply to each row. A token with `query:read` reads metric checks only if its user has catalog access.## Custom SQLdiff --git a/playwright/e2e/data-quality-overview.spec.ts b/playwright/e2e/data-quality-overview.spec.tsindex 26149fc16204..ca0fe7b274dc 100644--- a/playwright/e2e/data-quality-overview.spec.ts+++ b/playwright/e2e/data-quality-overview.spec.ts@@ -26,18 +26,17 @@ test('edits and deletes a check from Data Ops', async ({ page, playwrightSetup }expect(savedQuery.ok()).toBe(true)const savedQueryId = (await savedQuery.json()).id- const created = await page.request.post(- `/api/projects/${workspace.team_id}/warehouse_saved_queries/${savedQueryId}/checks/`,- {- ...auth,- data: {- name: CHECK_NAME,- check_type: 'custom_sql',- column_name: '',- config: { query: 'SELECT id FROM orders_e2e WHERE id < 0' },- },- }- )+ const created = await page.request.post(`/api/projects/${workspace.team_id}/data_quality_checks/`, {+ ...auth,+ data: {+ name: CHECK_NAME,+ check_type: 'custom_sql',+ column_name: '',+ config: { query: 'SELECT id FROM orders_e2e WHERE id < 0' },+ subject_type: 'view',+ subject_uuid: savedQueryId,+ },+ })expect(created.ok()).toBe(true)const check = await created.json()@@ -64,10 +63,7 @@ test('edits and deletes a check from Data Ops', async ({ page, playwrightSetup }await saveButton.click()await expect(page.getByText('Check saved')).toBeVisible()- const edited = await page.request.get(- `/api/projects/${workspace.team_id}/warehouse_saved_queries/${savedQueryId}/checks/${check.id}/`,- auth- )+ const edited = await page.request.get(`/api/projects/${workspace.team_id}/data_quality_checks/${check.id}/`, auth)const editedCheck = await edited.json()// The point of the whole change: an edit refines the check rather than replacing it.expect(editedCheck.id).toEqual(check.id)diff --git a/products/data_catalog/backend/routes.py b/products/data_catalog/backend/routes.pyindex 46d4e5231f22..417a7c8fb849 100644--- a/products/data_catalog/backend/routes.py+++ b/products/data_catalog/backend/routes.py@@ -5,17 +5,10 @@ from products.data_catalog.backend.presentation.views import (MetricViewSet,RelationshipProposalViewSet,)-from products.data_quality.backend.presentation.views import MetricCheckViewSet, MetricSuiteRunViewSetdef register_routes(routers: RouterRegistry) -> None:- metrics_router = routers.projects.register(- r"data_catalog/metrics", MetricViewSet, "environment_data_catalog_metrics", ["team_id"]- )- metrics_router.register(r"checks", MetricCheckViewSet, "project_metric_checks", ["team_id", "metric_id"])- metrics_router.register(- r"check_suite_runs", MetricSuiteRunViewSet, "project_metric_check_suite_runs", ["team_id", "metric_id"]- )+ routers.projects.register(r"data_catalog/metrics", MetricViewSet, "environment_data_catalog_metrics", ["team_id"])routers.projects.register(r"data_catalog/certifications",CertificationViewSet,diff --git a/products/data_catalog/frontend/tabs/MetricTestsTab.stories.tsx b/products/data_catalog/frontend/tabs/MetricTestsTab.stories.tsxindex a474e762d064..b64dff65e377 100644--- a/products/data_catalog/frontend/tabs/MetricTestsTab.stories.tsx+++ b/products/data_catalog/frontend/tabs/MetricTestsTab.stories.tsx@@ -23,7 +23,7 @@ const meta: Meta<StoryProps> = {name: 'signups',definition_kind: definitionKind,},- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/': {+ '/api/projects/:team_id/data_quality_checks/': {results: hasCheck? [{@@ -40,12 +40,18 @@ const meta: Meta<StoryProps> = {]: [],},- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/health/': {- health: hasCheck ? 'failing' : 'unknown',- checks_total: hasCheck ? 1 : 0,- checks_failing: hasCheck ? 1 : 0,- },- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/check_types/': [+ '/api/projects/:team_id/data_quality_checks/health/': hasCheck+ ? [+ {+ subject_type: 'metric',+ subject_uuid: 'metric-1',+ health: 'failing',+ checks_total: 1,+ checks_failing: 1,+ },+ ]+ : [],+ '/api/projects/:team_id/data_quality_checks/check_types/': [{check_type: 'custom_sql',description: 'Return one row per failure.',@@ -53,8 +59,8 @@ const meta: Meta<StoryProps> = {config_schema: {},},],- '/api/projects/:team_id/data_catalog/metrics/metric-1/check_suite_runs/': { results: [] },- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/schedule/': {+ '/api/projects/:team_id/data_quality_runs/': { results: [] },+ '/api/projects/:team_id/data_quality_checks/schedule/': {id: 'schedule-1',enabled: true,interval: '24hour',diff --git a/products/data_catalog/frontend/tabs/MetricTestsTab.test.tsx b/products/data_catalog/frontend/tabs/MetricTestsTab.test.tsxindex 147628462de7..d43c0258969d 100644--- a/products/data_catalog/frontend/tabs/MetricTestsTab.test.tsx+++ b/products/data_catalog/frontend/tabs/MetricTestsTab.test.tsx@@ -20,13 +20,9 @@ describe('MetricTestsTab', () => {name: 'signups',definition_kind: kind,},- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/': { results: [] },- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/health/': {- health: 'unknown',- checks_total: 0,- checks_failing: 0,- },- '/api/projects/:team_id/data_catalog/metrics/metric-1/check_suite_runs/': { results: [] },+ '/api/projects/:team_id/data_quality_checks/': { results: [] },+ '/api/projects/:team_id/data_quality_checks/health/': [],+ '/api/projects/:team_id/data_quality_runs/': { results: [] },},})initKeaTests()@@ -57,7 +53,7 @@ describe('MetricTestsTab', () => {name: 'signups',definition_kind: 'MarkdownDefinition',},- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/': {+ '/api/projects/:team_id/data_quality_checks/': {results: [{id: 'check-1',@@ -71,12 +67,16 @@ describe('MetricTestsTab', () => {},],},- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/health/': {- health: 'failing',- checks_total: 1,- checks_failing: 1,- },- '/api/projects/:team_id/data_catalog/metrics/metric-1/checks/schedule/': {+ '/api/projects/:team_id/data_quality_checks/health/': [+ {+ subject_type: 'metric',+ subject_uuid: 'metric-1',+ health: 'failing',+ checks_total: 1,+ checks_failing: 1,+ },+ ],+ '/api/projects/:team_id/data_quality_checks/schedule/': {id: 'schedule-1',enabled: true,interval: '24hour',@@ -84,7 +84,7 @@ describe('MetricTestsTab', () => {last_run_at: null,last_suite_run: null,},- '/api/projects/:team_id/data_catalog/metrics/metric-1/check_suite_runs/': { results: [] },+ '/api/projects/:team_id/data_quality_runs/': { results: [] },},})initKeaTests()diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 7ff8f3b18298..9aecb0781df1 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -37,6 +37,7 @@ _LAZY = {"get_saved_query_columns": "logic.saved_query_reads","get_saved_query_ids_for_nodes": "logic.saved_query_reads","get_saved_query_summary": "logic.saved_query_reads",+ "all_saved_query_columns": "logic.saved_query_reads","all_saved_query_names": "logic.saved_query_reads","allowed_saved_query_ids": "logic.saved_query_reads","backing_table_ids_by_saved_query": "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.pyindex ff48482ee20e..8e23321d2f1c 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -61,6 +61,17 @@ def get_saved_query_summary(team_id: int, saved_query_id: UUID | str) -> SavedQu)+def all_saved_query_columns(team_id: int) -> dict[str, dict[str, str]]:+ """Each still-resolving saved query's columns, by id, unwrapped the way ``get_saved_query_columns`` does."""+ rows = DataWarehouseSavedQuery.objects.filter(team_id=team_id).exclude(deleted=True).values_list("id", "columns")+ return {+ str(saved_query_id): {+ name: type_ for name, entry in (stored or {}).items() if (type_ := _clickhouse_type(entry)) is not None+ }+ for saved_query_id, stored in rows+ }++def all_saved_query_names(team_id: int) -> dict[str, str]:"""The current name of every saved query in this team that still resolves. One query."""rows = DataWarehouseSavedQuery.objects.filter(team_id=team_id).exclude(deleted=True).values_list("id", "name")diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.pyindex 505f7fda5364..6920ad1cc775 100644--- a/products/data_quality/backend/facade/api.py+++ b/products/data_quality/backend/facade/api.py@@ -16,6 +16,7 @@ from ..logic.checks import (live_subject_checks,soft_delete_check,start_check_suite,+ subject_filter,subject_health,upsert_check,validate_check,@@ -56,9 +57,9 @@ from ..logic.subject_access import (visible_checks,without_denied_runs,)-from ..logic.subjects import resolve_metric_subjects, resolve_subject, testable_metric_subjects+from ..logic.subjects import resolve_metric_subjects, resolve_subject, selectable_subjects, testable_metric_subjectsfrom ..logic.triggers import materialization_audit_mode as quality_audit_mode-from .contracts import CheckTypeInfo, MetricSubject, OutputColumn+from .contracts import CheckTypeInfo, MetricSubject, OutputColumn, SelectableSubject__all__ = ["log_metric_schedule_change",@@ -73,6 +74,7 @@ __all__ = ["DenialContext","MetricSubject","OutputColumn",+ "SelectableSubject","ReadableSubjects","ReferencedSubjects","SubjectKey",@@ -114,8 +116,10 @@ __all__ = ["schedule_with_history","soft_delete_check","start_check_suite",+ "subject_filter","subject_health","subject_locations",+ "selectable_subjects","testable_metric_subjects","suites_backing_unreadable_runs_q","to_config_entry",diff --git a/products/data_quality/backend/facade/contracts.py b/products/data_quality/backend/facade/contracts.pyindex a691fce05b81..002f9ebf86fb 100644--- a/products/data_quality/backend/facade/contracts.py+++ b/products/data_quality/backend/facade/contracts.py@@ -73,6 +73,21 @@ class MetricSubject:display_name: str+@dataclass(frozen=True)+class SelectableSubject:+ """One thing a caller may author a check on, with enough to fill a picker.++ ``columns`` is empty for a metric, whose output columns come from running its query.+ """++ subject_type: str+ id: str+ name: str+ display_name: str = ""+ columns: dict[str, str] = field(default_factory=dict)+ editable: bool = True++@dataclass(frozen=True)class OutputColumn:name: strdiff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.pyindex e1c961eb37aa..679359f7e137 100644--- a/products/data_quality/backend/logic/checks.py+++ b/products/data_quality/backend/logic/checks.py@@ -72,7 +72,7 @@ def _edits_the_assertion(fields: Iterable[str]) -> bool:return any(field in requested for field in _ASSERTION_FIELDS)-def _subject_fk(subject_type: str, subject_uuid: str | UUID) -> dict[str, Any]:+def subject_filter(subject_type: str, subject_uuid: str | UUID) -> dict[str, Any]:"""The FK kwargs for whichever subject kind this is."""if subject_type == SubjectType.TABLE:return {"table_id": subject_uuid}@@ -163,7 +163,7 @@ def upsert_check(column_name=column_name,config=canonical,fingerprint=fingerprint,- **_subject_fk(subject_type, subject_uuid),+ **subject_filter(subject_type, subject_uuid),**fields,)if check.subject_type == SubjectType.METRIC and check.metric_id:@@ -193,7 +193,7 @@ def _find_by_fingerprint("""return (DataQualityCheck.objects.for_team(team_id)- .filter(fingerprint=fingerprint, deleted=False, **_subject_fk(subject_type, subject_uuid))+ .filter(fingerprint=fingerprint, deleted=False, **subject_filter(subject_type, subject_uuid)).first())@@ -329,7 +329,7 @@ def _definition_taken(check: DataQualityCheck, fingerprint: str) -> bool:"""Whether *another* active check on this subject already asserts this."""return (DataQualityCheck.objects.for_team(check.team_id)- .filter(fingerprint=fingerprint, deleted=False, **_subject_fk(check.subject_type, str(check.subject_uuid)))+ .filter(fingerprint=fingerprint, deleted=False, **subject_filter(check.subject_type, str(check.subject_uuid))).exclude(id=check.id).exists())@@ -364,7 +364,7 @@ def live_subject_checks(checks: QuerySet[DataQualityCheck]) -> QuerySet[DataQualdef checks_for_subject(team_id: int, subject_type: str, subject_uuid: str | UUID, include_deleted: bool = False) -> QuerySet[DataQualityCheck]:- queryset = DataQualityCheck.objects.for_team(team_id).filter(**_subject_fk(subject_type, subject_uuid))+ queryset = DataQualityCheck.objects.for_team(team_id).filter(**subject_filter(subject_type, subject_uuid))# A soft-deleted check's past runs still sit in the aggregate counts of suites it ran in, so# authorization over a *historical* suite has to see it too, even though it no longer runs.return queryset if include_deleted else live_subject_checks(queryset.filter(deleted=False))diff --git a/products/data_quality/backend/logic/permissions.py b/products/data_quality/backend/logic/permissions.pyindex 386543853fd4..0cc1ddb1c0a8 100644--- a/products/data_quality/backend/logic/permissions.py+++ b/products/data_quality/backend/logic/permissions.py@@ -9,7 +9,7 @@ from ..facade.enums import SubjectTypefrom .subject_access import DenialContext, ReadableSubjectsif TYPE_CHECKING:- from posthog.scopes import APIScopeObject, APIScopeObjectOrNotSupported+ from posthog.scopes import APIScopeObjectfrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -18,6 +18,7 @@ _SUBJECT_RESOURCES: dict[SubjectType, "APIScopeObject"] = {SubjectType.VIEW: "warehouse_view",SubjectType.METRIC: "data_catalog",}+_WAREHOUSE_FAMILY_SCOPE = "warehouse_objects"def authorized_subject_types(@@ -25,21 +26,21 @@ def authorized_subject_types(scopes: Collection[str] | None,*,write: bool = False,- route_scope: "APIScopeObjectOrNotSupported | None" = None,) -> frozenset[SubjectType]:level: Literal["editor", "viewer"] = "editor" if write else "viewer"return frozenset(kindfor kind, resource in _SUBJECT_RESOURCES.items()- if _scope_allows(- scopes,- resource if kind == SubjectType.METRIC or resource == route_scope else "warehouse_objects",- write,- )- and _has_subject_access(access, kind, level)+ if _scope_reaches(scopes, kind, resource, write) and _has_subject_access(access, kind, level))+def _scope_reaches(scopes: Collection[str] | None, kind: SubjectType, resource: str, write: bool) -> bool:+ if _scope_allows(scopes, resource, write):+ return True+ return kind != SubjectType.METRIC and _scope_allows(scopes, _WAREHOUSE_FAMILY_SCOPE, write)++def _has_subject_access(access: "UserAccessControl", kind: SubjectType, level: Literal["editor", "viewer"]) -> bool:if access.check_access_level_for_resource(_SUBJECT_RESOURCES[kind], level):return Truediff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pyindex 98afe857e70c..c4a3a1001b39 100644--- a/products/data_quality/backend/logic/subject_access.py+++ b/products/data_quality/backend/logic/subject_access.py@@ -40,7 +40,7 @@ from .contracts import SubjectIdentity, SubjectReffrom .exceptions import SubjectAccessUnverifiablefrom .registry import all_specs, get_specfrom .spec import CheckTypeSpec-from .subjects import resolve_metric_subjects, resolve_subject, resolve_subject_by_name+from .subjects import resolve_metric_subjects, resolve_subject, resolve_subject_by_name, unqueryable_table_idsif TYPE_CHECKING:from posthog.models import Team, User@@ -248,8 +248,7 @@ class SubjectMetadata:def subject_metadata(team_id: int) -> SubjectMetadata:tables = warehouse_facade.all_queryable_table_keys(team_id)- excluded_table_ids = set(data_modeling_facade.backing_table_ids_by_saved_query(team_id))- excluded_table_ids.update(warehouse_facade.direct_access_table_ids(team_id))+ excluded_table_ids = unqueryable_table_ids(team_id)included = {table_id: names for table_id, names in tables.items() if table_id not in excluded_table_ids}return SubjectMetadata(table_names={table_id: names.row_name for table_id, names in included.items()},diff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.pyindex 2b1aec24f651..f7843136bd30 100644--- a/products/data_quality/backend/logic/subjects.py+++ b/products/data_quality/backend/logic/subjects.py@@ -15,7 +15,7 @@ from products.data_modeling.backend.facade import api as data_modeling_facadefrom products.warehouse_sources.backend.facade import api as warehouse_facadefrom products.warehouse_sources.backend.facade.contracts import WAREHOUSE_OBJECT_TABLE, WAREHOUSE_OBJECT_VIEW-from ..facade.contracts import MetricSubject+from ..facade.contracts import MetricSubject, SelectableSubjectfrom ..facade.enums import SubjectTypefrom .contracts import SubjectRef@@ -35,6 +35,61 @@ def resolve_subject(team_id: int, subject_type: str, subject_uuid: str | UUID) -return _resolve_view(team_id, subject_uuid)+def unqueryable_table_ids(team_id: int) -> set[UUID]:+ """The tables the normal HogQL database leaves out, so no check should name one.++ A direct-access table is absent from the database build, so a check on it errors on every run.+ A materialized view's backing table answers to the view's own name, so a check on it reports+ against the wrong subject instead.+ """+ excluded = set(data_modeling_facade.backing_table_ids_by_saved_query(team_id))+ excluded.update(warehouse_facade.direct_access_table_ids(team_id))+ return excluded+++def selectable_subjects(team_id: int, kinds: Collection[SubjectType]) -> list[SelectableSubject]:+ """Everything in this team a check can be authored on, of the kinds asked for.++ The catalog, not the gate: narrowing it to what the caller may read is the caller's job.+ """+ subjects: list[SelectableSubject] = []+ if SubjectType.TABLE in kinds:+ excluded_table_ids = unqueryable_table_ids(team_id)+ columns_by_id = warehouse_facade.all_queryable_table_columns(team_id)+ subjects.extend(+ SelectableSubject(+ subject_type=SubjectType.TABLE,+ id=str(table_id),+ name=name,+ columns=columns_by_id.get(table_id) or {},+ )+ for table_id, name in warehouse_facade.all_queryable_table_names(team_id).items()+ if table_id not in excluded_table_ids+ )+ if SubjectType.VIEW in kinds:+ columns_by_id = data_modeling_facade.all_saved_query_columns(team_id)+ subjects.extend(+ SelectableSubject(+ subject_type=SubjectType.VIEW,+ id=saved_query_id,+ name=name,+ columns=columns_by_id.get(saved_query_id) or {},+ )+ for saved_query_id, name in data_modeling_facade.all_saved_query_names(team_id).items()+ )+ if SubjectType.METRIC in kinds:+ subjects.extend(+ SelectableSubject(+ subject_type=SubjectType.METRIC,+ id=str(metric.id),+ name=metric.name,+ display_name=metric.display_name,+ )+ for metric in testable_metric_subjects(team_id)+ )+ return sorted(subjects, key=lambda subject: (subject.subject_type, subject.name))++def testable_metric_subjects(team_id: int) -> list[MetricSubject]:return [MetricSubject(id=metric.id, name=metric.name, display_name=metric.display_name)@@ -124,17 +179,11 @@ def subject_column_type(team_id: int, subject_type: str, subject_uuid: str | UUIif kind is SubjectType.METRIC:return Noneif kind is SubjectType.TABLE:- table = warehouse_facade.get_queryable_table(UUID(str(subject_uuid)), team_id)- columns = table.columns if table else {}+ table_id = UUID(str(subject_uuid))+ columns = warehouse_facade.all_queryable_table_columns(team_id, {table_id}).get(table_id, {})else:columns = data_modeling_facade.get_saved_query_columns(team_id, subject_uuid)- entry = (columns or {}).get(column_name)- # A table records either a bare type string (older rows) or a dict keyed "clickhouse", the same- # two shapes hogql_fields_and_structure_for_columns handles; the saved-query facade already- # unwrapped a view's entry to the string.- if isinstance(entry, dict):- entry = entry.get("clickhouse")- return entry if isinstance(entry, str) else None+ return columns.get(column_name)def _missing(kind: SubjectType, subject_uuid: str | UUID) -> SubjectRef:diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.pyindex fca6836ff32d..b8305b2070c1 100644--- a/products/data_quality/backend/presentation/serializers.py+++ b/products/data_quality/backend/presentation/serializers.py@@ -29,6 +29,40 @@ class DataQualityMetricSubjectSerializer(serializers.Serializer):display_name = serializers.CharField(allow_blank=True, help_text="Metric label shown in the data catalog.")+@extend_schema_serializer(component_name="DataQualitySubjectRef")+class DataQualitySubjectRefSerializer(serializers.Serializer):+ """The subject a request names, wherever it names it: a body, a query string, or both."""++ subject_type = serializers.ChoiceField(+ choices=[(t.value, t.value) for t in SubjectType],+ help_text="Kind of catalog object: 'table', 'view', or 'metric'.",+ )+ subject_uuid = serializers.UUIDField(help_text="Id of the table, view, or metric.")+++@extend_schema_serializer(component_name="DataQualitySubject")+class DataQualitySubjectSerializer(serializers.Serializer):+ """One thing a check can be authored on, whatever kind it is."""++ subject_type = serializers.ChoiceField(+ choices=[(t.value, t.value) for t in SubjectType],+ help_text="Kind of object: 'table', 'view', or 'metric'. Pass it back as subject_type when creating a check.",+ )+ id = serializers.CharField(help_text="Id of the subject. Pass it back as subject_uuid when creating a check.")+ name = serializers.CharField(help_text="Queryable name of the subject.")+ display_name = serializers.CharField(+ allow_blank=True, help_text="Label shown in the data catalog. Blank for tables and views."+ )+ 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.",+ )+ editable = serializers.BooleanField(+ help_text="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."+ )++class DataQualityOutputColumnSerializer(serializers.Serializer):name = serializers.CharField(help_text="Output column name available through the {metric} relation.")type = serializers.CharField(allow_null=True, help_text="ClickHouse type, or null when it could not be inferred.")@@ -40,15 +74,20 @@ class DataQualityOutputSchemaSerializer(serializers.Serializer):@extend_schema_serializer(component_name="DataQualityCheck")class DataQualityCheckSerializer(serializers.ModelSerializer):- """The subject is implied by the URL (the parent saved query or table), never part of the body."""+ """A check as it reads back, and everything an edit may change about it.++ The subject is not one of those: it is writable only on ``DataQualityCheckCreate``.+ """subject_type = serializers.ChoiceField(choices=[(t.value, t.value) for t in SubjectType],read_only=True,help_text="Kind of catalog object being checked: 'table', 'view', or 'metric'.",)- subject_uuid = serializers.SerializerMethodField(- help_text="Id of the table, view, or metric being checked, from the parent resource in the URL."+ subject_uuid = serializers.UUIDField(+ read_only=True,+ allow_null=True,+ help_text="Id of the table, view, or metric being checked. Null once the subject is deleted.",)check_type = serializers.ChoiceField(choices=[(t.value, t.value) for t in CheckType],@@ -168,15 +207,10 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):def get_owner(self, obj: DataQualityCheck) -> str | None:return obj.owner.email if obj.owner else None- @extend_schema_field(serializers.UUIDField(allow_null=True))- def get_subject_uuid(self, obj: DataQualityCheck) -> str | None:- return str(obj.subject_uuid) if obj.subject_uuid else None-def validate(self, attrs: dict) -> dict:if self.instance is not None:return attrs- # The subject comes from the URL: the viewset resolves the parent and passes it in context.try:api.validate_check(self.context["get_team"](),@@ -211,6 +245,17 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):)+@extend_schema_serializer(component_name="DataQualityCheckCreate")+class DataQualityCheckCreateSerializer(DataQualityCheckSerializer):+ """The create body, where the subject is named for the only time in a check's life."""++ subject_type = serializers.ChoiceField(+ choices=[(t.value, t.value) for t in SubjectType],+ help_text="Kind of catalog object to check: 'table', 'view', or 'metric'.",+ )+ subject_uuid = serializers.UUIDField(help_text="Id of the table, view, or metric to check.")++@extend_schema_serializer(component_name="DataQualityOverviewCheck")class DataQualityOverviewCheckSerializer(DataQualityCheckSerializer):"""A check plus where its subject can be opened, for the project-wide list.@@ -265,12 +310,21 @@ class DataQualityOverviewCheckSerializer(DataQualityCheckSerializer):return self._location(obj).metric_name-class DataQualityCheckScheduleUpdateSerializer(serializers.Serializer):+@extend_schema_serializer(component_name="DataQualityCheckScheduleUpdate")+class DataQualityCheckScheduleUpdateSerializer(DataQualitySubjectRefSerializer):+ """Which subject's schedule to change, and what to change about it."""++ SCHEDULE_FIELDS = ("interval", "enabled")+interval = serializers.ChoiceField(- choices=list(ScheduleInterval), required=False, help_text="How often all enabled checks on the metric run."+ choices=list(ScheduleInterval), required=False, help_text="How often all enabled checks on the subject run.")enabled = serializers.BooleanField(required=False, help_text="Whether checks run automatically on this schedule.")+ @property+ def schedule_changes(self) -> dict:+ return {key: value for key, value in self.validated_data.items() if key in self.SCHEDULE_FIELDS}+class DataQualityCheckScheduleSerializer(serializers.Serializer):id = serializers.UUIDField(read_only=True, help_text="Schedule identifier.")@@ -420,6 +474,22 @@ class DataQualityRunRequestSerializer(serializers.Serializer):required=False,help_text="Ids of the checks to run. Omit to run every enabled check in the project.",)+ subject_type = serializers.ChoiceField(+ choices=[(t.value, t.value) for t in SubjectType],+ required=False,+ help_text="Narrow the run to one subject. Pass subject_uuid with it. Ignored when check_ids is given.",+ )+ subject_uuid = serializers.UUIDField(+ required=False,+ help_text="Id of the subject to run every enabled check on. Pass subject_type with it.",+ )++ def validate(self, attrs: dict) -> dict:+ if bool(attrs.get("subject_type")) != bool(attrs.get("subject_uuid")):+ raise serializers.ValidationError(+ {"subject_uuid": "Name the subject with both subject_type and subject_uuid, or neither."}+ )+ return attrs@extend_schema_serializer(component_name="DataQualityGateConfig")diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex 7e20000a71b9..d62f632c5edf 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -1,16 +1,16 @@-"""DRF views for data quality checks, nested under the subjects they audit.+"""DRF views for data quality checks.-Checks hang off the existing warehouse surfaces -- ``warehouse_saved_queries/{id}/checks`` and-``warehouse_tables/{id}/checks`` -- the same way run/materialize/resume do, gated by warehouse-scopes rather than a scope of their own. Thin: validate via the serializer, call the facade,-serialize the result. Nothing here runs a check -- every trigger hands off to Temporal and returns-a suite-run handle to poll.+Every check is authored, read, run and scheduled through ``data_quality_checks``, whatever kind of+subject it audits. The subject is named in the body on create and read off the check row after+that. Thin: validate via the serializer, call the facade, serialize the result. Nothing here runs a+check -- every trigger hands off to Temporal and returns a suite-run handle to poll."""from collections import defaultdict-from collections.abc import Callable, Sequence+from collections.abc import Mapping, Sequence+from dataclasses import replacefrom functools import cached_property-from typing import TYPE_CHECKING, ClassVar, cast+from typing import TYPE_CHECKING, Any, ClassVar, castfrom uuid import UUIDfrom django.db.models import QuerySet@@ -32,14 +32,13 @@ from posthog.models import Team, Userfrom posthog.permissions import APIScopePermission, TeamMemberAccessPermission, get_authenticator_scopesfrom posthog.rate_limit import HogQLQueryThrottle-from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin-from ..facade import api-from ..facade.enums import CheckRunStatus, SubjectStatus, SubjectType+from ..facade.enums import CheckRunStatus, CheckType, SubjectStatus, SubjectTypefrom ..facade.flags import is_data_quality_checks_enabledfrom ..facade.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom .serializers import (CheckTypeSerializer,+ DataQualityCheckCreateSerializer,DataQualityCheckRunSerializer,DataQualityCheckScheduleSerializer,DataQualityCheckScheduleUpdateSerializer,@@ -49,12 +48,15 @@ from .serializers import (DataQualityOutputSchemaSerializer,DataQualityOverviewCheckSerializer,DataQualityRunRequestSerializer,+ DataQualitySubjectRefSerializer,+ DataQualitySubjectSerializer,DataQualitySuiteRunSerializer,SubjectHealthSerializer,)_RECENT_RUNS_LIMIT = 50_LAST_RUN_FIELDS = ("last_status", "last_run_at", "last_succeeded_at", "failing_since")+_SUBJECT_TYPE_VALUES = frozenset(kind.value for kind in SubjectType)if TYPE_CHECKING:from rest_framework.permissions import _SupportsHasPermission@@ -66,9 +68,6 @@ class _DataQualitySubjectPermission(BasePermission):return Falseif not view.user_access_control.check_access_level_for_object(view.team, "member"):return False- if isinstance(view, _SubjectScopedViewSet):- view._require_parent_subject_access()- return view.subject_type in view._authorized_subject_types(write=request.method not in SAFE_METHODS)return bool(view._authorized_subject_types(write=request.method not in SAFE_METHODS))def has_object_permission(self, request: Request, view: APIView, obj: object) -> bool:@@ -81,11 +80,11 @@ class _DataQualitySubjectPermission(BasePermission):class _QualityGatedViewSet(TeamAndOrgViewSetMixin):- """The gating every data quality surface shares, whether or not it is nested under a subject.+ """The gating every data quality surface shares.- Entry points are gated on the product flag, and most additionally on query access: run results- are a count oracle over the underlying rows, so a member denied `query` must not reach them- through a check. Only the check-type *catalog* stays ungated by query: static schema metadata.+ Entry points are gated on the product flag and on query access: run results are a count oracle+ over the underlying rows, so a member denied `query` must not reach them through a check. Only+ the check-type *catalog* stays ungated by any one subject: it is static schema metadata.Denial is name-based, reading the same set the information_schema loaders do, so REST and SQLcan never disagree about which subjects a member may see.@@ -161,7 +160,6 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):self.user_access_control,get_authenticator_scopes(self.request.successful_authenticator),write=write,- route_scope=self.scope_object,)return self._authorized_types[write]@@ -254,104 +252,213 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):return Nonereturn api.SubjectIdentity(subject_type=check.subject_type, subject_uuid=str(check.subject_uuid))+ def _require_subject_access(self, identity: api.SubjectIdentity, *, write: bool) -> None:+ """403 a subject this caller may not read, or may not change when the request changes it.-class _SubjectScopedViewSet(_QualityGatedViewSet):- """Adds the parent-subject gate for viewsets nested under a catalog subject."""+ A subject that no longer resolves is out of reach on the same terms: deleting it takes its+ denial with it, so nothing left can show the caller was allowed it. A caller who cannot be+ object-denied keeps orphan access, since orphaned history stays reachable for them.+ """+ if not self._can_be_object_denied():+ return+ if not self._denial_context().readable.contains(identity.subject_type, identity.subject_uuid):+ raise PermissionDenied("You don't have access to this table or view.")+ if write and not self._writable_subjects.contains(identity.subject_type, identity.subject_uuid):+ raise PermissionDenied("You need edit access to this subject to change or run its checks.")- subject_type: ClassVar[SubjectType]- subject_field: ClassVar[str]+ def _require_subject_type_authorized(self, subject_type: str, *, write: bool) -> None:+ """403 a kind of subject this caller's role or token scopes do not cover at all."""+ if subject_type not in self._authorized_subject_types(write=write):+ raise PermissionDenied("You don't have permission to work with checks on this kind of subject.")- @property- def subject_uuid(self) -> str:- return str(self.parents_query_dict[f"{self.subject_field}_id"])+ def _require_subject(self, identity: api.SubjectIdentity, *, write: bool) -> None:+ self._require_subject_type_authorized(identity.subject_type, write=write)+ self._require_subject_access(identity, write=write)- def initial(self, request: Request, *args, **kwargs) -> None:- super().initial(request, *args, **kwargs)- self._require_parent_subject_access()- self._require_subject_id()+ def _named_subject(self, source: Mapping[str, Any]) -> api.SubjectIdentity:+ """The subject this request names, as a 400 rather than a lookup when it names none."""+ serializer = DataQualitySubjectRefSerializer(data={key: source.get(key) for key in _SUBJECT_KEYS})+ serializer.is_valid(raise_exception=True)+ return api.SubjectIdentity(+ subject_type=str(serializer.validated_data["subject_type"]),+ subject_uuid=str(serializer.validated_data["subject_uuid"]),+ )- def _require_subject_id(self) -> None:- """404 a parent segment that is not a uuid, before it reaches a UUIDField filter.+ def _optional_subject(self, source: Mapping[str, Any]) -> api.SubjectIdentity | None:+ if not any(source.get(key) for key in _SUBJECT_KEYS):+ return None+ return self._named_subject(source)- The segment accepts any path token, and a metric's own routes address it by name, so a- caller can land a name here. A UUIDField raises Django's ValidationError rather than the- ValueError the router's parent filter catches, so the request would end as a 500 and a- captured exception.+ def _require_enabled_check_access(self, identity: api.SubjectIdentity) -> None:+ """403 when any check the request is about to set running reads a subject out of reach."""+ if not self._can_be_object_denied():+ return+ for check in api.checks_for_subject(self.team_id, identity.subject_type, identity.subject_uuid).filter(+ enabled=True+ ):+ self._require_referenced_subject_access(check.check_type, check.config, subject=identity)- After the access gate, not before it: a caller who can be object-denied is already answered- by that gate, which reads the same segment and denies anything it cannot parse. This one- covers the callers the gate returns early for.- """- try:- UUID(self.subject_uuid)- except ValueError:- raise NotFound(f"This route addresses a {self.subject_type} by its id, not its name.")- @cached_property- def _parent_identity(self) -> api.SubjectIdentity:- return api.SubjectIdentity(subject_type=self.subject_type, subject_uuid=self.subject_uuid)+class ScheduleUnavailableAPIError(APIException):+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE+ default_code = "schedule_unavailable"+ default_detail = "Could not read or update the check schedule. Reload it and try again."- def _require_parent_subject_access(self) -> None:- """403 a parent this caller may not read -- for every action, including list.- A member denied a view must not be able to enumerate its check configs or counts through- this surface. A parent that no longer resolves is out of reach on the same terms: deleting- it takes its denial with it, so nothing left can show the caller was allowed it. A caller who- cannot be object-denied keeps orphan access, since orphaned history stays reachable for them.- """- if not self._can_be_object_denied():- return- if not self._denial_context().readable.contains(self.subject_type, self.subject_uuid):- raise PermissionDenied("You don't have access to this table or view.")- if self.request.method not in SAFE_METHODS and not self._writable_subjects.contains(- self.subject_type, self.subject_uuid- ):- raise PermissionDenied("You need edit access to this subject to change or run its checks.")+class _ProjectQualityViewSet(_QualityGatedViewSet):+ scope_object = "query"++ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str]:+ return ["query:read"]++ def initial(self, request: Request, *args, **kwargs) -> None:+ super().initial(request, *args, **kwargs)+ if not self._authorized_subject_types(write=request.method not in SAFE_METHODS):+ raise PermissionDenied("You need access to warehouse objects or the data catalog to work with checks.")_EDIT_DESCRIPTION = ("Edit this check in place, including what it asserts (check_type, column_name, config). The "- "table or view it audits is fixed, and the check keeps its id, run history, latest status, and "- "latest run time. A definition or name already held by another active check comes back as a "- "field error, with nothing written."+ "subject it audits is fixed, and the check keeps its id, run history, latest status, and latest "+ "run time. A definition or name already held by another active check comes back as a field "+ "error, with nothing written."+)++_SUBJECT_TYPE_PARAMETER = OpenApiParameter(+ "subject_type",+ OpenApiTypes.STR,+ OpenApiParameter.QUERY,+ enum=[kind.value for kind in SubjectType],+ description="Kind of catalog object: 'table', 'view', or 'metric'.",)+_SUBJECT_UUID_PARAMETER = OpenApiParameter(+ "subject_uuid",+ OpenApiTypes.UUID,+ OpenApiParameter.QUERY,+ description="Id of the table, view, or metric.",+)+_SUBJECT_PARAMETERS = [_SUBJECT_TYPE_PARAMETER, _SUBJECT_UUID_PARAMETER]+# A listing filter can be left out; a lookup cannot answer without a subject at all, so the actions+# that look one up declare both as required rather than letting a generated client omit them.+_REQUIRED_SUBJECT_PARAMETERS = [+ OpenApiParameter(+ parameter.name,+ parameter.type,+ parameter.location,+ required=True,+ description=parameter.description,+ enum=parameter.enum,+ )+ for parameter in _SUBJECT_PARAMETERS+]+_CHECK_TYPE_PARAMETER = OpenApiParameter(+ "check_type",+ OpenApiTypes.STR,+ OpenApiParameter.QUERY,+ enum=[kind.value for kind in CheckType],+ description="Only the checks that make this assertion. See /check_types/.",+)+_SUBJECT_KEYS = ("subject_type", "subject_uuid")@extend_schema_view(update=extend_schema(description=_EDIT_DESCRIPTION),partial_update=extend_schema(description=_EDIT_DESCRIPTION),+ list=extend_schema(+ description="Every check in the project. Narrow it to one subject with subject_type and "+ "subject_uuid, or to one assertion with check_type.",+ parameters=[*_SUBJECT_PARAMETERS, _CHECK_TYPE_PARAMETER],+ ),)-class _BaseCheckViewSet(_SubjectScopedViewSet, viewsets.ModelViewSet):- """CRUD for one subject's checks, plus the actions that run them and report on them."""+class DataQualityCheckViewSet(_ProjectQualityViewSet, viewsets.ModelViewSet):+ """Every check in the project: authoring, running, results, health, and schedules."""DETAIL_VISIBILITY_ACTIONS = frozenset({"retrieve", "destroy"})QUERY_GATED_ACTIONS = frozenset(- {"list", "retrieve", "create", "update", "partial_update", "destroy", "run", "run_all", "runs", "health"}+ {+ "list",+ "retrieve",+ "create",+ "update",+ "partial_update",+ "destroy",+ "run",+ "runs",+ "health",+ "output_schema",+ "schedule",+ "subjects",+ "metric_subjects",+ })+ SUBJECT_FILTERED_ACTIONS = frozenset({"list", "health"})serializer_class = DataQualityCheckSerializerqueryset = DataQualityCheck.objects.unscoped()+ ACTION_SERIALIZERS: ClassVar[dict[str, type[BaseSerializer]]] = {+ "list": DataQualityOverviewCheckSerializer,+ "create": DataQualityCheckCreateSerializer,+ }++ def get_serializer_class(self) -> type[BaseSerializer]:+ return self.ACTION_SERIALIZERS.get(self.action or "", DataQualityCheckSerializer)++ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str]:+ if getattr(view, "action", None) == "metric_subjects":+ return ["data_catalog:read", "query:read"]+ return super().dangerously_get_required_scopes(request, view)++ def _authorized_query_subject(self) -> api.SubjectIdentity | None:+ subject = self._optional_subject(self.request.query_params)+ if subject is not None:+ self._require_subject(subject, write=False)+ return subject++ def get_serializer_context(self) -> dict:+ context = super().get_serializer_context()+ subject = getattr(self, "_authorized_subject", None)+ if subject is not None:+ context |= {"subject_type": subject.subject_type, "subject_uuid": subject.subject_uuid}+ return context+def safely_get_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:- # The parent lookup filters by the subject FK; deleted checks stay hidden.- queryset = api.live_subject_checks(queryset.filter(team_id=self.team_id, deleted=False)).select_related(- "created_by", "owner"+ # Orphans are excluded: their subject is gone, so there is no page to link to, nothing to+ # run, and no rollup to sit under. The run history they left behind stays queryable.+ # The rollup reads four columns of every enabled check in the project and serializes none of+ # the people, so it does not pay for the author join the listing needs.+ # A name is optional, so the id breaks the tie a blank one leaves -- newest first, and a+ # total order, without which two pages of the same listing can repeat or drop a check.+ queryset = (+ api.live_subject_checks(queryset.filter(team_id=self.team_id, deleted=False))+ .exclude(subject_status=SubjectStatus.ORPHANED)+ .order_by("subject_name", "name", "-id"))+ if self.action in self.SUBJECT_FILTERED_ACTIONS and (subject := self._authorized_query_subject()):+ queryset = queryset.filter(**api.subject_filter(subject.subject_type, subject.subject_uuid))if check_type := self.request.query_params.get("check_type"):queryset = queryset.filter(check_type=check_type)- return queryset.order_by("-created_at")+ return queryset.select_related("created_by", "owner") if self.action == "list" else querysetdef filter_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:- # The parent gate cleared this subject, but a check under it can read a second one. Its- # config names that subject, and its status answers questions about the rows behind it.+ # Hiding a denied subject's checks matters here: this one lists everything, so a leak is a+ # directory of the tables a member cannot read. Denial is matched by name rather than+ # equality, so the pass has to happen in Python; only a restricted member pays for it, since+ # the denied set is empty for everyone else.queryset = super().filter_queryset(queryset)- # Listing only. The routes that address one check keep answering 403 with what is wrong,- # which tells the caller more than the 404 that hiding the row would give them.- if self.action != "list":- return queryset- if not self._can_be_object_denied():+ if self.action not in self.SUBJECT_FILTERED_ACTIONS or not self._can_be_object_denied():return querysetreturn api.visible_check_queryset(self.team_id, queryset, self._denial_context())+ def list(self, request: Request, *args, **kwargs) -> Response:+ queryset = self.filter_queryset(self.get_queryset())+ page = self.paginate_queryset(queryset)+ checks = list(queryset) if page is None else page+ # Resolved once for the page, so linking to a subject costs two queries rather than one per+ # check. Anything the batch cannot resolve stays absent and renders as plain text.+ context = {**self.get_serializer_context(), "subject_locations": api.subject_locations(self.team_id, checks)}+ serializer = self.get_serializer(checks, many=True, context=context)+ return self.get_paginated_response(serializer.data) if page is not None else Response(serializer.data)+def safely_get_object(self, queryset: QuerySet[DataQualityCheck]) -> DataQualityCheck:lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_fieldcheck = get_object_or_404(queryset, **{self.lookup_field: self.kwargs[lookup_url_kwarg]})@@ -361,28 +468,25 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, viewsets.ModelViewSet):and check.id in self._hidden_check_ids([check])):raise PermissionDenied("You don't have access to a table or view this check reads.")+ subject = self._check_identity(check)+ if subject is not None:+ self._require_subject(subject, write=self.request.method not in SAFE_METHODS)return check- def get_serializer_context(self) -> dict:- return {- **super().get_serializer_context(),- "subject_type": self.subject_type,- "subject_uuid": self.subject_uuid,- }-@extend_schema(- description="Create a check on this table or view, or refine the one already carrying the same "- "fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.",+ description="Create a check on the table, view or metric named by subject_type and subject_uuid, "+ "or refine the one already carrying the same fingerprint. Re-creating a semantically identical "+ "check returns 200 and the existing row, never a duplicate.",)def create(self, request: Request, *args, **kwargs) -> Response:+ subject = self._named_subject(request.data)+ self._require_subject(subject, write=True)+ self._authorized_subject = subject+serializer = self.get_serializer(data=request.data)serializer.is_valid(raise_exception=True)data = serializer.validated_data- self._require_referenced_subject_access(- data["check_type"],- data.get("config") or {},- subject=self._parent_identity,- )+ self._require_referenced_subject_access(data["check_type"], data.get("config") or {}, subject=subject)optional = {key: data[key]@@ -402,8 +506,8 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, viewsets.ModelViewSet):check, created = api.upsert_check(team=self.team,user=cast(User, request.user),- subject_type=self.subject_type,- subject_uuid=self.subject_uuid,+ subject_type=subject.subject_type,+ subject_uuid=subject.subject_uuid,check_type=data["check_type"],column_name=data.get("column_name", ""),config=data.get("config") or {},@@ -457,50 +561,22 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, viewsets.ModelViewSet):)@action(methods=["POST"], detail=True)def run(self, request: Request, **kwargs) -> Response:- # The parent gate cleared the declared subject; a check can still read a denied one+ # The subject gate cleared the declared subject; a check can still read a denied one# (relationships target, custom_sql table), so gate on every subject it references too.check = self.get_object()- self._require_referenced_subject_access(- check.check_type,- check.config,- subject=self._parent_identity,- )- # The subject is stamped alongside check_ids so the handle stays reachable through this- # subject's nested suite-run routes, which filter on it. check_ids still decides what runs.+ subject = self._check_identity(check)+ self._require_referenced_subject_access(check.check_type, check.config, subject=subject)+ # The subject is stamped alongside check_ids so the suite reads back as scoped to it.+ # check_ids still decides what runs.suite_run = api.start_check_suite(team=self.team,user=cast(User, request.user),- subject_type=self.subject_type,- subject_uuids=[self.subject_uuid],+ subject_type=subject.subject_type if subject else "",+ subject_uuids=[subject.subject_uuid] if subject else [],check_ids=[str(check.id)],)return Response(DataQualitySuiteRunSerializer(suite_run).data)- @extend_schema(- description="Run every enabled check on this table or view. Returns the suite run to poll.",- request=None,- responses={200: DataQualitySuiteRunSerializer},- )- @action(methods=["POST"], detail=False, url_path="run_all")- def run_all(self, request: Request, **kwargs) -> Response:- # Each of the subject's checks may read a further subject the member is denied, so gate on- # those too before running the batch. Only a restricted member has anything to check.- self._require_enabled_check_access()- suite_run = api.start_check_suite(- team=self.team,- user=cast(User, request.user),- subject_type=self.subject_type,- subject_uuids=[self.subject_uuid],- )- return Response(DataQualitySuiteRunSerializer(suite_run).data)-- def _require_enabled_check_access(self) -> None:- if not self._can_be_object_denied():- return- subject = self._parent_identity- for check in api.checks_for_subject(self.team_id, self.subject_type, self.subject_uuid).filter(enabled=True):- self._require_referenced_subject_access(check.check_type, check.config, subject=subject)-@extend_schema(description="Recent run history for this check, newest first.",responses={200: DataQualityCheckRunSerializer(many=True)},@@ -510,11 +586,7 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, viewsets.ModelViewSet):check = self.get_object()# The current definition gates the check itself; each run is then judged on the definition# it executed, so editing a check into a harmless one does not unlock what it used to read.- self._require_referenced_subject_access(- check.check_type,- check.config,- subject=self._parent_identity,- )+ self._require_referenced_subject_access(check.check_type, check.config, subject=self._check_identity(check))runs = self._readable_runs(DataQualityCheckRun.objects.for_team(self.team_id).filter(quality_check=check)).select_related("quality_check")@@ -523,103 +595,151 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, viewsets.ModelViewSet):)@extend_schema(- description="Health rollup for this table or view, from the denormalized status of its checks.",- responses={200: SubjectHealthSerializer},+ description="Health rollup per subject, for every subject in the project that has checks. "+ "Narrow it to one subject with subject_type and subject_uuid.",+ parameters=_SUBJECT_PARAMETERS,+ responses={200: SubjectHealthSerializer(many=True)},)@action(methods=["GET"], detail=False, pagination_class=None)def health(self, request: Request, **kwargs) -> Response:- # A rollup counts the checks it covers, so it has to cover the same ones the list serves.- # Rolled up from the rows that survive rather than through subject_health(), which would go- # back to the database and count the withheld ones straight back in.- checks = list(api.checks_for_subject(self.team_id, self.subject_type, self.subject_uuid).filter(enabled=True))- if self._can_be_object_denied():- withheld = self._hidden_check_ids(checks)- checks = [check for check in checks if check.id not in withheld]- return Response(- SubjectHealthSerializer(- {- "subject_type": self.subject_type,- "subject_uuid": self.subject_uuid,- "health": api.roll_up_health(- api.CheckStatusRow(severity=check.severity, last_status=check.last_status) for check in checks- ),- "checks_total": len(checks),- "checks_failing": sum(1 for check in checks if check.last_status == CheckRunStatus.FAILED),- }- ).data- )+ # Rolled up from the checks already loaded, using the same rule as the listing. Calling+ # subject_health() per subject would be a query per table.+ by_subject: dict[tuple[str, str], list[DataQualityCheck]] = defaultdict(list)+ for check in self.filter_queryset(self.get_queryset()).filter(enabled=True):+ if check.subject_uuid is None:+ # An orphan has no subject left to roll up under.+ continue+ by_subject[(check.subject_type, str(check.subject_uuid))].append(check)++ rollups = [+ {+ "subject_type": subject_type,+ "subject_uuid": subject_uuid,+ "health": api.roll_up_health(+ api.CheckStatusRow(severity=check.severity, last_status=check.last_status) for check in checks+ ),+ "checks_total": len(checks),+ "checks_failing": sum(1 for check in checks if check.last_status == CheckRunStatus.FAILED),+ }+ for (subject_type, subject_uuid), checks in by_subject.items()+ ]+ return Response(SubjectHealthSerializer(rollups, many=True).data)@extend_schema(- description="The check types this project can author, with the JSON schema of each type's config.",+ description="The check types this project can author, with the JSON schema of each type's config. "+ "Pass subject_type to narrow it to the types that kind of subject supports.",+ parameters=[_SUBJECT_TYPE_PARAMETER],responses={200: CheckTypeSerializer(many=True)},)@action(methods=["GET"], detail=False, url_path="check_types", pagination_class=None)def check_types(self, request: Request, **kwargs) -> Response:- return Response(CheckTypeSerializer(api.list_check_types(self.subject_type), many=True).data)---class SavedQueryCheckViewSet(_BaseCheckViewSet, AccessControlViewSetMixin):- scope_object = "warehouse_view"- subject_type = SubjectType.VIEW- subject_field = "saved_query"---class TableCheckViewSet(_BaseCheckViewSet, AccessControlViewSetMixin):- scope_object = "warehouse_table"- subject_type = SubjectType.TABLE- subject_field = "table"---class ScheduleUnavailableAPIError(APIException):- status_code = status.HTTP_503_SERVICE_UNAVAILABLE- default_code = "schedule_unavailable"- default_detail = "Could not read or update the check schedule. Reload it and try again."+ subject_type = request.query_params.get("subject_type") or None+ if subject_type is not None and subject_type not in _SUBJECT_TYPE_VALUES:+ raise ValidationError({"subject_type": f"Unknown subject type '{subject_type}'."})+ return Response(CheckTypeSerializer(api.list_check_types(subject_type), many=True).data)+ @extend_schema(+ description="Everything in this project you can author a check on, with each subject's columns.",+ request=None,+ responses={200: DataQualitySubjectSerializer(many=True)},+ )+ @action(methods=["GET"], detail=False, pagination_class=None)+ def subjects(self, request: Request, **kwargs) -> Response:+ selectable = api.selectable_subjects(self.team_id, self._authorized_subject_types())+ editable_kinds = self._authorized_subject_types(write=True)+ if self._can_be_object_denied():+ readable = self._denial_context().readable+ writable = self._writable_subjects+ selectable = [+ replace(subject, editable=writable.contains(subject.subject_type, subject.id))+ for subject in selectable+ if readable.contains(subject.subject_type, subject.id)+ ]+ else:+ selectable = [+ replace(subject, editable=SubjectType(subject.subject_type) in editable_kinds) for subject in selectable+ ]+ return Response(DataQualitySubjectSerializer(selectable, many=True).data)-class MetricCheckViewSet(_BaseCheckViewSet):- scope_object = "data_catalog"- subject_type = SubjectType.METRIC- subject_field = "metric"- QUERY_GATED_ACTIONS = _BaseCheckViewSet.QUERY_GATED_ACTIONS | {"output_schema", "schedule"}+ @extend_schema(request=None, responses={200: DataQualityMetricSubjectSerializer(many=True)})+ @action(methods=["GET"], detail=False, pagination_class=None)+ def metric_subjects(self, request: Request, **kwargs) -> Response:+ if not self.user_access_control.check_access_level_for_resource("data_catalog", "viewer"):+ raise PermissionDenied("You need data catalog access to create checks on metrics.")+ metrics = api.testable_metric_subjects(self.team_id)+ if self._can_be_object_denied():+ readable_ids = self._denial_context().readable.metric_ids+ metrics = [metric for metric in metrics if metric.id in readable_ids]+ return Response(DataQualityMetricSubjectSerializer(metrics, many=True).data)- @extend_schema(request=None, responses={200: DataQualityOutputSchemaSerializer})- @action(methods=["GET"], detail=False, pagination_class=None, throttle_classes=[HogQLQueryThrottle])+ @extend_schema(+ description="Columns the subject's query returns, for authoring a check against them. Metrics only.",+ parameters=_SUBJECT_PARAMETERS,+ request=None,+ responses={200: DataQualityOutputSchemaSerializer},+ )+ @action(+ methods=["GET"],+ detail=False,+ url_path="output_schema",+ pagination_class=None,+ throttle_classes=[HogQLQueryThrottle],+ )def output_schema(self, request: Request, **kwargs) -> Response:+ subject = self._named_subject(request.query_params)+ self._require_subject(subject, write=False)+ if subject.subject_type != SubjectType.METRIC:+ raise ValidationError({"subject_type": "Only a metric has an output schema to read."})try:- columns = api.metric_output_schema(self.team, self.subject_uuid, cast(User, request.user))+ columns = api.metric_output_schema(self.team, subject.subject_uuid, cast(User, request.user))except (api.CheckConfigError, api.SubjectUnresolvableError) as error:raise ValidationError({"metric": str(error)})return Response(DataQualityOutputSchemaSerializer({"columns": columns}).data)- @extend_schema(methods=["GET"], request=None, responses={200: DataQualityCheckScheduleSerializer})+ @extend_schema(+ methods=["GET"],+ description="The schedule every enabled check on this subject runs on.",+ parameters=_SUBJECT_PARAMETERS,+ request=None,+ responses={200: DataQualityCheckScheduleSerializer},+ )@extend_schema(methods=["PATCH"],+ description="Change how often this subject's checks run, or stop running them automatically. "+ "Name the subject with subject_type and subject_uuid in the body.",request=DataQualityCheckScheduleUpdateSerializer,responses={200: DataQualityCheckScheduleSerializer},)@action(methods=["GET", "PATCH"], detail=False, pagination_class=None)def schedule(self, request: Request, **kwargs) -> Response:- if not self._subject_checks().exists():- raise NotFound("Add a check to create this metric's schedule.")+ writing = request.method == "PATCH"+ subject = self._named_subject(request.data if writing else request.query_params)+ self._require_subject(subject, write=writing)+ if subject.subject_type != SubjectType.METRIC:+ raise ValidationError(+ {"subject_type": f"A {subject.subject_type}'s checks run when its data changes, not on a schedule."}+ )+ if not self._scheduled_checks(subject).exists():+ raise NotFound("Add a check to create this subject's schedule.")authorization_context = self._denial_context() if self._can_be_object_denied() else None- if request.method == "PATCH":- self._require_enabled_check_access()- serializer = DataQualityCheckScheduleUpdateSerializer(data=request.data)- serializer.is_valid(raise_exception=True)+ if writing:+ self._require_enabled_check_access(subject)+ update = DataQualityCheckScheduleUpdateSerializer(data=request.data)+ update.is_valid(raise_exception=True)schedule: api.MetricCheckSchedule | Nonetry:- if request.method == "PATCH":+ if writing:schedule = api.update_schedule(self.team_id,- self.subject_type,- self.subject_uuid,+ SubjectType(subject.subject_type),+ subject.subject_uuid,user=cast(User, request.user),authorization_context=authorization_context,- **serializer.validated_data,+ **update.schedule_changes,)else:schedule = api.get_schedule_with_history(- self.team_id, self.subject_type, self.subject_uuid, authorization_context+ self.team_id, SubjectType(subject.subject_type), subject.subject_uuid, authorization_context)if schedule is None:raise api.ScheduleUnavailableError()@@ -627,42 +747,61 @@ class MetricCheckViewSet(_BaseCheckViewSet):raise ScheduleUnavailableAPIError() from errorreturn Response(DataQualityCheckScheduleSerializer(schedule).data)- def _subject_checks(self) -> QuerySet[DataQualityCheck]:- return DataQualityCheck.objects.for_team(self.team_id).filter(metric_id=self.subject_uuid)+ 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)-class _BaseSuiteRunViewSet(- _SubjectScopedViewSet,+@extend_schema_view(+ list=extend_schema(+ description="Every check-suite run in the project, newest first. Narrow it to one subject "+ "with subject_type and subject_uuid.",+ parameters=_SUBJECT_PARAMETERS,+ ),+)+class DataQualityRunViewSet(+ _ProjectQualityViewSet,mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet,):- """Read-only reports for this subject's check-suite executions."""+ """Check-suite executions: start one over a selection, and read every run the project has had.++ A suite run may sweep several subjects at once -- a manual project-wide run, a materialization,+ a source sync -- so it is reported here rather than under any one of them.+ """- QUERY_GATED_ACTIONS = frozenset({"list", "retrieve", "check_runs"})+ QUERY_GATED_ACTIONS = frozenset({"list", "retrieve", "create", "check_runs"})serializer_class = DataQualitySuiteRunSerializerqueryset = DataQualitySuiteRun.objects.unscoped()def safely_get_queryset(self, queryset: QuerySet[DataQualitySuiteRun]) -> QuerySet[DataQualitySuiteRun]:- # The parent lookup is rewritten onto subject_uuid, so this lists the parent's own- # single-subject suites. Multi-subject sweep suites stay reachable through- # information_schema, which is the cross-subject surface.- return queryset.filter(team_id=self.team_id).order_by("-created_at")+ queryset = queryset.filter(team_id=self.team_id).order_by("-created_at")+ if self.action != "list":+ return queryset+ subject = self._optional_subject(self.request.query_params)+ if subject is None:+ return queryset+ self._require_subject(subject, write=False)+ return queryset.filter(subject_type=subject.subject_type, subject_uuid=subject.subject_uuid)def filter_queryset(self, queryset: QuerySet[DataQualitySuiteRun]) -> QuerySet[DataQualitySuiteRun]:- """Withhold the suites whose executions read a subject the caller is denied.+ """Withhold the suites that report on a subject the caller is denied.++ A suite row carries its subject and its passed/failed/errored/skipped counters, so serving+ one is serving outcome counts over the rows behind it. Excluded in SQL rather than filtered+ per page, so the paginated count cannot report the withheld suites either.- The parent gate clears the declared subject, but a suite row carries passed/failed/errored/- skipped over every check it ran, while ``check_runs`` hands back only the readable ones.- Serving both names the withheld check's outcome by subtraction.+ ``check_runs`` is left alone on purpose: it already drops the individual runs that read a+ denied subject, and hiding the suite there would take the readable runs down with them."""queryset = super().filter_queryset(queryset)- # check_runs is left alone on purpose: it already drops the individual runs that read a- # denied subject, and hiding the suite there would take the readable runs down with them.- if self.action not in ("list", "retrieve"):+ if self.action == "check_runs":return querysetif not self._can_be_object_denied():return queryset+ # A suite with runs is withheld when any of them touched a subject out of reach, the same+ # rule the check routes apply. A suite that swept nothing has no run to gate on, so its own+ # subject gates it directly -- which is the only path that reaches an empty suite.context = self._denial_context()return queryset.exclude(api.unreadable_suites_q(context)).exclude(api.suites_backing_unreadable_runs_q(self.team_id, context)@@ -685,187 +824,9 @@ class _BaseSuiteRunViewSet()return Response(serializer.data)--def _parent_id_parameter(name: str, description: str) -> Callable[[type], type]:- # The suite-run model carries the parent as subject_uuid, so drf-spectacular cannot derive the- # nested path parameter's type from a model field; annotate it on every action instead.- parameter = OpenApiParameter(name, OpenApiTypes.UUID, OpenApiParameter.PATH, description=description)- schema = extend_schema(parameters=[parameter])- return extend_schema_view(list=schema, retrieve=schema, check_runs=schema)---@_parent_id_parameter("saved_query_id", "Id of the saved query whose suite runs these are.")-class SavedQuerySuiteRunViewSet(_BaseSuiteRunViewSet, AccessControlViewSetMixin):- scope_object = "warehouse_view"- subject_type = SubjectType.VIEW- subject_field = "saved_query"- filter_rewrite_rules = {"saved_query_id": "subject_uuid"}---@_parent_id_parameter("table_id", "Id of the warehouse table whose suite runs these are.")-class TableSuiteRunViewSet(_BaseSuiteRunViewSet, AccessControlViewSetMixin):- scope_object = "warehouse_table"- subject_type = SubjectType.TABLE- subject_field = "table"- filter_rewrite_rules = {"table_id": "subject_uuid"}---@_parent_id_parameter("metric_id", "Id of the metric whose suite runs these are.")-class MetricSuiteRunViewSet(_BaseSuiteRunViewSet):- scope_object = "data_catalog"- subject_type = SubjectType.METRIC- subject_field = "metric"- filter_rewrite_rules = {"metric_id": "subject_uuid"}---class _ProjectQualityViewSet(_QualityGatedViewSet):- scope_object = "query"-- def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str]:- return ["query:read"]-- def initial(self, request: Request, *args, **kwargs) -> None:- super().initial(request, *args, **kwargs)- if not self._authorized_subject_types(write=request.method not in SAFE_METHODS):- raise PermissionDenied("You need access to warehouse objects or the data catalog to work with checks.")---class DataQualityCheckOverviewViewSet(- _ProjectQualityViewSet,- mixins.ListModelMixin,- viewsets.GenericViewSet,-):- """Every check in the project, and the health of every subject that has one.-- The per-subject surfaces answer "what is wrong with this table". This answers "what is wrong- across the project", which they cannot: each is nested under one parent. Read-only -- authoring- still happens against the subject that owns the check.- """-- QUERY_GATED_ACTIONS = frozenset({"list", "health", "metric_subjects"})- serializer_class = DataQualityOverviewCheckSerializer- queryset = DataQualityCheck.objects.unscoped()-- def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str]:- if getattr(view, "action", None) == "metric_subjects":- return ["data_catalog:read", "query:read"]- return super().dangerously_get_required_scopes(request, view)-- @extend_schema(request=None, responses={200: DataQualityMetricSubjectSerializer(many=True)})- @action(methods=["GET"], detail=False, pagination_class=None)- def metric_subjects(self, request: Request, **kwargs) -> Response:- if not self.user_access_control.check_access_level_for_resource("data_catalog", "viewer"):- raise PermissionDenied("You need data catalog access to create checks on metrics.")- metrics = api.testable_metric_subjects(self.team_id)- if self._can_be_object_denied():- readable_ids = self._denial_context().readable.metric_ids- metrics = [metric for metric in metrics if metric.id in readable_ids]- return Response(DataQualityMetricSubjectSerializer(metrics, many=True).data)-- def safely_get_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:- # Orphans are excluded: their subject is gone, so there is no page to link to, nothing to- # run, and no rollup to sit under. The run history they left behind stays queryable.- # The rollup reads four columns of every enabled check in the project and serializes none of- # the people, so it does not pay for the author join the listing needs.- queryset = (- api.live_subject_checks(queryset.filter(team_id=self.team_id, deleted=False))- .exclude(subject_status=SubjectStatus.ORPHANED)- .order_by("subject_name", "name")- )- return queryset.select_related("created_by", "owner") if self.action == "list" else queryset-- def list(self, request: Request, *args, **kwargs) -> Response:- queryset = self.filter_queryset(self.get_queryset())- page = self.paginate_queryset(queryset)- checks = list(queryset) if page is None else page- # Resolved once for the page, so linking to a subject costs two queries rather than one per- # check. Anything the batch cannot resolve stays absent and renders as plain text.- context = {**self.get_serializer_context(), "subject_locations": api.subject_locations(self.team_id, checks)}- serializer = self.get_serializer(checks, many=True, context=context)- return self.get_paginated_response(serializer.data) if page is not None else Response(serializer.data)-- def filter_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:- # Hiding a denied subject's checks matters more here than on the nested surfaces: this one- # lists everything, so a leak is a directory of the tables a member cannot read. Denial is- # matched by name rather than equality, so the pass has to happen in Python; only a- # restricted member pays for it, since the denied set is empty for everyone else.- queryset = super().filter_queryset(queryset)- if not self._can_be_object_denied():- return queryset- return api.visible_check_queryset(self.team_id, queryset, self._denial_context())-@extend_schema(- description="Health rollup for every table and view in the project that has checks.",- responses={200: SubjectHealthSerializer(many=True)},- )- @action(methods=["GET"], detail=False, pagination_class=None)- def health(self, request: Request, **kwargs) -> Response:- # Rolled up from the checks already loaded, using the same rule as the per-subject endpoint.- # Calling subject_health() per subject would be a query per table.- by_subject: dict[tuple[str, str], list[DataQualityCheck]] = defaultdict(list)- for check in self.filter_queryset(self.get_queryset()).filter(enabled=True):- if check.subject_uuid is None:- # An orphan has no subject left to roll up under.- continue- by_subject[(check.subject_type, str(check.subject_uuid))].append(check)-- rollups = [- {- "subject_type": subject_type,- "subject_uuid": subject_uuid,- "health": api.roll_up_health(- api.CheckStatusRow(severity=check.severity, last_status=check.last_status) for check in checks- ),- "checks_total": len(checks),- "checks_failing": sum(1 for check in checks if check.last_status == CheckRunStatus.FAILED),- }- for (subject_type, subject_uuid), checks in by_subject.items()- ]- return Response(SubjectHealthSerializer(rollups, many=True).data)---class DataQualityRunViewSet(- _ProjectQualityViewSet,- mixins.ListModelMixin,- mixins.RetrieveModelMixin,- viewsets.GenericViewSet,-):- """Project-wide check runs: start one over a selection, and read every run the project has had.-- The per-subject surfaces only serve runs scoped to their own subject, so this is where a sweep- across several subjects -- a manual project-wide run, a materialization, a source sync -- is- readable. Scoped to `warehouse_objects` because it spans tables and views at once.- """-- QUERY_GATED_ACTIONS = frozenset({"list", "retrieve", "create"})- serializer_class = DataQualitySuiteRunSerializer- queryset = DataQualitySuiteRun.objects.unscoped()-- def safely_get_queryset(self, queryset: QuerySet[DataQualitySuiteRun]) -> QuerySet[DataQualitySuiteRun]:- return queryset.filter(team_id=self.team_id).order_by("-created_at")-- def filter_queryset(self, queryset: QuerySet[DataQualitySuiteRun]) -> QuerySet[DataQualitySuiteRun]:- """Withhold the suites that report on a subject the caller is denied.-- A suite row carries its subject and its passed/failed/errored/skipped counters, so serving- one is serving outcome counts over the rows behind it. The nested suite lists are gated by- their parent; this one spans every subject and has no parent to gate on. Excluded in SQL- rather than filtered per page, so the paginated count cannot report the withheld suites- either.- """- queryset = super().filter_queryset(queryset)- if not self._can_be_object_denied():- return queryset- # A suite with runs is withheld when any of them touched a subject out of reach, the same- # rule the check routes apply. A suite that swept nothing has no run to gate on, so its own- # subject gates it directly -- which is the only path that reaches an empty suite.- context = self._denial_context()- return queryset.exclude(api.unreadable_suites_q(context)).exclude(- api.suites_backing_unreadable_runs_q(self.team_id, context)- )-- @extend_schema(- description="Run the named checks now, or every enabled check in the project when none are named. "+ description="Run checks now: the ones named by check_ids, every enabled check on the subject named by "+ "subject_type and subject_uuid, or every enabled check in the project when neither is given. ""Returns the suite run to poll for the report.",request=DataQualityRunRequestSerializer,responses={200: DataQualitySuiteRunSerializer},@@ -874,6 +835,9 @@ class DataQualityRunViewSet(serializer = DataQualityRunRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)requested = [str(check_id) for check_id in serializer.validated_data.get("check_ids") or []]+ subject = self._optional_subject(serializer.validated_data)+ if subject is not None and not requested:+ return Response(self._run_subject(subject, cast(User, request.user)))runnable = api.live_subject_checks(DataQualityCheck.objects.for_team(self.team_id).filter(deleted=False, enabled=True)@@ -895,6 +859,22 @@ class DataQualityRunViewSet()return Response(DataQualitySuiteRunSerializer(suite_run).data)+ def _run_subject(self, subject: api.SubjectIdentity, user: User) -> dict:+ """Run every enabled check on one subject, stamping the suite with it so it reads back scoped.++ Pointing at a subject is naming what to run, so a check on it the caller may not reach is a+ 403 rather than something quietly dropped.+ """+ self._require_subject(subject, write=True)+ self._require_enabled_check_access(subject)+ suite_run = api.start_check_suite(+ team=self.team,+ user=user,+ subject_type=subject.subject_type,+ subject_uuids=[subject.subject_uuid],+ )+ return DataQualitySuiteRunSerializer(suite_run).data+def _authorized_checks(self, checks: list[DataQualityCheck], named: bool) -> list[DataQualityCheck]:"""Drop, or reject, the checks this member may not run.diff --git a/products/data_quality/backend/routes.py b/products/data_quality/backend/routes.pyindex 034d3e730301..5b215c2e2a6f 100644--- a/products/data_quality/backend/routes.py+++ b/products/data_quality/backend/routes.py@@ -1,12 +1,10 @@from posthog.api.routing import RouterRegistry-from products.data_quality.backend.presentation.views import DataQualityCheckOverviewViewSet, DataQualityRunViewSet+from products.data_quality.backend.presentation.views import DataQualityCheckViewSet, DataQualityRunViewSetdef register_routes(routers: RouterRegistry) -> None:- # The per-subject check surfaces are nested under their warehouse parent and registered by the- # data_warehouse product. This one spans every subject, so it hangs off the project directly.routers.projects.register(- r"data_quality_checks", DataQualityCheckOverviewViewSet, "project_data_quality_checks", ["team_id"]+ r"data_quality_checks", DataQualityCheckViewSet, "project_data_quality_checks", ["team_id"])routers.projects.register(r"data_quality_runs", DataQualityRunViewSet, "project_data_quality_runs", ["team_id"])diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex 3eb083cad8df..7549928995d0 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -17,6 +17,8 @@ from posthog.hogql.database.database import Databasefrom posthog.constants import AvailableFeaturefrom posthog.models.activity_logging.activity_log import ActivityLog, Detail, log_activity+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.access_control.backend.models.access_control import AccessControlfrom products.data_catalog.backend.facade.models import Metric@@ -28,7 +30,7 @@ from products.data_quality.backend.logic.metric_schedules import MetricScheduleKfrom products.data_quality.backend.logic.runner import run_checkfrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom products.data_quality.backend.presentation.serializers import DataQualitySuiteRunSerializer-from products.data_quality.backend.presentation.views import SavedQueryCheckViewSet+from products.data_quality.backend.presentation.views import DataQualityCheckViewSetfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -54,8 +56,10 @@ class TestMetricCheckAPI(APIBaseTest):self.temporal = schedule_client()self.connect = AsyncMock(return_value=self.temporal)self.enterContext(patch("products.data_quality.backend.logic.schedules.async_connect", self.connect))- self.url = f"/api/projects/{self.team.id}/data_catalog/metrics/{self.metric.id}/checks"- self.suites_url = f"/api/projects/{self.team.id}/data_catalog/metrics/{self.metric.id}/check_suite_runs"+ self.url = f"/api/projects/{self.team.id}/data_quality_checks"+ self.suites_url = f"/api/projects/{self.team.id}/data_quality_runs"+ self.subject = {"subject_type": "metric", "subject_uuid": str(self.metric.id)}+ self.subject_query = f"subject_type=metric&subject_uuid={self.metric.id}"flag = patch(FLAG, return_value=True)flag.start()self.addCleanup(flag.stop)@@ -64,30 +68,34 @@ class TestMetricCheckAPI(APIBaseTest):with self.captureOnCommitCallbacks(execute=True):response = self.client.post(f"{self.url}/",- {"check_type": "custom_sql", "config": {"query": "SELECT * FROM {metric} WHERE signups < 100"}},+ {+ **self.subject,+ "check_type": "custom_sql",+ "config": {"query": "SELECT * FROM {metric} WHERE signups < 100"},+ },)assert response.status_code == 201, response.contentreturn response.json()@parameterized.expand([- ("checks_list", "get", "checks/"),- ("checks_schedule", "get", "checks/schedule/"),- ("checks_health", "get", "checks/health/"),- ("checks_run_all", "post", "checks/run_all/"),- ("suite_runs_list", "get", "check_suite_runs/"),+ ("list", "get", ""),+ ("health", "get", "health/"),+ ("schedule", "get", "schedule/"),+ ("output_schema", "get", "output_schema/"),])- def test_metric_name_in_the_id_segment_is_not_found(self, _name: str, method: str, suffix: str) -> None:- # Metrics have their own routes that address them by name, so a caller can land a name in a- # segment these routes read as a uuid.- url = f"/api/projects/{self.team.id}/data_catalog/metrics/{self.metric.name}/{suffix}"-- response = getattr(self.client, method)(url)+ def test_a_subject_named_by_something_other_than_a_uuid_is_rejected(+ self, _name: str, method: str, suffix: str+ ) -> None:+ response = getattr(self.client, method)(+ f"{self.url}/{suffix}?subject_type=metric&subject_uuid={self.metric.name}"+ )- assert response.status_code == status.HTTP_404_NOT_FOUND, response.content+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "subject_uuid" in response.json()["attr"]- def test_metric_children_do_not_expose_access_control_actions(self) -> None:+ def test_checks_do_not_expose_access_control_actions(self) -> None:check = self._create()suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team,@@ -129,21 +137,23 @@ class TestMetricCheckAPI(APIBaseTest):"posthog.hogql.database.database.feature_enabled_or_false",side_effect=lambda name, *a, **k: name == "hogql-warehouse-access-control",):- response = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour"})+ response = self.client.patch(f"{self.url}/schedule/", {**self.subject, "interval": "6hour"})assert response.status_code == 403, response.contentschedule = api.get_schedule(self.team.id, "metric", self.metric.id)assert schedule is not Noneassert schedule.interval == "24hour"def test_metric_check_authoring_schedule_and_overview(self) -> None:- assert self.client.get(f"{self.url}/schedule/").status_code == 404- assert self.client.patch(f"{self.url}/schedule/", {"enabled": False}).status_code == 404+ assert self.client.get(f"{self.url}/schedule/?{self.subject_query}").status_code == 404+ assert self.client.patch(f"{self.url}/schedule/", {**self.subject, "enabled": False}).status_code == 404check = self._create()- assert [entry["check_type"] for entry in self.client.get(f"{self.url}/check_types/").json()] == ["custom_sql"]- assert self.client.get(f"{self.url}/").json()["results"][0]["id"] == check["id"]- schedule = self.client.get(f"{self.url}/schedule/").json()+ assert [+ entry["check_type"] for entry in self.client.get(f"{self.url}/check_types/?subject_type=metric").json()+ ] == ["custom_sql"]+ assert self.client.get(f"{self.url}/?{self.subject_query}").json()["results"][0]["id"] == check["id"]+ schedule = self.client.get(f"{self.url}/schedule/?{self.subject_query}").json()assert schedule["interval"] == "24hour"- patched = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour", "enabled": False})+ patched = self.client.patch(f"{self.url}/schedule/", {**self.subject, "interval": "6hour", "enabled": False})assert patched.status_code == 200assert patched.json()["interval"] == "6hour"assert patched.json()["enabled"] is False@@ -158,13 +168,13 @@ class TestMetricCheckAPI(APIBaseTest):assert row["subject_metric_name"] == "registrations"assert "definition" not in row and "values" not in rowassert self.client.delete(f"{self.url}/{check['id']}/").status_code == 204- assert self.client.get(f"{self.url}/schedule/").status_code == 200+ assert self.client.get(f"{self.url}/schedule/?{self.subject_query}").status_code == 200def test_schedule_patch_reuses_one_connection_and_records_snapshots(self) -> None:self._create()self.connect.reset_mock()- response = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour", "enabled": False})+ response = self.client.patch(f"{self.url}/schedule/", {**self.subject, "interval": "6hour", "enabled": False})assert response.status_code == status.HTTP_200_OK, response.contentassert response.json()["interval"] == "6hour"@@ -217,9 +227,11 @@ class TestMetricCheckAPI(APIBaseTest):failure = patch.object(MetricSchedules, "describe", cast(AsyncMock, missing_after_update))with failure:- response = self.client.patch(f"{self.url}/schedule/", {"enabled": False})+ response = self.client.patch(f"{self.url}/schedule/", {**self.subject, "enabled": False})assert response.status_code == 503- assert self.client.get(f"{self.url}/schedule/").json()["enabled"] is (phase != "read_after")+ assert self.client.get(f"{self.url}/schedule/?{self.subject_query}").json()["enabled"] is (+ phase != "read_after"+ )def test_schedule_history_excludes_manual_suites(self) -> None:self._create()@@ -229,7 +241,7 @@ class TestMetricCheckAPI(APIBaseTest):DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual", subject_type=SubjectType.METRIC, subject_uuid=self.metric.id)- schedule = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour"}).json()+ schedule = self.client.patch(f"{self.url}/schedule/", {**self.subject, "interval": "6hour"}).json()assert schedule["last_suite_run"] == str(scheduled.id)def test_schedule_history_hides_a_suite_with_revoked_reference_access(self) -> None:@@ -252,7 +264,7 @@ class TestMetricCheckAPI(APIBaseTest):)self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]self.organization.save(update_fields=["available_product_features"])- assert self.client.get(f"{self.url}/schedule/").json()["last_suite_run"] == str(suite.id)+ assert self.client.get(f"{self.url}/schedule/?{self.subject_query}").json()["last_suite_run"] == str(suite.id)AccessControl.objects.create(team=self.team,resource="warehouse_view",@@ -261,7 +273,7 @@ class TestMetricCheckAPI(APIBaseTest):access_level="none",)cache.clear()- schedule = self.client.patch(f"{self.url}/schedule/", {"interval": "6hour"}).json()+ schedule = self.client.patch(f"{self.url}/schedule/", {**self.subject, "interval": "6hour"}).json()assert schedule["last_suite_run"] is Noneassert schedule["last_run_at"] is None@@ -331,9 +343,9 @@ class TestMetricCheckAPI(APIBaseTest):access_level="none",)cache.clear()- assert self.client.get(f"{self.url}/").status_code == 403- assert self.client.get(f"{self.url}/schedule/").status_code == 403- assert self.client.get(f"{self.suites_url}/").status_code == 403+ assert self.client.get(f"{self.url}/?{self.subject_query}").status_code == 403+ assert self.client.get(f"{self.url}/schedule/?{self.subject_query}").status_code == 403+ assert self.client.get(f"{self.suites_url}/?{self.subject_query}").status_code == 403assert self.client.get(f"/api/projects/{self.team.id}/data_quality_checks/").json()["results"] == []@parameterized.expand([("check_assertion", False), ("metric_definition", True)])@@ -366,7 +378,7 @@ class TestMetricCheckAPI(APIBaseTest):)cache.clear()- for url in (f"{self.url}/", f"/api/projects/{self.team.id}/data_quality_checks/"):+ for url in (f"{self.url}/?{self.subject_query}", f"{self.url}/"):listed = self.client.get(url)assert listed.status_code == status.HTTP_200_OK, listed.contentassert listed.json()["results"] == []@@ -402,6 +414,7 @@ class TestMetricCheckAPI(APIBaseTest):response = self.client.post(f"{self.url}/",{+ **self.subject,"check_type": "custom_sql","config": {"query": "SELECT * FROM {metric}"},},@@ -478,24 +491,24 @@ class TestMetricCheckAPI(APIBaseTest):warehouse_ac.start()self.addCleanup(warehouse_ac.stop)cache.clear()- suffix = action if action == "run_all" else f"{check['id']}/{action}"with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):- response = getattr(self.client, method.lower())(f"{self.url}/{suffix}/")+ if action == "run_all":+ response = self.client.post(f"{self.suites_url}/", self.subject)+ else:+ response = getattr(self.client, method.lower())(f"{self.url}/{check['id']}/{action}/")assert response.status_code == (403 if denied else 200), response.contentclass TestCheckViewSetScopes(SimpleTestCase):@parameterized.expand([- ("query_gated_read", "list", "GET", ["warehouse_view:read", "query:read"]),- ("query_gated_write", "create", "POST", ["warehouse_view:write", "query:read"]),- ("inherited_access_control", "users_with_access", "GET", ["access_control:read"]),+ ("read", "list", "GET", ["query:read"]),+ ("write", "create", "POST", ["query:read"]),+ ("metric_catalog", "metric_subjects", "GET", ["data_catalog:read", "query:read"]),])def test_required_scopes_per_action(self, _name: str, action: str, method: str, expected: list[str]) -> None:- # The query gate is this viewset's own scope rule; everything else has to keep deferring, or the- # access-control actions it inherits would answer to a warehouse token with no access_control scope.- view = SavedQueryCheckViewSet()+ view = DataQualityCheckViewSet()view.action = actionassert view.dangerously_get_required_scopes(APIRequestFactory().generic(method, "/"), view) == expected@@ -519,7 +532,8 @@ class TestMetricOutputSchemaAPI(ClickhouseTestMixin, APIBaseTest):def test_returns_the_saved_metrics_output_columns_and_types(self) -> None:response = self.client.get(- f"/api/projects/{self.team.id}/data_catalog/metrics/{self.metric.id}/checks/output_schema/"+ f"/api/projects/{self.team.id}/data_quality_checks/output_schema/"+ f"?subject_type=metric&subject_uuid={self.metric.id}")assert response.status_code == status.HTTP_200_OK, response.content@@ -537,7 +551,9 @@ class TestDataQualityCheckAPI(APIBaseTest):self.view = DataWarehouseSavedQuery.objects.create(team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS customer_id"})- self.url = self._checks_url(self.view.id)+ self.url = f"/api/projects/{self.team.id}/data_quality_checks"+ self.suites_url = f"/api/projects/{self.team.id}/data_quality_runs"+ self.subject = {"subject_type": SubjectType.VIEW, "subject_uuid": str(self.view.id)}flag = patch(FLAG, return_value=True)flag.start()self.addCleanup(flag.stop)@@ -547,7 +563,7 @@ class TestDataQualityCheckAPI(APIBaseTest):other_view = DataWarehouseSavedQuery.objects.create(team=self.team, name="other_orders", query={"kind": "HogQLQuery", "query": "SELECT 1"})- other_check = self._create_check(url=self._checks_url(other_view.id))+ other_check = self._create_check(subject_uuid=str(other_view.id))for item_id, scope in [(self.view.id, "DataWarehouseSavedQuery"),(check.id, "DataQualityCheck"),@@ -597,17 +613,22 @@ class TestDataQualityCheckAPI(APIBaseTest):assert entry is not Noneassert entry.activity == "deleted"- def _checks_url(self, saved_query_id) -> str:- return f"/api/projects/{self.team.id}/warehouse_saved_queries/{saved_query_id}/checks"+ def _subject_query(self, subject_uuid, subject_type: str = SubjectType.VIEW) -> str:+ return f"subject_type={subject_type}&subject_uuid={subject_uuid}"++ def _subject_of(self, subject_uuid, subject_type: str = SubjectType.VIEW) -> dict:+ return {"subject_type": subject_type, "subject_uuid": str(subject_uuid)}- def _suite_runs_url(self, saved_query_id=None) -> str:- parent = saved_query_id or self.view.id- return f"/api/projects/{self.team.id}/warehouse_saved_queries/{parent}/check_suite_runs"+ def _checks_of(self, subject_uuid, subject_type: str = SubjectType.VIEW) -> str:+ return f"{self.url}/?{self._subject_query(subject_uuid, subject_type)}"++ def _runs_of(self, subject_uuid, subject_type: str = SubjectType.VIEW) -> str:+ return f"{self.suites_url}/?{self._subject_query(subject_uuid, subject_type)}"def _gate_url(self) -> str:return f"/api/projects/{self.team.id}/data_warehouse/data_quality_gate/"- def _table_checks_url(self) -> str:+ def _table_subject(self) -> dict:credential = DataWarehouseCredential.objects.create(team=self.team, access_key="_key", access_secret="_secret")table = DataWarehouseTable.objects.create(name="orders_source",@@ -617,17 +638,18 @@ class TestDataQualityCheckAPI(APIBaseTest):format=DataWarehouseTable.TableFormat.Parquet,url_pattern="http://localhost:19000/bucket/orders_source",)- return f"/api/projects/{self.team.id}/warehouse_tables/{table.id}/checks"+ return self._subject_of(table.id, SubjectType.TABLE)def _payload(self, **overrides) -> dict:return {+ **self.subject,"check_type": CheckType.NOT_NULL,"column_name": "customer_id",**overrides,}- def _create_check(self, url: str | None = None, **overrides) -> DataQualityCheck:- response = self.client.post(f"{url or self.url}/", self._payload(**overrides))+ def _create_check(self, **overrides) -> DataQualityCheck:+ response = self.client.post(f"{self.url}/", self._payload(**overrides))assert response.status_code == status.HTTP_201_CREATED, response.json()return DataQualityCheck.objects.for_team(self.team.id).get(id=response.json()["id"])@@ -648,12 +670,12 @@ class TestDataQualityCheckAPI(APIBaseTest):@parameterized.expand([("view",), ("table",)])def test_create_returns_the_fingerprint_and_re_creating_upserts(self, kind: str) -> None:- url = self.url if kind == "view" else self._table_checks_url()- created = self.client.post(f"{url}/", self._payload())+ subject = self.subject if kind == "view" else self._table_subject()+ created = self.client.post(f"{self.url}/", self._payload(**subject))assert created.status_code == status.HTTP_201_CREATED, created.json()assert created.json()["fingerprint"]- again = self.client.post(f"{url}/", self._payload(description="clarified"))+ again = self.client.post(f"{self.url}/", self._payload(**subject, description="clarified"))assert again.status_code == status.HTTP_200_OKassert again.json()["id"] == created.json()["id"]@@ -678,7 +700,7 @@ class TestDataQualityCheckAPI(APIBaseTest):assert DataQualityCheck.objects.for_team(self.team.id).count() == 0def test_creating_under_an_unknown_parent_is_rejected(self) -> None:- response = self.client.post(f"{self._checks_url(uuid4())}/", self._payload())+ response = self.client.post(f"{self.url}/", self._payload(subject_uuid=str(uuid4())))assert response.status_code == status.HTTP_400_BAD_REQUESTassert DataQualityCheck.objects.for_team(self.team.id).count() == 0@@ -740,14 +762,14 @@ class TestDataQualityCheckAPI(APIBaseTest):])def test_editing_the_assertion_keeps_the_check_identity(self, kind: str, _case: str, edit: dict) -> None:- url = self.url if kind == "view" else self._table_checks_url()- check = self._create_check(url=url)+ subject = self.subject if kind == "view" else self._table_subject()+ check = self._create_check(**subject)ran_at = now()DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(last_status=CheckRunStatus.FAILED, last_run_at=ran_at)- response = self.client.patch(f"{url}/{check.id}/", edit)+ response = self.client.patch(f"{self.url}/{check.id}/", edit)assert response.status_code == status.HTTP_200_OK, response.json()body = response.json()@@ -962,22 +984,36 @@ class TestDataQualityCheckAPI(APIBaseTest):assert check.deleted is Trueassert check.enabled is False- def test_list_is_scoped_to_the_parent_and_filters_by_check_type(self) -> None:+ def test_list_narrows_by_subject_and_by_check_type(self) -> None:self._create_check()self._create_check(check_type=CheckType.UNIQUE)other_view = self._make_view("refunds")- other = self.client.post(f"{self._checks_url(other_view.id)}/", self._payload())+ other = self.client.post(f"{self.url}/", self._payload(subject_uuid=str(other_view.id)))assert other.status_code == status.HTTP_201_CREATED- listed = self.client.get(f"{self.url}/")- filtered = self.client.get(f"{self.url}/?check_type={CheckType.UNIQUE}")+ everything = self.client.get(f"{self.url}/")+ scoped = self.client.get(self._checks_of(self.view.id))+ filtered = self.client.get(f"{self._checks_of(self.view.id)}&check_type={CheckType.UNIQUE}")- assert {row["subject_uuid"] for row in listed.json()["results"]} == {str(self.view.id)}- assert len(listed.json()["results"]) == 2+ assert len(everything.json()["results"]) == 3+ assert {row["subject_uuid"] for row in scoped.json()["results"]} == {str(self.view.id)}+ assert len(scoped.json()["results"]) == 2assert [row["check_type"] for row in filtered.json()["results"]] == [CheckType.UNIQUE]+ def test_unnamed_checks_on_one_subject_come_back_newest_first(self) -> None:+ # A name is optional, so most checks on a subject sort on the same blank value. Without a+ # tiebreak the page a caller receives is whatever order the database happened to return.+ oldest = self._create_check(column_name="a")+ middle = self._create_check(column_name="b")+ newest = self._create_check(column_name="c")++ listed = self.client.get(self._checks_of(self.view.id))++ assert listed.status_code == status.HTTP_200_OK, listed.json()+ assert [row["id"] for row in listed.json()["results"]] == [str(newest.id), str(middle.id), str(oldest.id)]+def test_check_types_exposes_a_config_schema_per_type(self) -> None:- response = self.client.get(f"{self.url}/check_types/")+ response = self.client.get(f"{self.url}/check_types/?subject_type={SubjectType.VIEW}")assert response.status_code == status.HTTP_200_OKby_type = {row["check_type"]: row for row in response.json()}@@ -1028,11 +1064,12 @@ class TestDataQualityCheckAPI(APIBaseTest):last_status=last_status,)- response = self.client.get(f"{self.url}/health/")+ response = self.client.get(f"{self.url}/health/?{self._subject_query(self.view.id)}")assert response.status_code == status.HTTP_200_OK- assert response.json()["health"] == expected- assert response.json()["checks_total"] == len(states)+ rollups = response.json()+ assert [entry["health"] for entry in rollups] == ([expected] if states else [])+ assert sum(entry["checks_total"] for entry in rollups) == len(states)def test_health_ignores_disabled_checks(self) -> None:# A disabled failing check must not drive the verdict, or health would read 'failing' while@@ -1056,12 +1093,18 @@ class TestDataQualityCheckAPI(APIBaseTest):**common,)- response = self.client.get(f"{self.url}/health/")+ response = self.client.get(f"{self.url}/health/?{self._subject_query(self.view.id)}")assert response.status_code == status.HTTP_200_OK- assert response.json()["health"] == "healthy"- assert response.json()["checks_total"] == 1- assert response.json()["checks_failing"] == 0+ assert response.json() == [+ {+ "subject_type": SubjectType.VIEW,+ "subject_uuid": str(self.view.id),+ "health": "healthy",+ "checks_total": 1,+ "checks_failing": 0,+ }+ ]def test_run_returns_a_pollable_suite_run(self) -> None:check = self._create_check()@@ -1074,23 +1117,21 @@ class TestDataQualityCheckAPI(APIBaseTest):assert suite_run.status == "running"assert response.json()["workflow_id"] == suite_run.workflow_id# The handle is only pollable if it carries the subject: the nested routes filter on it.- polled = self.client.get(f"{self._suite_runs_url()}/{suite_run.id}/")+ polled = self.client.get(f"{self.suites_url}/{suite_run.id}/")assert polled.status_code == status.HTTP_200_OK- listed = self.client.get(f"{self._suite_runs_url()}/")+ listed = self.client.get(self._runs_of(self.view.id))assert str(suite_run.id) in {row["id"] for row in listed.json()["results"]}- def test_run_all_records_the_subject_on_the_report(self) -> None:+ def test_running_a_whole_subject_records_it_on_the_report(self) -> None:self._create_check()with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):- response = self.client.post(f"{self.url}/run_all/")+ response = self.client.post(f"{self.suites_url}/", self.subject)assert response.status_code == status.HTTP_200_OKassert response.json()["subject_uuid"] == str(self.view.id)- def test_suite_runs_list_the_parents_single_subject_suites(self) -> None:- # Multi-subject sweep suites carry no parent, so this surface must not serve them -- they- # stay reachable through information_schema, the cross-subject surface.+ def test_a_subject_filter_leaves_out_the_sweeps_that_span_several(self) -> None:mine = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=self.view.id)@@ -1107,12 +1148,12 @@ class TestDataQualityCheckAPI(APIBaseTest):failed_row_count=3,)- base = self._suite_runs_url()- listed = self.client.get(f"{base}/")+ listed = self.client.get(self._runs_of(self.view.id))assert {row["id"] for row in listed.json()["results"]} == {str(mine.id)}- assert self.client.get(f"{base}/{sweep.id}/").status_code == status.HTTP_404_NOT_FOUND- check_runs = self.client.get(f"{base}/{mine.id}/check_runs/")+ unfiltered = self.client.get(f"{self.suites_url}/")+ assert {row["id"] for row in unfiltered.json()["results"]} == {str(mine.id), str(sweep.id)}+ check_runs = self.client.get(f"{self.suites_url}/{mine.id}/check_runs/")assert [row["subject_name"] for row in check_runs.json()] == ["orders"]def test_check_runs_name_the_check_each_row_ran(self) -> None:@@ -1133,7 +1174,7 @@ class TestDataQualityCheckAPI(APIBaseTest):status=CheckRunStatus.PASSED,)- response = self.client.get(f"{self._suite_runs_url()}/{suite.id}/check_runs/")+ response = self.client.get(f"{self.suites_url}/{suite.id}/check_runs/")assert response.status_code == status.HTTP_200_OKassert {row["check_name"] for row in response.json()} == {"orders_customer_id_not_null", None}@@ -1153,7 +1194,7 @@ class TestDataQualityCheckAPI(APIBaseTest):)self._deny_the_view()- listed = self.client.get(f"{self._checks_url(allowed.id)}/")+ listed = self.client.get(self._checks_of(allowed.id))assert listed.status_code == status.HTTP_200_OK, listed.json()assert listed.json()["results"] == []@@ -1174,12 +1215,10 @@ class TestDataQualityCheckAPI(APIBaseTest):)self._deny_the_view()- health = self.client.get(f"{self._checks_url(allowed.id)}/health/")+ health = self.client.get(f"{self.url}/health/?{self._subject_query(allowed.id)}")assert health.status_code == status.HTTP_200_OK, health.json()- assert health.json()["checks_total"] == 0- assert health.json()["checks_failing"] == 0- assert health.json()["health"] == "unknown"+ assert health.json() == []@parameterized.expand([("pinned", True), ("recorded before pinning", False)])def test_editing_a_check_does_not_unlock_the_history_it_used_to_read(self, _name: str, pinned: bool) -> None:@@ -1220,7 +1259,7 @@ class TestDataQualityCheckAPI(APIBaseTest):last_succeeded_at=ran_at,failing_since=ran_at,)- url = f"{self._checks_url(allowed.id)}/{check.id}"+ url = f"{self.url}/{check.id}"authorized_edit = self.client.patch(url + "/", {"config": {"query": "SELECT 1 FROM customers"}})assert authorized_edit.status_code == status.HTTP_200_OK, authorized_edit.json()self._deny_the_view()@@ -1247,7 +1286,7 @@ class TestDataQualityCheckAPI(APIBaseTest):# "orders" -- one that list hides, retrieve 403s, runs/ empties and patch redacts.allowed = self._make_view("customers")safe = {"check_type": CheckType.NOT_NULL, "column_name": "id", "config": {}}- created = self.client.post(f"{self._checks_url(allowed.id)}/", safe)+ created = self.client.post(f"{self.url}/", {**self._subject_of(allowed.id), **safe})assert created.status_code == status.HTTP_201_CREATED, created.json()check = DataQualityCheck.objects.for_team(self.team.id).get(id=created.json()["id"])api.record_check_run(@@ -1274,7 +1313,7 @@ class TestDataQualityCheckAPI(APIBaseTest):)self._deny_the_view()- recreated = self.client.post(f"{self._checks_url(allowed.id)}/", safe)+ recreated = self.client.post(f"{self.url}/", {**self._subject_of(allowed.id), **safe})assert recreated.status_code == status.HTTP_200_OK, recreated.json()assert recreated.json()["last_status"] is None@@ -1292,8 +1331,13 @@ class TestDataQualityCheckAPI(APIBaseTest):DataWarehouseSavedQuery.objects.filter(id=view.id).update(columns={"amount": "Nullable(Int64)"})response = self.client.post(- f"{self._checks_url(view.id)}/",- {"check_type": CheckType.ACCEPTED_VALUES, "column_name": "amount", "config": {"values": ["1", "2"]}},+ f"{self.url}/",+ self._payload(+ subject_uuid=str(view.id),+ check_type=CheckType.ACCEPTED_VALUES,+ column_name="amount",+ config={"values": ["1", "2"]},+ ),)assert response.status_code == status.HTTP_201_CREATED, response.json()@@ -1305,7 +1349,7 @@ class TestDataQualityCheckAPI(APIBaseTest):# database sees it -- so denied_subject_names() picks it up and the endpoint hides it.self._deny_object("warehouse_view", str(self.view.id))- def _deny_object(self, resource: str, resource_id: str) -> None:+ def _deny_object(self, resource: str, resource_id: str, access_level: str = "none") -> None:self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}]@@ -1315,7 +1359,7 @@ class TestDataQualityCheckAPI(APIBaseTest):resource=resource,resource_id=resource_id,organization_member=self.organization_membership,- access_level="none",+ access_level=access_level,)# Warehouse table/view denial only flows into the HogQL database behind this flag.warehouse_ac = patch(@@ -1326,9 +1370,35 @@ class TestDataQualityCheckAPI(APIBaseTest):self.addCleanup(warehouse_ac.stop)cache.clear()+ def test_the_catalog_lists_a_subject_the_member_may_only_read_as_not_editable(self) -> None:+ self._deny_object("warehouse_view", str(self.view.id), access_level="viewer")++ response = self.client.get(f"{self.url}/subjects/")++ assert response.status_code == status.HTTP_200_OK, response.content+ editable_by_name = {row["name"]: row["editable"] for row in response.json()}+ assert editable_by_name["orders"] is False++ def test_the_catalog_marks_nothing_editable_for_a_read_only_token(self) -> None:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="read only",+ secure_value=hash_key_value(token),+ scopes=["query:read", "warehouse_objects:read"],+ )+ self.client.logout()++ response = self.client.get(f"{self.url}/subjects/", HTTP_AUTHORIZATION=f"Bearer {token}")++ assert response.status_code == status.HTTP_200_OK, response.content+ editable_by_name = {row["name"]: row["editable"] for row in response.json()}+ assert "orders" in editable_by_name+ assert not any(editable_by_name.values())+@parameterized.expand([- ("list", lambda self, check, suite: self.client.get(f"{self.url}/")),+ ("list", lambda self, check, suite: self.client.get(self._checks_of(self.view.id))),("retrieve", lambda self, check, suite: self.client.get(f"{self.url}/{check.id}/")),("create", lambda self, check, suite: self.client.post(f"{self.url}/", self._payload())),(@@ -1337,41 +1407,45 @@ class TestDataQualityCheckAPI(APIBaseTest):),("run", lambda self, check, suite: self.client.post(f"{self.url}/{check.id}/run/")),("runs", lambda self, check, suite: self.client.get(f"{self.url}/{check.id}/runs/")),- ("run_all", lambda self, check, suite: self.client.post(f"{self.url}/run_all/")),- ("health", lambda self, check, suite: self.client.get(f"{self.url}/health/")),- ("suite_runs_list", lambda self, check, suite: self.client.get(f"{self._suite_runs_url()}/")),+ ("run_subject", lambda self, check, suite: self.client.post(f"{self.suites_url}/", self.subject)),(- "suite_run_check_runs",- lambda self, check, suite: self.client.get(f"{self._suite_runs_url()}/{suite.id}/check_runs/"),+ "health",+ lambda self, check, suite: self.client.get(f"{self.url}/health/?{self._subject_query(self.view.id)}"),),+ ("suite_runs_list", lambda self, check, suite: self.client.get(self._runs_of(self.view.id))),+ ("suite_run_retrieve", lambda self, check, suite: self.client.get(f"{self.suites_url}/{suite.id}/")),])- def test_a_denied_parent_subject_blocks_every_action(self, _name: str, call) -> None:- # Authoring, running, or reading anything under a table the member cannot query would leak- # its shape and observed counts. The subject is the parent in the URL, so every action 403s.+ def test_a_denied_subject_blocks_every_action(self, _name: str, call) -> None:check = self._create_check()suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=self.view.id)self._deny_the_view()- assert call(self, check, suite).status_code == status.HTTP_403_FORBIDDEN+ response = call(self, check, suite)+ assert response.status_code in (+ status.HTTP_403_FORBIDDEN,+ status.HTTP_404_NOT_FOUND,+ ), response.status_codedef test_deleting_a_denied_subject_does_not_hand_its_history_over(self) -> None:# An orphan resolves to an empty name, which matches no denial, so deleting the view would# otherwise lift the member's denial along with it.self._create_check()self._deny_the_view()+ view_id = self.view.idself.view.delete()- assert self.client.get(f"{self.url}/").status_code == status.HTTP_403_FORBIDDEN+ assert self.client.get(self._checks_of(view_id)).status_code == status.HTTP_403_FORBIDDENdef test_an_unrestricted_member_still_reads_an_orphaned_subjects_checks(self) -> None:# Orphaned history stays reachable: checks on a deleted subject are skipped, not hidden.self._create_check()+ view_id = self.view.idself.view.delete()- assert self.client.get(f"{self.url}/").status_code == status.HTTP_200_OK+ assert self.client.get(self._checks_of(view_id)).status_code == status.HTTP_200_OK@parameterized.expand([@@ -1389,8 +1463,8 @@ class TestDataQualityCheckAPI(APIBaseTest):self._deny_the_view()response = self.client.post(- f"{self._checks_url(allowed.id)}/",- self._payload(check_type=check_type, column_name=column_name, config=config),+ f"{self.url}/",+ self._payload(subject_uuid=str(allowed.id), check_type=check_type, column_name=column_name, config=config),)assert response.status_code == status.HTTP_403_FORBIDDEN@@ -1408,13 +1482,13 @@ class TestDataQualityCheckAPI(APIBaseTest):reads_charges = self._payload(check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": "SELECT 1 FROM stripe.charges"})- created = self.client.post(f"{self._checks_url(allowed.id)}/", reads_charges)+ created = self.client.post(f"{self.url}/", {**self._subject_of(allowed.id), **reads_charges})assert created.status_code == status.HTTP_201_CREATED, created.json()self._deny_object("warehouse_table", str(charges.id))with patch.object(Database, "create_for", side_effect=Database.create_for) as build:- listed = self.client.get(f"{self._checks_url(allowed.id)}/")- recreated = self.client.post(f"{self._checks_url(allowed.id)}/", reads_charges)+ listed = self.client.get(self._checks_of(allowed.id))+ recreated = self.client.post(f"{self.url}/", {**self._subject_of(allowed.id), **reads_charges})build.assert_not_called()assert listed.status_code == status.HTTP_200_OK, listed.json()@@ -1433,7 +1507,7 @@ class TestDataQualityCheckAPI(APIBaseTest):allowed = self._make_view("customers")for index in range(3):self._create_check(- url=self._checks_url(allowed.id),+ subject_uuid=str(allowed.id),check_type=CheckType.CUSTOM_SQL,column_name="",config={"query": query.format(index=index)},@@ -1441,7 +1515,7 @@ class TestDataQualityCheckAPI(APIBaseTest):self._deny_the_view()with patch.object(Database, "create_for", side_effect=Database.create_for) as build:- listed = self.client.get(f"{self._checks_url(allowed.id)}/")+ listed = self.client.get(self._checks_of(allowed.id))assert listed.status_code == status.HTTP_200_OK, listed.json()assert len(listed.json()["results"]) == 3@@ -1462,12 +1536,12 @@ class TestDataQualityCheckAPI(APIBaseTest):reads_backing_table = self._payload(check_type=CheckType.CUSTOM_SQL, column_name="", config={"query": f"SELECT 1 FROM {backing_table.name}"})- created = self.client.post(f"{self._checks_url(allowed.id)}/", reads_backing_table)+ created = self.client.post(f"{self.url}/", {**self._subject_of(allowed.id), **reads_backing_table})assert created.status_code == status.HTTP_201_CREATED, created.json()self._deny_object("warehouse_table", str(backing_table.id))- listed = self.client.get(f"{self._checks_url(allowed.id)}/")- recreated = self.client.post(f"{self._checks_url(allowed.id)}/", reads_backing_table)+ listed = self.client.get(self._checks_of(allowed.id))+ recreated = self.client.post(f"{self.url}/", {**self._subject_of(allowed.id), **reads_backing_table})assert listed.status_code == status.HTTP_200_OK, listed.json()assert listed.json()["results"] == []@@ -1476,7 +1550,7 @@ class TestDataQualityCheckAPI(APIBaseTest):def test_a_database_build_that_fails_refuses_rather_than_500s(self) -> None:allowed = self._make_view("customers")self._create_check(- url=self._checks_url(allowed.id),+ subject_uuid=str(allowed.id),check_type=CheckType.CUSTOM_SQL,column_name="",config={"query": "SELECT 1 FROM customers"},@@ -1484,7 +1558,7 @@ class TestDataQualityCheckAPI(APIBaseTest):self._deny_the_view()with patch.object(Database, "create_for", side_effect=RuntimeError("a saved query will not parse")):- response = self.client.get(f"{self._checks_url(allowed.id)}/")+ response = self.client.get(self._checks_of(allowed.id))assert response.status_code == status.HTTP_403_FORBIDDENassert response.json()["detail"] == "Could not verify your access to this table or view."@@ -1494,11 +1568,11 @@ class TestDataQualityCheckAPI(APIBaseTest):# The stored definition cleared the denial; the candidate one has to clear it too, or an edit# is the way to point a visible check at a table the member cannot read.allowed = self._make_view("customers")- check = self._create_check(url=self._checks_url(allowed.id), column_name="id")+ check = self._create_check(subject_uuid=str(allowed.id), column_name="id")self._deny_the_view()response = getattr(self.client, method)(- f"{self._checks_url(allowed.id)}/{check.id}/",+ f"{self.url}/{check.id}/",{"check_type": CheckType.CUSTOM_SQL, "column_name": "", "config": {"query": "SELECT 1 FROM orders"}},)@@ -1510,7 +1584,7 @@ class TestDataQualityCheckAPI(APIBaseTest):def test_editing_a_check_with_an_unreadable_stored_definition_writes_nothing(self, method: str) -> None:allowed = self._make_view("customers")check = self._create_check(- url=self._checks_url(allowed.id),+ subject_uuid=str(allowed.id),check_type=CheckType.CUSTOM_SQL,column_name="",config={"query": "SELECT 1 FROM orders"},@@ -1524,7 +1598,7 @@ class TestDataQualityCheckAPI(APIBaseTest):)response = getattr(self.client, "patch" if method == "presentation" else method)(- f"{self._checks_url(allowed.id)}/{check.id}/", changes+ f"{self.url}/{check.id}/", changes)assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()@@ -1536,7 +1610,7 @@ class TestDataQualityCheckAPI(APIBaseTest):def test_editing_rechecks_access_when_the_stored_definition_changes_before_locking(self) -> None:allowed = self._make_view("customers")check = self._create_check(- url=self._checks_url(allowed.id),+ subject_uuid=str(allowed.id),check_type=CheckType.CUSTOM_SQL,column_name="",config={"query": "SELECT 1 FROM customers"},@@ -1566,7 +1640,7 @@ class TestDataQualityCheckAPI(APIBaseTest):with patch.object(checks_logic, "_candidate_definition", side_effect=replace_definition_before_lock):response = self.client.patch(- f"{self._checks_url(allowed.id)}/{check.id}/",+ f"{self.url}/{check.id}/",{"config": {"query": "SELECT 1"}, "description": "proposed change"},)@@ -1630,7 +1704,7 @@ class TestDataQualityCheckAPI(APIBaseTest):if deny:self._deny_the_view()- response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")+ response = self.client.get(f"{self.suites_url}/{suite.id}/check_runs/")assert response.status_code == status.HTTP_200_OKassert sorted(row["check_type"] for row in response.json()) == sorted(expected_types)@@ -1643,9 +1717,8 @@ class TestDataQualityCheckAPI(APIBaseTest):suite = self._suite_with_two_runs(allowed)self._deny_the_view()- base = self._suite_runs_url(allowed.id)- listed = self.client.get(f"{base}/")- retrieved = self.client.get(f"{base}/{suite.id}/")+ listed = self.client.get(self._runs_of(allowed.id))+ retrieved = self.client.get(f"{self.suites_url}/{suite.id}/")assert listed.status_code == status.HTTP_200_OK, listed.json()assert listed.json()["results"] == []@@ -1662,7 +1735,7 @@ class TestDataQualityCheckAPI(APIBaseTest):)self._deny_the_view()- response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")+ response = self.client.get(f"{self.suites_url}/{suite.id}/check_runs/")assert response.status_code == status.HTTP_200_OKassert [row["check_type"] for row in response.json()] == [CheckType.NOT_NULL]@@ -1709,8 +1782,8 @@ class TestDataQualityCheckAPI(APIBaseTest):self._deny_the_view()self.view.delete()- suite_runs = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")- history = self.client.get(f"{self._checks_url(allowed.id)}/{check.id}/runs/")+ suite_runs = self.client.get(f"{self.suites_url}/{suite.id}/check_runs/")+ history = self.client.get(f"{self.url}/{check.id}/runs/")# The suite route filters, since it serves runs from many checks. The per-check route refuses,# since the one definition it serves is the one that cannot be established.@@ -1745,7 +1818,7 @@ class TestDataQualityCheckAPI(APIBaseTest):self.view.delete()self._make_view("orders")- response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")+ response = self.client.get(f"{self.suites_url}/{suite.id}/check_runs/")assert response.status_code == status.HTTP_200_OKassert response.json() == []@@ -1772,7 +1845,7 @@ class TestDataQualityCheckAPI(APIBaseTest):)self._deny_the_view()- response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")+ response = self.client.get(f"{self.suites_url}/{suite.id}/check_runs/")assert response.status_code == status.HTTP_200_OKassert [row["check_type"] for row in response.json()] == [CheckType.CUSTOM_SQL]@@ -1814,7 +1887,7 @@ class TestDataQualityCheckAPI(APIBaseTest):)self._deny_the_view()- response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")+ response = self.client.get(f"{self.suites_url}/{suite.id}/check_runs/")assert response.status_code == status.HTTP_200_OKassert [row["check_type"] for row in response.json()] == [CheckType.CUSTOM_SQL]@@ -1851,10 +1924,11 @@ class TestDataQualityCheckAPI(APIBaseTest):failed_row_count=3,)self._deny_the_view()+ temp_id = temp.idtemp.delete()- assert self.client.get(f"{self._checks_url(temp.id)}/").status_code == status.HTTP_403_FORBIDDEN- assert self.client.get(f"{self._suite_runs_url(temp.id)}/").status_code == status.HTTP_403_FORBIDDEN+ assert self.client.get(self._checks_of(temp_id)).status_code == status.HTTP_403_FORBIDDEN+ assert self.client.get(self._runs_of(temp_id)).status_code == status.HTTP_403_FORBIDDENdef test_a_restricted_member_loses_an_orphaned_checks_row_from_the_project_list(self) -> None:# An orphan has no subject left to prove access against, so it fails closed for a member who@@ -1895,7 +1969,12 @@ class TestDataQualityCheckAPI(APIBaseTest):@parameterized.expand([("run", lambda self, url, check: self.client.post(f"{url}/{check.id}/run/")),- ("run_all", lambda self, url, check: self.client.post(f"{url}/run_all/")),+ (+ "run_subject",+ lambda self, url, check: self.client.post(+ f"{self.suites_url}/", self._subject_of(check.saved_query_id)+ ),+ ),("runs", lambda self, url, check: self.client.get(f"{url}/{check.id}/runs/")),])@@ -1915,7 +1994,7 @@ class TestDataQualityCheckAPI(APIBaseTest):)self._deny_the_view()- assert call(self, self._checks_url(allowed.id), check).status_code == status.HTTP_403_FORBIDDEN+ assert call(self, self.url, check).status_code == status.HTTP_403_FORBIDDEN@parameterized.expand([@@ -1936,7 +2015,7 @@ class TestDataQualityCheckAPI(APIBaseTest):)self._deny_the_view()- response = call(self, self._checks_url(allowed.id), check)+ response = call(self, self.url, check)assert response.status_code == status.HTTP_403_FORBIDDENassert DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id, deleted=False).exists()@@ -1945,12 +2024,13 @@ class TestDataQualityCheckAPI(APIBaseTest):[("create", lambda self, check: self.client.post(f"{self.url}/", self._payload(column_name="total"))),("run", lambda self, check: self.client.post(f"{self.url}/{check.id}/run/")),- ("run_all", lambda self, check: self.client.post(f"{self.url}/run_all/")),+ ("run_all", lambda self, check: self.client.post(f"{self.suites_url}/", self.subject)),("runs", lambda self, check: self.client.get(f"{self.url}/{check.id}/runs/")),("list", lambda self, check: self.client.get(f"{self.url}/")),("retrieve", lambda self, check: self.client.get(f"{self.url}/{check.id}/")),("health", lambda self, check: self.client.get(f"{self.url}/health/")),- ("suite_runs_list", lambda self, check: self.client.get(f"{self._suite_runs_url()}/")),+ ("subjects", lambda self, check: self.client.get(f"{self.url}/subjects/")),+ ("suite_runs_list", lambda self, check: self.client.get(self._runs_of(self.view.id))),])def test_query_denied_members_cannot_author_execute_or_read_check_outcomes(self, _name: str, call) -> None:@@ -1964,22 +2044,32 @@ class TestDataQualityCheckAPI(APIBaseTest):assert call(self, check).status_code == status.HTTP_403_FORBIDDEN- def test_check_types_catalog_stays_readable_without_query_access(self) -> None:- # The check-type catalog is static schema metadata with no execution state, so unlike the- # check rows it is not gated on query access -- an agent must be able to discover config shapes.- AccessControl.objects.create(team=self.team, resource="query", access_level="none")- self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": "access"}]- self.organization.save()+ @parameterized.expand([("get",), ("patch",)])+ def test_a_subject_that_runs_on_its_data_cannot_be_scheduled(self, method: str) -> None:+ self._create_check()++ response = (+ self.client.patch(f"{self.url}/schedule/", self.subject)+ if method == "patch"+ else self.client.get(f"{self.url}/schedule/?{self._subject_query(self.view.id)}")+ )- assert self.client.get(f"{self.url}/check_types/").status_code == status.HTTP_200_OK+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert response.json()["attr"] == "subject_type"++ def test_the_check_type_catalog_needs_no_access_to_any_subject(self) -> None:+ self._deny_the_view()++ response = self.client.get(f"{self.url}/check_types/")++ assert response.status_code == status.HTTP_200_OK, response.content+ assert {row["check_type"] for row in response.json()}def test_another_projects_checks_are_not_visible(self) -> None:check = self._create_check()other_team = self.create_team_with_organization(self.organization)- response = self.client.get(- f"/api/projects/{other_team.id}/warehouse_saved_queries/{self.view.id}/checks/{check.id}/"- )+ response = self.client.get(f"/api/projects/{other_team.id}/data_quality_checks/{check.id}/")assert response.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/data_quality/backend/tests/test_permissions.py b/products/data_quality/backend/tests/test_permissions.pynew file mode 100644index 000000000000..a63bb510dc43--- /dev/null+++ b/products/data_quality/backend/tests/test_permissions.py@@ -0,0 +1,35 @@+from unittest.mock import MagicMock++from django.test import SimpleTestCase++from parameterized import parameterized++from products.data_quality.backend.facade.enums import SubjectType+from products.data_quality.backend.logic.permissions import authorized_subject_types+++class TestAuthorizedSubjectTypes(SimpleTestCase):+ @parameterized.expand(+ [+ ("per_kind_table_write", ["query:read", "warehouse_table:write"], True, {SubjectType.TABLE}),+ ("per_kind_view_read", ["query:read", "warehouse_view:read"], False, {SubjectType.VIEW}),+ ("per_kind_read_cannot_write", ["query:read", "warehouse_table:read"], True, set()),+ ("family_read", ["query:read", "warehouse_objects:read"], False, {SubjectType.TABLE, SubjectType.VIEW}),+ ("family_write", ["query:read", "warehouse_objects:write"], True, {SubjectType.TABLE, SubjectType.VIEW}),+ ("catalog_only", ["query:read", "data_catalog:write"], True, {SubjectType.METRIC}),+ (+ "family_does_not_reach_metrics",+ ["warehouse_objects:write"],+ False,+ {SubjectType.TABLE, SubjectType.VIEW},+ ),+ ("session_user", None, True, set(SubjectType)),+ ]+ )+ def test_a_scope_reaches_the_subject_kinds_it_names(+ self, _name: str, scopes: list[str] | None, write: bool, expected: set[SubjectType]+ ) -> None:+ access = MagicMock(team=None)+ access.check_access_level_for_resource.return_value = True++ assert authorized_subject_types(access, scopes, write=write) == frozenset(expected)diff --git a/products/data_quality/backend/tests/test_runs_api.py b/products/data_quality/backend/tests/test_runs_api.pyindex e12b5b174059..dcf4a3ebc460 100644--- a/products/data_quality/backend/tests/test_runs_api.py+++ b/products/data_quality/backend/tests/test_runs_api.py@@ -39,6 +39,7 @@ class TestDataQualityRunAPI(APIBaseTest):self.customers = self._make_view("customers")self.url = f"/api/projects/{self.team.id}/data_quality_runs/"self.checks_url = f"/api/projects/{self.team.id}/data_quality_checks/"+flag = patch(FLAG, return_value=True)flag.start()self.addCleanup(flag.stop)@@ -82,6 +83,12 @@ class TestDataQualityRunAPI(APIBaseTest):})+ def _subject_query(self, subject_type: str, subject_uuid) -> str:+ return f"subject_type={subject_type}&subject_uuid={subject_uuid}"++ def _checks_of(self, subject_type: str, subject_uuid) -> str:+ return f"{self.checks_url}?{self._subject_query(subject_type, subject_uuid)}"+def _run(self, **body):with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):return self.client.post(self.url, body, format="json")@@ -238,12 +245,11 @@ class TestDataQualityRunAPI(APIBaseTest):swept = self.client.post(self.url, {}, format="json")assert swept.status_code == 200temporal.start_workflow.assert_not_called()- nested_url = f"/api/projects/{self.team.id}/data_catalog/metrics/{metric.id}/checks/"- nested = self.client.get(nested_url)- assert nested.status_code == 200- assert nested.json()["results"] == []+ scoped = self.client.get(self._checks_of(SubjectType.METRIC, metric.id))+ assert scoped.status_code == 200+ assert scoped.json()["results"] == []with patch(START_SUITE, return_value=temporal):- assert self.client.post(f"{nested_url}{check.id}/run/").status_code == 403+ assert self.client.post(f"{self.checks_url}{check.id}/run/").status_code == 403@parameterized.expand([@@ -266,26 +272,41 @@ class TestDataQualityRunAPI(APIBaseTest):for level in ("read", "write")])- def test_nested_warehouse_routes_honor_their_own_scopes(self, kind: str, subject_type: str, level: str) -> None:+ def test_the_warehouse_objects_scope_covers_both_kinds_of_subject(+ self, kind: str, subject_type: str, level: str+ ) -> None:subject: DataWarehouseSavedQuery | DataWarehouseTableif subject_type == "table":subject = DataWarehouseTable.objects.create(team=self.team, name="purchases", format="Parquet")check = self._check(self.orders, subject_type=SubjectType.TABLE, saved_query_id=None, table_id=subject.id)- path = "warehouse_tables"else:subject = self.orderscheck = self._check(self.orders)- path = "warehouse_saved_queries"- nested = f"/api/projects/{self.team.id}/{path}/{subject.id}/checks/"- self._authenticate_token(kind, [f"warehouse_{subject_type}:{level}", "query:read"])+ self._authenticate_token(kind, [f"warehouse_objects:{level}", "query:read"])- listed = self.client.get(nested)+ listed = self.client.get(self._checks_of(subject_type, subject.id))assert listed.status_code == 200, listed.json()assert [row["id"] for row in listed.json()["results"]] == [str(check.id)]- assert self.client.get(f"{nested}{check.id}/runs/").status_code == 200+ assert self.client.get(f"{self.checks_url}{check.id}/runs/").status_code == 200with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):- assert self.client.post(f"{nested}{check.id}/run/").status_code == (200 if level == "write" else 403)- assert self.client.get(self.checks_url).status_code == 403+ assert self.client.post(f"{self.checks_url}{check.id}/run/").status_code == (+ 200 if level == "write" else 403+ )++ @parameterized.expand([("table",), ("view",)])+ def test_a_token_scoped_to_one_kind_of_warehouse_object_reaches_only_that_kind(self, subject_type: str) -> None:+ purchases = DataWarehouseTable.objects.create(team=self.team, name="purchases", format="Parquet")+ table_check = self._check(+ self.orders, subject_type=SubjectType.TABLE, saved_query_id=None, table_id=purchases.id+ )+ view_check = self._check(self.orders)+ self._authenticate_token("pat", [f"warehouse_{subject_type}:write", "query:read"])++ listed = self.client.get(self.checks_url)++ assert listed.status_code == 200, listed.json()+ expected = table_check if subject_type == "table" else view_check+ assert [row["id"] for row in listed.json()["results"]] == [str(expected.id)]def test_catalog_only_members_see_teammates_metric_checks_and_suites(self) -> None:author = self._create_user("[email protected]")@@ -316,13 +337,12 @@ class TestDataQualityRunAPI(APIBaseTest):)self._check(self.orders)cache.clear()- nested = f"/api/projects/{self.team.id}/data_catalog/metrics/{metric.id}/"- for url in (self.checks_url, f"{nested}checks/"):+ for url in (self.checks_url, self._checks_of(SubjectType.METRIC, metric.id)):response = self.client.get(url)assert response.status_code == 200, response.json()assert [row["id"] for row in response.json()["results"]] == [str(check.id)]- for url in (self.url, f"{nested}check_suite_runs/"):+ for url in (self.url, f"{self.url}?{self._subject_query(SubjectType.METRIC, metric.id)}"):response = self.client.get(url)assert response.status_code == 200, response.json()assert [row["id"] for row in response.json()["results"]] == [str(suite.id)]@@ -346,14 +366,12 @@ class TestDataQualityRunAPI(APIBaseTest):for name in ("granted_table", "ungranted_table")]subject_fk = "table_id"- parent_path = "warehouse_tables"else:subjects = [self.orders, self.customers]DataWarehouseSavedQuery.objects.filter(team=self.team, id__in=[subject.id for subject in subjects]).update(created_by=author)subject_fk = "saved_query_id"- parent_path = "warehouse_saved_queries"granted, ungranted = [self._check(self.orders,@@ -407,15 +425,15 @@ class TestDataQualityRunAPI(APIBaseTest):)flag.start()self.addCleanup(flag.stop)- nested = f"/api/projects/{self.team.id}/{parent_path}/{subjects[0].id}/checks/"- denied_nested = f"/api/projects/{self.team.id}/{parent_path}/{subjects[1].id}/checks/"+ scoped = self._checks_of(subject_type, subjects[0].id)+ denied_scoped = self._checks_of(subject_type, subjects[1].id)- for url in (nested, self.checks_url):+ for url in (scoped, self.checks_url):listed = self.client.get(url)assert listed.status_code == status.HTTP_200_OK, listed.json()assert listed.json()["count"] == 1assert [row["id"] for row in listed.json()["results"]] == [str(granted.id)]- assert self.client.get(denied_nested).status_code == status.HTTP_403_FORBIDDEN+ assert self.client.get(denied_scoped).status_code == status.HTTP_403_FORBIDDENhistory = self.client.get(self.url)assert history.status_code == status.HTTP_200_OK, history.json()assert [suite["id"] for suite in history.json()["results"]] == [str(allowed_suite.id)]@@ -423,14 +441,14 @@ class TestDataQualityRunAPI(APIBaseTest):temporal = MagicMock(start_workflow=AsyncMock())with patch(START_SUITE, return_value=temporal):- assert self.client.post(f"{denied_nested}{ungranted.id}/run/").status_code == status.HTTP_403_FORBIDDEN+ assert self.client.post(f"{self.checks_url}{ungranted.id}/run/").status_code == status.HTTP_403_FORBIDDENdenied_selection = self.client.post(self.url, {"check_ids": [str(ungranted.id)]}, format="json")assert denied_selection.status_code == status.HTTP_403_FORBIDDEN, denied_selection.json()temporal.start_workflow.assert_not_called()expected_status = status.HTTP_200_OK if access_level == "editor" else status.HTTP_403_FORBIDDEN- nested_run = self.client.post(f"{nested}{granted.id}/run/")- assert nested_run.status_code == expected_status, nested_run.json()+ direct_run = self.client.post(f"{self.checks_url}{granted.id}/run/")+ assert direct_run.status_code == expected_status, direct_run.json()selected_run = self.client.post(self.url, {"check_ids": [str(granted.id)]}, format="json")assert selected_run.status_code == expected_status, selected_run.json()assert temporal.start_workflow.call_count == (2 if access_level == "editor" else 0)diff --git a/products/data_quality/backend/tests/test_subjects.py b/products/data_quality/backend/tests/test_subjects.pyindex 9c1a35b06c26..1ddb37ee3fea 100644--- a/products/data_quality/backend/tests/test_subjects.py+++ b/products/data_quality/backend/tests/test_subjects.py@@ -1,4 +1,4 @@-from uuid import uuid4+from uuid import UUID, uuid4from posthog.test.base import BaseTest@@ -13,7 +13,7 @@ from products.data_modeling.backend.facade import api as data_modeling_facadefrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.enums import SubjectTypefrom products.data_quality.backend.logic.subject_access import readable_subjects, subject_metadata-from products.data_quality.backend.logic.subjects import resolve_subject, subject_column_type+from products.data_quality.backend.logic.subjects import resolve_subject, selectable_subjects, subject_column_typefrom products.warehouse_sources.backend.facade.models import DataWarehouseTablefrom products.warehouse_sources.backend.facade.types import ExternalDataSourceTypefrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -109,6 +109,56 @@ class TestSubjectResolver(BaseTest):assert not resolve_subject(other_team.id, SubjectType.TABLE, table.id).exists+ def test_a_curated_tables_columns_are_offered_under_the_names_hogql_resolves(self) -> None:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="stripe_source",+ connection_id="stripe_connection",+ source_type=ExternalDataSourceType.STRIPE,+ )+ table = DataWarehouseTable.objects.create(+ team=self.team,+ name="stripe_charge",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/x",+ external_data_source=source,+ columns={+ "id": {"clickhouse": "String"},+ "amount": {"clickhouse": "Nullable(Int64)"},+ "customer": {"clickhouse": "String"},+ "created": {"clickhouse": "Int64"},+ "_dlt_id": {"clickhouse": "String"},+ },+ )+ database = Database.create_for(team=self.team, bypass_warehouse_access_control=True)++ offered = next(+ subject for subject in selectable_subjects(self.team.id, {SubjectType.TABLE}) if subject.id == str(table.id)+ )++ assert set(offered.columns) == {"id", "amount", "customer_id", "created_at"}+ assert offered.columns["amount"] == "Nullable(Int64)"+ assert all(name in database.get_table("stripe_charge").fields for name in offered.columns)+ assert subject_column_type(self.team.id, SubjectType.TABLE, table.id, "customer_id") == "String"+ assert subject_column_type(self.team.id, SubjectType.TABLE, table.id, "customer") is None++ def test_an_uncurated_tables_columns_keep_their_names_without_the_sync_plumbing(self) -> None:+ table = self._table("postgres_orders")+ table.columns = {+ "id": {"clickhouse": "Int64"},+ "customer": {"clickhouse": "String"},+ "_dlt_id": {"clickhouse": "String"},+ "_dlt_load_id": {"clickhouse": "String"},+ }+ table.save(update_fields=["columns"])++ offered = next(+ subject for subject in selectable_subjects(self.team.id, {SubjectType.TABLE}) if subject.id == str(table.id)+ )++ assert set(offered.columns) == {"id", "customer"}+ assert subject_column_type(self.team.id, SubjectType.TABLE, table.id, "customer") == "String"+class TestReadableSubjectSnapshot(BaseTest):def _table(@@ -152,9 +202,12 @@ class TestReadableSubjectSnapshot(BaseTest):catalog_excluded = {table.id for table in tables if not database.has_table(table.name)}readable = readable_subjects(self.team.id, set())snapshot_excluded = {table.id for table in tables} - readable.table_ids+ offered = {UUID(subject.id) for subject in selectable_subjects(self.team.id, {SubjectType.TABLE})}+ offered_excluded = {table.id for table in tables} - offeredassert catalog_excluded == {backing_table.id, direct_table.id}assert snapshot_excluded == catalog_excluded+ assert offered_excluded == catalog_excludeddef test_a_soft_deleted_views_backing_table_stays_out_of_the_snapshot(self) -> None:view, backing_table = self._materialized_view()diff --git a/products/data_quality/frontend/DataQualitySchedule.test.tsx b/products/data_quality/frontend/DataQualitySchedule.test.tsxindex 510777d367ea..ad4acd005776 100644--- a/products/data_quality/frontend/DataQualitySchedule.test.tsx+++ b/products/data_quality/frontend/DataQualitySchedule.test.tsx@@ -5,11 +5,11 @@ import { cleanup, render, screen } from '@testing-library/react'import { initKeaTests } from '~/test/init'import { DataQualitySchedule } from './DataQualitySchedule'-import { dataCatalogMetricsChecksScheduleRetrieve } from './generated/api'+import { dataQualityChecksScheduleRetrieve } from './generated/api'jest.mock('./generated/api', () => ({- dataCatalogMetricsChecksScheduleRetrieve: jest.fn(),- dataCatalogMetricsChecksSchedulePartialUpdate: jest.fn(),+ dataQualityChecksScheduleRetrieve: jest.fn(),+ dataQualityChecksSchedulePartialUpdate: jest.fn(),}))describe('DataQualitySchedule', () => {@@ -26,7 +26,7 @@ describe('DataQualitySchedule', () => {})it('shows an elapsed next run as due now', async () => {- ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock).mockResolvedValue({+ ;(dataQualityChecksScheduleRetrieve as jest.Mock).mockResolvedValue({id: 'schedule-1',enabled: true,interval: '1hour',diff --git a/products/data_quality/frontend/checksApi.test.ts b/products/data_quality/frontend/checksApi.test.tsindex 9974898bd2da..7bdce6e9dfb1 100644--- a/products/data_quality/frontend/checksApi.test.ts+++ b/products/data_quality/frontend/checksApi.test.ts@@ -10,69 +10,13 @@ jest.mock('lib/api', () => ({jest.mock('./generated/api')-const ROUTE_PREFIX: Record<DataQualitySubjectType, string> = {- table: 'warehouseTables',- view: 'warehouseSavedQueries',- metric: 'dataCatalogMetrics',-}-interface Operation {name: stringroute: stringcall: (ref: DataQualitySubjectRef) => Promise<unknown>- trailingArgs: unknown[]+ args: (subject: { subject_type: DataQualitySubjectType; subject_uuid: string }) => unknown[]}-const OPERATIONS: Operation[] = [- { name: 'list', route: 'ChecksList', call: (ref) => checksApi.list(ref, 25), trailingArgs: [{ limit: 25 }] },- {- name: 'create',- route: 'ChecksCreate',- call: (ref) => checksApi.create(ref, { check_type: 'not_null', column_name: 'id' }),- trailingArgs: [{ check_type: 'not_null', column_name: 'id' }],- },- {- name: 'partialUpdate',- route: 'ChecksPartialUpdate',- call: (ref) => checksApi.partialUpdate(ref, 'check-1', { enabled: false }),- trailingArgs: ['check-1', { enabled: false }],- },- {- name: 'destroy',- route: 'ChecksDestroy',- call: (ref) => checksApi.destroy(ref, 'check-1'),- trailingArgs: ['check-1'],- },- { name: 'run', route: 'ChecksRunCreate', call: (ref) => checksApi.run(ref, 'check-1'), trailingArgs: ['check-1'] },- { name: 'runAll', route: 'ChecksRunAllCreate', call: (ref) => checksApi.runAll(ref), trailingArgs: [] },- { name: 'runs', route: 'ChecksRunsList', call: (ref) => checksApi.runs(ref, 'check-1'), trailingArgs: ['check-1'] },- {- name: 'checkTypes',- route: 'ChecksCheckTypesList',- call: (ref) => checksApi.checkTypes(ref),- trailingArgs: [],- },- { name: 'health', route: 'ChecksHealthRetrieve', call: (ref) => checksApi.health(ref), trailingArgs: [] },- {- name: 'suiteRuns',- route: 'CheckSuiteRunsList',- call: (ref) => checksApi.suiteRuns(ref, 25),- trailingArgs: [{ limit: 25 }],- },- {- name: 'suiteRunRetrieve',- route: 'CheckSuiteRunsRetrieve',- call: (ref) => checksApi.suiteRunRetrieve(ref, 'suite-1'),- trailingArgs: ['suite-1'],- },- {- name: 'suiteRunCheckRuns',- route: 'CheckSuiteRunsCheckRunsList',- call: (ref) => checksApi.suiteRunCheckRuns(ref, 'suite-1'),- trailingArgs: ['suite-1'],- },-]-const SUBJECT_TYPES: DataQualitySubjectType[] = ['table', 'view', 'metric']const mocked = generated as unknown as Record<string, jest.Mock>@@ -80,17 +24,107 @@ const mocked = generated as unknown as Record<string, jest.Mock>describe('checksApi', () => {beforeEach(() => {jest.clearAllMocks()+ mocked.dataQualityChecksHealthList.mockResolvedValue([])})- test.each(- SUBJECT_TYPES.flatMap((subjectType) =>- OPERATIONS.map((operation) => [subjectType, operation.name, operation] as const)- )- )('sends a %s %s to its own endpoint', async (subjectType, _name, operation) => {- const expected = `${ROUTE_PREFIX[subjectType]}${operation.route}`+ describe('subject-scoped operations', () => {+ const OPERATIONS: Operation[] = [+ {+ name: 'list',+ route: 'dataQualityChecksList',+ call: (ref) => checksApi.list(ref, 25),+ args: (subject) => [{ ...subject, limit: 25 }],+ },+ {+ name: 'create',+ route: 'dataQualityChecksCreate',+ call: (ref) => checksApi.create(ref, { check_type: 'not_null', column_name: 'id' }),+ args: (subject) => [{ check_type: 'not_null', column_name: 'id', ...subject }],+ },+ {+ name: 'runAll',+ route: 'dataQualityRunsCreate',+ call: (ref) => checksApi.runAll(ref),+ args: (subject) => [subject],+ },+ {+ name: 'checkTypes',+ route: 'dataQualityChecksCheckTypesList',+ call: (ref) => checksApi.checkTypes(ref),+ args: ({ subject_type }) => [{ subject_type }],+ },+ {+ name: 'health',+ route: 'dataQualityChecksHealthList',+ call: (ref) => checksApi.health(ref),+ args: (subject) => [subject],+ },+ {+ name: 'suiteRuns',+ route: 'dataQualityRunsList',+ call: (ref) => checksApi.suiteRuns(ref, 25),+ args: (subject) => [{ ...subject, limit: 25 }],+ },+ {+ name: 'schedule',+ route: 'dataQualityChecksScheduleRetrieve',+ call: (ref) => checksApi.schedule(ref),+ args: (subject) => [subject],+ },+ {+ name: 'updateSchedule',+ route: 'dataQualityChecksSchedulePartialUpdate',+ call: (ref) => checksApi.updateSchedule(ref, { interval: '24hour' }),+ args: (subject) => [{ interval: '24hour', ...subject }],+ },+ ]++ test.each(+ SUBJECT_TYPES.flatMap((subjectType) =>+ OPERATIONS.map((operation) => [subjectType, operation.name, operation] as const)+ )+ )('names the subject of a %s %s in the request', async (subjectType, _name, operation) => {+ await operation.call({ subjectType, subjectId: 'subject-1' })++ const expected = operation.args({ subject_type: subjectType, subject_uuid: 'subject-1' })+ expect(mocked[operation.route]).toHaveBeenCalledWith('1', ...expected)+ })+ })++ it('reads the output schema only for a metric', async () => {+ expect(await checksApi.outputSchema({ subjectType: 'table', subjectId: 'subject-1' })).toEqual({ columns: [] })+ expect(mocked.dataQualityChecksOutputSchemaRetrieve).not.toHaveBeenCalled()++ await checksApi.outputSchema({ subjectType: 'metric', subjectId: 'subject-1' })+ expect(mocked.dataQualityChecksOutputSchemaRetrieve).toHaveBeenCalledWith('1', {+ subject_type: 'metric',+ subject_uuid: 'subject-1',+ })+ })++ it('reports a subject with no rollup as unknown rather than missing', async () => {+ expect(await checksApi.health({ subjectType: 'view', subjectId: 'subject-1' })).toEqual({+ subject_type: 'view',+ subject_uuid: 'subject-1',+ health: 'unknown',+ checks_total: 0,+ checks_failing: 0,+ })+ })- await operation.call({ subjectType, subjectId: 'subject-1' })+ it('addresses a check by id alone, without its subject', async () => {+ await checksApi.partialUpdate('check-1', { enabled: false })+ await checksApi.destroy('check-1')+ await checksApi.run('check-1')+ await checksApi.runs('check-1')+ await checksApi.suiteRunRetrieve('suite-1')+ await checksApi.suiteRunCheckRuns('suite-1')- expect(mocked[expected]).toHaveBeenCalledWith('1', 'subject-1', ...operation.trailingArgs)+ expect(mocked.dataQualityChecksPartialUpdate).toHaveBeenCalledWith('1', 'check-1', { enabled: false })+ expect(mocked.dataQualityChecksDestroy).toHaveBeenCalledWith('1', 'check-1')+ expect(mocked.dataQualityChecksRunCreate).toHaveBeenCalledWith('1', 'check-1')+ expect(mocked.dataQualityChecksRunsList).toHaveBeenCalledWith('1', 'check-1')+ expect(mocked.dataQualityRunsRetrieve).toHaveBeenCalledWith('1', 'suite-1')+ expect(mocked.dataQualityRunsCheckRunsList).toHaveBeenCalledWith('1', 'suite-1')})})diff --git a/products/data_quality/frontend/checksApi.ts b/products/data_quality/frontend/checksApi.tsindex be384343500e..face9a3271a3 100644--- a/products/data_quality/frontend/checksApi.ts+++ b/products/data_quality/frontend/checksApi.ts@@ -1,54 +1,36 @@import { ApiConfig, ApiError } from 'lib/api'import {- dataCatalogMetricsCheckSuiteRunsCheckRunsList,- dataCatalogMetricsCheckSuiteRunsList,- dataCatalogMetricsCheckSuiteRunsRetrieve,- dataCatalogMetricsChecksCheckTypesList,- dataCatalogMetricsChecksCreate,- dataCatalogMetricsChecksDestroy,- dataCatalogMetricsChecksHealthRetrieve,- dataCatalogMetricsChecksList,- dataCatalogMetricsChecksOutputSchemaRetrieve,- dataCatalogMetricsChecksPartialUpdate,- dataCatalogMetricsChecksRunAllCreate,- dataCatalogMetricsChecksRunCreate,- dataCatalogMetricsChecksRunsList,+ dataQualityChecksCheckTypesList,+ dataQualityChecksCreate,+ dataQualityChecksDestroy,+ dataQualityChecksHealthList,+ dataQualityChecksList,dataQualityChecksMetricSubjectsList,- warehouseSavedQueriesCheckSuiteRunsCheckRunsList,- warehouseSavedQueriesCheckSuiteRunsList,- warehouseSavedQueriesCheckSuiteRunsRetrieve,- warehouseSavedQueriesChecksCheckTypesList,- warehouseSavedQueriesChecksCreate,- warehouseSavedQueriesChecksDestroy,- warehouseSavedQueriesChecksHealthRetrieve,- warehouseSavedQueriesChecksList,- warehouseSavedQueriesChecksPartialUpdate,- warehouseSavedQueriesChecksRunAllCreate,- warehouseSavedQueriesChecksRunCreate,- warehouseSavedQueriesChecksRunsList,- warehouseTablesCheckSuiteRunsCheckRunsList,- warehouseTablesCheckSuiteRunsList,- warehouseTablesCheckSuiteRunsRetrieve,- warehouseTablesChecksCheckTypesList,- warehouseTablesChecksCreate,- warehouseTablesChecksDestroy,- warehouseTablesChecksHealthRetrieve,- warehouseTablesChecksList,- warehouseTablesChecksPartialUpdate,- warehouseTablesChecksRunAllCreate,- warehouseTablesChecksRunCreate,- warehouseTablesChecksRunsList,+ dataQualityChecksOutputSchemaRetrieve,+ dataQualityChecksPartialUpdate,+ dataQualityChecksRunCreate,+ dataQualityChecksRunsList,+ dataQualityChecksSchedulePartialUpdate,+ dataQualityChecksScheduleRetrieve,+ dataQualityChecksSubjectsList,+ dataQualityRunsCheckRunsList,+ dataQualityRunsCreate,+ dataQualityRunsList,+ dataQualityRunsRetrieve,} from './generated/api'import type {DataQualityCheckApi,DataQualityCheckRunApi,+ DataQualityCheckScheduleApi,DataQualityCheckTypeApi,DataQualityMetricSubjectApi,DataQualityOutputSchemaApi,+ DataQualitySubjectApi,DataQualitySubjectHealthApi,DataQualitySuiteRunApi,- PaginatedDataQualityCheckListApi,+ PatchedDataQualityCheckScheduleUpdateApi,+ PaginatedDataQualityOverviewCheckListApi,PaginatedDataQualitySuiteRunListApi,} from './generated/api.schemas'@@ -63,125 +45,72 @@ export interface DataQualitySubjectRef {subjectId: string}-type CreateBody = Parameters<typeof warehouseSavedQueriesChecksCreate>[2]-type PatchBody = Parameters<typeof warehouseSavedQueriesChecksPartialUpdate>[3]-type PageParams = Parameters<typeof warehouseSavedQueriesChecksList>[2]--interface SubjectRoutes {- list: (projectId: string, subjectId: string, params?: PageParams) => Promise<PaginatedDataQualityCheckListApi>- create: (projectId: string, subjectId: string, body: CreateBody) => Promise<DataQualityCheckApi>- partialUpdate: (projectId: string, subjectId: string, id: string, body?: PatchBody) => Promise<DataQualityCheckApi>- destroy: (projectId: string, subjectId: string, id: string) => Promise<void>- run: (projectId: string, subjectId: string, id: string) => Promise<DataQualitySuiteRunApi>- runAll: (projectId: string, subjectId: string) => Promise<DataQualitySuiteRunApi>- runs: (projectId: string, subjectId: string, id: string) => Promise<DataQualityCheckRunApi[]>- checkTypes: (projectId: string, subjectId: string) => Promise<DataQualityCheckTypeApi[]>- health: (projectId: string, subjectId: string) => Promise<DataQualitySubjectHealthApi>- suiteRuns: (- projectId: string,- subjectId: string,- params?: PageParams- ) => Promise<PaginatedDataQualitySuiteRunListApi>- suiteRunRetrieve: (projectId: string, subjectId: string, id: string) => Promise<DataQualitySuiteRunApi>- suiteRunCheckRuns: (projectId: string, subjectId: string, id: string) => Promise<DataQualityCheckRunApi[]>-}--const ROUTES: Record<DataQualitySubjectType, SubjectRoutes> = {- table: {- list: warehouseTablesChecksList,- create: warehouseTablesChecksCreate,- partialUpdate: warehouseTablesChecksPartialUpdate,- destroy: warehouseTablesChecksDestroy,- run: warehouseTablesChecksRunCreate,- runAll: warehouseTablesChecksRunAllCreate,- runs: warehouseTablesChecksRunsList,- checkTypes: warehouseTablesChecksCheckTypesList,- health: warehouseTablesChecksHealthRetrieve,- suiteRuns: warehouseTablesCheckSuiteRunsList,- suiteRunRetrieve: warehouseTablesCheckSuiteRunsRetrieve,- suiteRunCheckRuns: warehouseTablesCheckSuiteRunsCheckRunsList,- },- view: {- list: warehouseSavedQueriesChecksList,- create: warehouseSavedQueriesChecksCreate,- partialUpdate: warehouseSavedQueriesChecksPartialUpdate,- destroy: warehouseSavedQueriesChecksDestroy,- run: warehouseSavedQueriesChecksRunCreate,- runAll: warehouseSavedQueriesChecksRunAllCreate,- runs: warehouseSavedQueriesChecksRunsList,- checkTypes: warehouseSavedQueriesChecksCheckTypesList,- health: warehouseSavedQueriesChecksHealthRetrieve,- suiteRuns: warehouseSavedQueriesCheckSuiteRunsList,- suiteRunRetrieve: warehouseSavedQueriesCheckSuiteRunsRetrieve,- suiteRunCheckRuns: warehouseSavedQueriesCheckSuiteRunsCheckRunsList,- },- metric: {- list: dataCatalogMetricsChecksList,- create: dataCatalogMetricsChecksCreate,- partialUpdate: dataCatalogMetricsChecksPartialUpdate,- destroy: dataCatalogMetricsChecksDestroy,- run: dataCatalogMetricsChecksRunCreate,- runAll: dataCatalogMetricsChecksRunAllCreate,- runs: dataCatalogMetricsChecksRunsList,- checkTypes: dataCatalogMetricsChecksCheckTypesList,- health: dataCatalogMetricsChecksHealthRetrieve,- suiteRuns: dataCatalogMetricsCheckSuiteRunsList,- suiteRunRetrieve: dataCatalogMetricsCheckSuiteRunsRetrieve,- suiteRunCheckRuns: dataCatalogMetricsCheckSuiteRunsCheckRunsList,- },-}+type CreateBody = Omit<Parameters<typeof dataQualityChecksCreate>[1], 'subject_type' | 'subject_uuid'>+type PatchBody = Parameters<typeof dataQualityChecksPartialUpdate>[2]function projectId(): string {return String(ApiConfig.getCurrentTeamId())}-function routesFor({ subjectType }: DataQualitySubjectRef): SubjectRoutes {- return ROUTES[subjectType]+function subjectParams(ref: DataQualitySubjectRef): { subject_type: DataQualitySubjectType; subject_uuid: string } {+ return { subject_type: ref.subjectType, subject_uuid: ref.subjectId }+}++function emptyHealth(ref: DataQualitySubjectRef): DataQualitySubjectHealthApi {+ return { ...subjectParams(ref), health: 'unknown', checks_total: 0, checks_failing: 0 }}export const checksApi = {metricSubjects: (): Promise<DataQualityMetricSubjectApi[]> => dataQualityChecksMetricSubjectsList(projectId()),+ subjects: (): Promise<DataQualitySubjectApi[]> => dataQualityChecksSubjectsList(projectId()),+outputSchema: (ref: DataQualitySubjectRef): Promise<DataQualityOutputSchemaApi> => {if (ref.subjectType !== 'metric') {return Promise.resolve({ columns: [] })}- return dataCatalogMetricsChecksOutputSchemaRetrieve(projectId(), ref.subjectId)+ return dataQualityChecksOutputSchemaRetrieve(projectId(), subjectParams(ref))},- list: (ref: DataQualitySubjectRef, limit: number): Promise<PaginatedDataQualityCheckListApi> =>- routesFor(ref).list(projectId(), ref.subjectId, { limit }),+ list: (ref: DataQualitySubjectRef, limit: number): Promise<PaginatedDataQualityOverviewCheckListApi> =>+ dataQualityChecksList(projectId(), { ...subjectParams(ref), limit }),create: (ref: DataQualitySubjectRef, body: CreateBody): Promise<DataQualityCheckApi> =>- routesFor(ref).create(projectId(), ref.subjectId, body),+ dataQualityChecksCreate(projectId(), { ...body, ...subjectParams(ref) }),- partialUpdate: (ref: DataQualitySubjectRef, id: string, body: PatchBody): Promise<DataQualityCheckApi> =>- routesFor(ref).partialUpdate(projectId(), ref.subjectId, id, body),+ partialUpdate: (id: string, body: PatchBody): Promise<DataQualityCheckApi> =>+ dataQualityChecksPartialUpdate(projectId(), id, body),- destroy: (ref: DataQualitySubjectRef, id: string): Promise<void> =>- routesFor(ref).destroy(projectId(), ref.subjectId, id),+ destroy: (id: string): Promise<void> => dataQualityChecksDestroy(projectId(), id),- run: (ref: DataQualitySubjectRef, id: string): Promise<DataQualitySuiteRunApi> =>- routesFor(ref).run(projectId(), ref.subjectId, id),+ run: (id: string): Promise<DataQualitySuiteRunApi> => dataQualityChecksRunCreate(projectId(), id),runAll: (ref: DataQualitySubjectRef): Promise<DataQualitySuiteRunApi> =>- routesFor(ref).runAll(projectId(), ref.subjectId),+ dataQualityRunsCreate(projectId(), subjectParams(ref)),- runs: (ref: DataQualitySubjectRef, id: string): Promise<DataQualityCheckRunApi[]> =>- routesFor(ref).runs(projectId(), ref.subjectId, id),+ runs: (id: string): Promise<DataQualityCheckRunApi[]> => dataQualityChecksRunsList(projectId(), id),checkTypes: (ref: DataQualitySubjectRef): Promise<DataQualityCheckTypeApi[]> =>- routesFor(ref).checkTypes(projectId(), ref.subjectId),+ dataQualityChecksCheckTypesList(projectId(), { subject_type: ref.subjectType }),- health: (ref: DataQualitySubjectRef): Promise<DataQualitySubjectHealthApi> =>- routesFor(ref).health(projectId(), ref.subjectId),+ health: async (ref: DataQualitySubjectRef): Promise<DataQualitySubjectHealthApi> => {+ const rollups = await dataQualityChecksHealthList(projectId(), subjectParams(ref))+ return rollups[0] ?? emptyHealth(ref)+ },suiteRuns: (ref: DataQualitySubjectRef, limit: number): Promise<PaginatedDataQualitySuiteRunListApi> =>- routesFor(ref).suiteRuns(projectId(), ref.subjectId, { limit }),+ dataQualityRunsList(projectId(), { ...subjectParams(ref), limit }),++ suiteRunRetrieve: (id: string): Promise<DataQualitySuiteRunApi> => dataQualityRunsRetrieve(projectId(), id),++ suiteRunCheckRuns: (id: string): Promise<DataQualityCheckRunApi[]> => dataQualityRunsCheckRunsList(projectId(), id),- suiteRunRetrieve: (ref: DataQualitySubjectRef, id: string): Promise<DataQualitySuiteRunApi> =>- routesFor(ref).suiteRunRetrieve(projectId(), ref.subjectId, id),+ schedule: (ref: DataQualitySubjectRef): Promise<DataQualityCheckScheduleApi> =>+ dataQualityChecksScheduleRetrieve(projectId(), subjectParams(ref)),- suiteRunCheckRuns: (ref: DataQualitySubjectRef, id: string): Promise<DataQualityCheckRunApi[]> =>- routesFor(ref).suiteRunCheckRuns(projectId(), ref.subjectId, id),+ updateSchedule: (+ ref: DataQualitySubjectRef,+ patch: PatchedDataQualityCheckScheduleUpdateApi+ ): Promise<DataQualityCheckScheduleApi> =>+ dataQualityChecksSchedulePartialUpdate(projectId(), { ...patch, ...subjectParams(ref) }),}diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.tsindex b2fe0767d36b..068311a936d2 100644--- a/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.test.ts@@ -10,16 +10,11 @@ import { expectLogic } from '~/test/keaTestUtils'import { DataQualitySubjectRef } from './checksApi'import { DataQualityCheckEditorLogicProps, dataQualityCheckEditorLogic } from './dataQualityCheckEditorLogic'import {- dataCatalogMetricsChecksCheckTypesList,- dataCatalogMetricsChecksCreate,- dataCatalogMetricsChecksOutputSchemaRetrieve,- dataCatalogMetricsChecksPartialUpdate,+ dataQualityChecksCheckTypesList,+ dataQualityChecksCreate,dataQualityChecksMetricSubjectsList,- warehouseSavedQueriesChecksCheckTypesList,- warehouseSavedQueriesChecksCreate,- warehouseSavedQueriesChecksPartialUpdate,- warehouseTablesChecksCheckTypesList,- warehouseTablesChecksCreate,+ dataQualityChecksOutputSchemaRetrieve,+ dataQualityChecksPartialUpdate,} from './generated/api'import type { DataQualityCheckApi } from './generated/api.schemas'import { CheckTypeEnumApi } from './generated/api.schemas'@@ -91,17 +86,11 @@ jest.mock('scenes/data-management/database/databaseTableListLogic', () => {})jest.mock('./generated/api', () => ({- dataCatalogMetricsChecksCheckTypesList: jest.fn(),- dataCatalogMetricsChecksCreate: jest.fn(),- dataCatalogMetricsChecksOutputSchemaRetrieve: jest.fn(),- dataCatalogMetricsChecksPartialUpdate: jest.fn(),+ dataQualityChecksCheckTypesList: jest.fn(),+ dataQualityChecksCreate: jest.fn(),dataQualityChecksMetricSubjectsList: jest.fn(),- warehouseSavedQueriesChecksCreate: jest.fn(),- warehouseSavedQueriesChecksPartialUpdate: jest.fn(),- warehouseSavedQueriesChecksCheckTypesList: jest.fn(),- warehouseTablesChecksCreate: jest.fn(),- warehouseTablesChecksPartialUpdate: jest.fn(),- warehouseTablesChecksCheckTypesList: jest.fn(),+ dataQualityChecksOutputSchemaRetrieve: jest.fn(),+ dataQualityChecksPartialUpdate: jest.fn(),}))const VIEW_SUBJECT: DataQualitySubjectRef = { subjectType: 'view', subjectId: 'view-1' }@@ -169,12 +158,12 @@ describe('dataQualityCheckEditorLogic', () => {beforeEach(() => {jest.clearAllMocks()silenceKeaLoadersErrors()- ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG)- ;(warehouseTablesChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG)+ ;(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' },])- ;(dataCatalogMetricsChecksOutputSchemaRetrieve as jest.Mock).mockResolvedValue({+ ;(dataQualityChecksOutputSchemaRetrieve as jest.Mock).mockResolvedValue({columns: [{ name: 'day', type: 'Nullable(Date)' },{ name: 'signups', type: 'UInt64' },@@ -188,10 +177,10 @@ describe('dataQualityCheckEditorLogic', () => {})it('authors metric SQL with a relation placeholder, no column, and no raw query execution', async () => {- ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql'))- ;(dataCatalogMetricsChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ check_type: 'custom_sql' }))+ ;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ check_type: 'custom_sql' }))await mountLogic()logic.actions.openEditor(null, { subjectType: 'metric', subjectId: 'metric-1' })await expectLogic(logic).toFinishAllListeners()@@ -211,10 +200,11 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.setCheckFormValue('customSql', 'SELECT * FROM {metric} WHERE signups < 100')logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(dataCatalogMetricsChecksCreate).toHaveBeenCalledWith(+ expect(dataQualityChecksCreate).toHaveBeenCalledWith('1',- 'metric-1',expect.objectContaining({+ subject_type: 'metric',+ subject_uuid: 'metric-1',check_type: 'custom_sql',column_name: '',config: { query: 'SELECT * FROM {metric} WHERE signups < 100' },@@ -224,7 +214,7 @@ describe('dataQualityCheckEditorLogic', () => {})it('offers HogQL metrics in the overview and pre-fills the metric query after selection', async () => {- ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql'))await mountLogic({ surface: 'overview' })@@ -249,7 +239,10 @@ describe('dataQualityCheckEditorLogic', () => {checkType: 'custom_sql',customSql: 'SELECT *\nFROM {metric}\nWHERE <failure condition>',})- expect(dataCatalogMetricsChecksOutputSchemaRetrieve).toHaveBeenCalledWith('1', 'metric-1')+ expect(dataQualityChecksOutputSchemaRetrieve).toHaveBeenCalledWith('1', {+ subject_type: 'metric',+ subject_uuid: 'metric-1',+ })})it('uses warehouse field types as the selected table output schema', async () => {@@ -268,12 +261,12 @@ describe('dataQualityCheckEditorLogic', () => {it('does not let a late table catalog replace the metric-only check types', async () => {let resolveTableCatalog: (catalog: typeof CHECK_TYPE_CATALOG) => void = () => {}- ;(warehouseTablesChecksCheckTypesList as jest.Mock).mockReturnValue(+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockReturnValue(new Promise((resolve) => {resolveTableCatalog = resolve}))- ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql'))await mountLogic()@@ -292,7 +285,7 @@ describe('dataQualityCheckEditorLogic', () => {resolvePreview = resolve}))- ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql'))await mountLogic()@@ -339,25 +332,27 @@ describe('dataQualityCheckEditorLogic', () => {{ column_name: '', config: { query: 'SELECT 1' } },],])('sends only the config %s needs', async (checkType, formValues, expectedBody) => {- ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ id: 'check-new' }))+ ;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ id: 'check-new' }))await mountLogic()await openWith(null, formValues)logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksCreate).toHaveBeenCalledWith('1', 'view-1', {+ expect(dataQualityChecksCreate).toHaveBeenCalledWith('1', {check_type: checkType,severity: 'error',tags: [],...expectedBody,+ subject_type: 'view',+ subject_uuid: 'view-1',})})it('sends the whole definition when an assertion is edited', async () => {// The old check kept its assertion; an edit now has to carry type, column and config together// so switching type cannot leave the previous type's config behind.- ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())+ ;(dataQualityChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())await mountLogic()await openWith(buildCheck({ name: 'orders_not_null', description: 'why' }), {checkType: 'accepted_values',@@ -368,7 +363,7 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith('1', 'view-1', 'check-1', {+ expect(dataQualityChecksPartialUpdate).toHaveBeenCalledWith('1', 'check-1', {check_type: 'accepted_values',column_name: 'status',config: { values: ['paid'] },@@ -382,10 +377,10 @@ describe('dataQualityCheckEditorLogic', () => {it('leaves an unchanged assertion out of a metadata-only edit', async () => {// The backend revalidates the definition whenever a request carries one, which a metric that// moved off its HogQL definition fails. Renaming its check must not go down that path.- ;(dataCatalogMetricsChecksCheckTypesList as jest.Mock).mockResolvedValue(+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockResolvedValue(CHECK_TYPE_CATALOG.filter((type) => type.check_type === 'custom_sql'))- ;(dataCatalogMetricsChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())+ ;(dataQualityChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())await mountLogic()logic.actions.openEditor(buildCheck({@@ -403,7 +398,7 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(dataCatalogMetricsChecksPartialUpdate).toHaveBeenCalledWith('1', 'metric-1', 'check-1', {+ expect(dataQualityChecksPartialUpdate).toHaveBeenCalledWith('1', 'check-1', {severity: 'error',name: 'signups_floor',description: 'renamed',@@ -414,7 +409,7 @@ describe('dataQualityCheckEditorLogic', () => {it('does not submit before the check-type catalog arrives', async () => {// Enter can submit while the catalog request is still pending. Without it there is no column// requirement to validate against, so the payload would omit column_name and be rejected.- ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock).mockReturnValueOnce(new Promise(() => {}))+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockReturnValueOnce(new Promise(() => {}))await mountLogic()logic.actions.openEditor(null, VIEW_SUBJECT, COLUMNS)@@ -424,12 +419,12 @@ describe('dataQualityCheckEditorLogic', () => {await Promise.resolve()}- expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()+ expect(dataQualityChecksCreate).not.toHaveBeenCalled()})it('sends blank metadata on an edit so it can be cleared', async () => {// Create omits blank optional fields, which would leave an edit unable to remove a name.- ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())+ ;(dataQualityChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())await mountLogic()await openWith(buildCheck({ name: 'orders_not_null', description: 'why', tags: ['core'] }), {name: '',@@ -440,9 +435,8 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith(+ expect(dataQualityChecksPartialUpdate).toHaveBeenCalledWith('1',- 'view-1','check-1',expect.objectContaining({ name: '', description: '', tags: [] }))@@ -460,13 +454,13 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()+ expect(dataQualityChecksCreate).not.toHaveBeenCalled()expect(logic.values.isOpen).toBe(true)})it('creates the check once when the form is submitted twice', async () => {// Enter submits the form even while the save button is disabled by its loading state.- ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ id: 'check-new' }))+ ;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ id: 'check-new' }))await mountLogic()await openWith(null, { checkType: 'not_null', columnName: 'customer_id' })@@ -474,7 +468,7 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksCreate).toHaveBeenCalledTimes(1)+ expect(dataQualityChecksCreate).toHaveBeenCalledTimes(1)})it('shows a stale failing preview until the custom SQL is tested again', async () => {@@ -605,7 +599,7 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()+ expect(dataQualityChecksCreate).not.toHaveBeenCalled()expect(logic.values.checkFormErrors.customSql).toEqual('Unknown table')})@@ -617,14 +611,14 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()+ expect(dataQualityChecksCreate).not.toHaveBeenCalled()expect(logic.values.checkFormErrors.customSql).toEqual('Checking query...')})it('saves a query nobody edited while Monaco validates the one it opened with', async () => {// Monaco validates the query as soon as the editor mounts. That pass is not an edit, so it// must not hold the save while it runs.- ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())+ ;(dataQualityChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck())await mountLogic()await openWith(buildCheck({@@ -639,9 +633,8 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith(+ expect(dataQualityChecksPartialUpdate).toHaveBeenCalledWith('1',- 'view-1','check-1',expect.objectContaining({ description: 'Every order keeps a positive id' }))@@ -681,7 +674,7 @@ describe('dataQualityCheckEditorLogic', () => {'A check with this definition already exists.',],])('keeps the draft open and shows %s', async (_case, data, field, message) => {- ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockRejectedValue(apiError(data))+ ;(dataQualityChecksCreate as jest.Mock).mockRejectedValue(apiError(data))await mountLogic()await openWith(null, { checkType: 'custom_sql', customSql: 'SELECT 1' })@@ -694,7 +687,7 @@ describe('dataQualityCheckEditorLogic', () => {})it('shows a failure with no field of its own in the modal banner', async () => {- ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockRejectedValue(+ ;(dataQualityChecksCreate as jest.Mock).mockRejectedValue(apiError({ detail: 'nope', code: 'permission_denied' }, 403))await mountLogic()@@ -709,7 +702,7 @@ describe('dataQualityCheckEditorLogic', () => {it('hands the saved check to the surface that opened it, and offers to run it', async () => {const saved = buildCheck({ id: 'check-new' })- ;(warehouseSavedQueriesChecksCreate as jest.Mock).mockResolvedValue(saved)+ ;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(saved)await mountLogic()await openWith(null, { checkType: 'not_null', columnName: 'customer_id' })@@ -724,9 +717,9 @@ describe('dataQualityCheckEditorLogic', () => {expect(onRunNow).toHaveBeenCalledWith(saved)})- it('routes an edit to the subject the check belongs to, not the surface', async () => {+ it("names the check's own subject, not the surface it was opened from", async () => {// The overview edits checks on every table and view, so the subject travels with the check.- ;(warehouseTablesChecksCreate as jest.Mock).mockResolvedValue(buildCheck())+ ;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(buildCheck())await mountLogic({ surface: 'overview' })logic.actions.openEditor(null, { subjectType: 'table', subjectId: 'table-9' }, COLUMNS)await expectLogic(logic).toFinishAllListeners()@@ -735,48 +728,41 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseTablesChecksCreate).toHaveBeenCalledWith('1', 'table-9', expect.anything())- expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()+ expect(dataQualityChecksCreate).toHaveBeenCalledWith(+ '1',+ expect.objectContaining({ subject_type: 'table', subject_uuid: 'table-9' })+ )})- it.each<[string, DataQualitySubjectRef, string, string, jest.Mock]>([- [- 'a table',- { subjectType: 'table', subjectId: 'table-9' },- 'customer_id',- 'table-9',- warehouseTablesChecksCreate as jest.Mock,- ],- [- 'a view',- { subjectType: 'view', subjectId: 'view-7' },- 'order_id',- 'view-7',- warehouseSavedQueriesChecksCreate as jest.Mock,- ],- ])(- 'opens without a subject and creates against %s after it is picked',- async (_case, subject, column, id, create) => {- create.mockResolvedValue(buildCheck({ id: 'check-new' }))- await mountLogic({ surface: 'overview' })+ it.each<[string, DataQualitySubjectRef, string]>([+ ['a table', { subjectType: 'table', subjectId: 'table-9' }, 'customer_id'],+ ['a view', { subjectType: 'view', subjectId: 'view-7' }, 'order_id'],+ ])('opens without a subject and creates against %s after it is picked', async (_case, subject, column) => {+ ;(dataQualityChecksCreate as jest.Mock).mockResolvedValue(buildCheck({ id: 'check-new' }))+ await mountLogic({ surface: 'overview' })- logic.actions.openEditor(null, null)- await expectLogic(logic).toFinishAllListeners()+ logic.actions.openEditor(null, null)+ await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksCheckTypesList).not.toHaveBeenCalled()- expect(warehouseTablesChecksCheckTypesList).not.toHaveBeenCalled()- expect((databaseTableListLogic.values as unknown as { loadCount: number }).loadCount).toEqual(1)+ expect(dataQualityChecksCheckTypesList).not.toHaveBeenCalled()+ expect((databaseTableListLogic.values as unknown as { loadCount: number }).loadCount).toEqual(1)- logic.actions.setSubject(subject)- await expectLogic(logic).toFinishAllListeners()- logic.actions.setCheckFormValues({ checkType: 'not_null', columnName: column })+ logic.actions.setSubject(subject)+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setCheckFormValues({ checkType: 'not_null', columnName: column })- logic.actions.submitCheckForm()- await expectLogic(logic).toFinishAllListeners()+ logic.actions.submitCheckForm()+ await expectLogic(logic).toFinishAllListeners()- expect(create).toHaveBeenCalledWith('1', id, expect.objectContaining({ column_name: column }))- }- )+ expect(dataQualityChecksCreate).toHaveBeenCalledWith(+ '1',+ expect.objectContaining({+ column_name: column,+ subject_type: subject.subjectType,+ subject_uuid: subject.subjectId,+ })+ )+ })it('clears subject-specific errors and columns when the picked subject changes', async () => {await mountLogic({ surface: 'overview' })@@ -807,8 +793,8 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.setSubject({ subjectType: 'view', subjectId: 'view-7' })await expectLogic(logic).toFinishAllListeners()- expect(warehouseTablesChecksCheckTypesList).toHaveBeenCalledWith('1', 'table-9')- expect(warehouseSavedQueriesChecksCheckTypesList).toHaveBeenCalledWith('1', 'view-7')+ expect(dataQualityChecksCheckTypesList).toHaveBeenCalledWith('1', { subject_type: 'table' })+ expect(dataQualityChecksCheckTypesList).toHaveBeenCalledWith('1', { subject_type: 'view' })})it('does not create a check until a subject is picked', async () => {@@ -819,12 +805,11 @@ describe('dataQualityCheckEditorLogic', () => {logic.actions.submitCheckForm()await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksCreate).not.toHaveBeenCalled()- expect(warehouseTablesChecksCreate).not.toHaveBeenCalled()+ expect(dataQualityChecksCreate).not.toHaveBeenCalled()})it('clears the check type error when a failed catalog request is retried', async () => {- ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock)+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockRejectedValueOnce(new Error('down')).mockResolvedValueOnce(CHECK_TYPE_CATALOG)await mountLogic()@@ -842,7 +827,7 @@ describe('dataQualityCheckEditorLogic', () => {it('drops a superseded check type request so a late failure keeps the newer catalog', async () => {let failFirst: (error: unknown) => void = () => {}- ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock)+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockImplementationOnce(() => new Promise((_resolve, reject) => (failFirst = reject))).mockResolvedValueOnce(CHECK_TYPE_CATALOG)await mountLogic()@@ -887,9 +872,7 @@ describe('dataQualityCheckEditorLogic', () => {})it('closes a saved draft without asking, since it is no longer unsaved', async () => {- ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(- buildCheck({ description: 'written' })- )+ ;(dataQualityChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck({ description: 'written' }))await mountLogic()await openWith(buildCheck(), { description: 'written' })diff --git a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts b/products/data_quality/frontend/dataQualityCheckEditorLogic.tsindex 92f2fa154ff4..df3e766ae5a5 100644--- a/products/data_quality/frontend/dataQualityCheckEditorLogic.ts+++ b/products/data_quality/frontend/dataQualityCheckEditorLogic.ts@@ -141,7 +141,7 @@ function definitionPayload(form: CheckFormValues, requiresColumn: boolean): Chectype CheckDefinitionPayload = Pick<CheckCreatePayload, 'check_type' | 'column_name' | 'config'>type CheckCreatePayload = Parameters<typeof checksApi.create>[1]-type CheckEditPayload = Parameters<typeof checksApi.partialUpdate>[2]+type CheckEditPayload = Parameters<typeof checksApi.partialUpdate>[1]export function checkCreatePayload(form: CheckFormValues, requiresColumn: boolean): CheckCreatePayload {return {@@ -929,7 +929,6 @@ export const dataQualityCheckEditorLogic = kea<dataQualityCheckEditorLogicType>(try {const saved = editing? await checksApi.partialUpdate(- values.subject,editing.id,checkEditPayload(form, values.requiresColumn, editing))diff --git a/products/data_quality/frontend/dataQualityChecksLogic.test.ts b/products/data_quality/frontend/dataQualityChecksLogic.test.tsindex 0738a8936281..566f08e2c5dc 100644--- a/products/data_quality/frontend/dataQualityChecksLogic.test.ts+++ b/products/data_quality/frontend/dataQualityChecksLogic.test.ts@@ -6,21 +6,15 @@ import { expectLogic } from '~/test/keaTestUtils'import { DataQualityChecksLogicProps, dataQualityChecksLogic } from './dataQualityChecksLogic'import {- dataCatalogMetricsChecksList,- dataCatalogMetricsChecksHealthRetrieve,- dataCatalogMetricsCheckSuiteRunsList,- warehouseSavedQueriesCheckSuiteRunsCheckRunsList,- warehouseSavedQueriesCheckSuiteRunsList,- warehouseSavedQueriesCheckSuiteRunsRetrieve,- warehouseSavedQueriesChecksDestroy,- warehouseSavedQueriesChecksHealthRetrieve,- warehouseSavedQueriesChecksList,- warehouseSavedQueriesChecksPartialUpdate,- warehouseSavedQueriesChecksRunAllCreate,- warehouseSavedQueriesChecksRunCreate,- warehouseTablesCheckSuiteRunsList,- warehouseTablesChecksHealthRetrieve,- warehouseTablesChecksList,+ dataQualityChecksDestroy,+ dataQualityChecksHealthList,+ dataQualityChecksList,+ dataQualityChecksPartialUpdate,+ dataQualityChecksRunCreate,+ dataQualityRunsCheckRunsList,+ dataQualityRunsCreate,+ dataQualityRunsList,+ dataQualityRunsRetrieve,} from './generated/api'import type { DataQualityCheckApi, DataQualitySuiteRunApi } from './generated/api.schemas'import { CheckTypeEnumApi } from './generated/api.schemas'@@ -52,33 +46,18 @@ jest.mock('scenes/data-management/database/databaseTableListLogic', () => ({}))jest.mock('./generated/api', () => ({- dataCatalogMetricsChecksList: jest.fn(),- dataCatalogMetricsChecksHealthRetrieve: jest.fn(),- dataCatalogMetricsCheckSuiteRunsList: jest.fn(),- warehouseSavedQueriesChecksList: jest.fn(),- warehouseSavedQueriesChecksCreate: jest.fn(),- warehouseSavedQueriesChecksPartialUpdate: jest.fn(),- warehouseSavedQueriesChecksDestroy: jest.fn(),- warehouseSavedQueriesChecksRunCreate: jest.fn(),- warehouseSavedQueriesChecksRunAllCreate: jest.fn(),- warehouseSavedQueriesChecksRunsList: jest.fn(),- warehouseSavedQueriesChecksCheckTypesList: jest.fn(),- warehouseSavedQueriesChecksHealthRetrieve: jest.fn(),- warehouseSavedQueriesCheckSuiteRunsList: jest.fn(),- warehouseSavedQueriesCheckSuiteRunsRetrieve: jest.fn(),- warehouseSavedQueriesCheckSuiteRunsCheckRunsList: jest.fn(),- warehouseTablesChecksList: jest.fn(),- warehouseTablesChecksCreate: jest.fn(),- warehouseTablesChecksPartialUpdate: jest.fn(),- warehouseTablesChecksDestroy: jest.fn(),- warehouseTablesChecksRunCreate: jest.fn(),- warehouseTablesChecksRunAllCreate: jest.fn(),- warehouseTablesChecksRunsList: jest.fn(),- warehouseTablesChecksCheckTypesList: jest.fn(),- warehouseTablesChecksHealthRetrieve: jest.fn(),- warehouseTablesCheckSuiteRunsList: jest.fn(),- warehouseTablesCheckSuiteRunsRetrieve: jest.fn(),- warehouseTablesCheckSuiteRunsCheckRunsList: jest.fn(),+ dataQualityChecksList: jest.fn(),+ dataQualityChecksCreate: jest.fn(),+ dataQualityChecksPartialUpdate: jest.fn(),+ dataQualityChecksDestroy: jest.fn(),+ dataQualityChecksRunCreate: jest.fn(),+ dataQualityChecksRunsList: jest.fn(),+ dataQualityChecksCheckTypesList: jest.fn(),+ dataQualityChecksHealthList: jest.fn(),+ dataQualityRunsList: jest.fn(),+ dataQualityRunsCreate: jest.fn(),+ dataQualityRunsRetrieve: jest.fn(),+ dataQualityRunsCheckRunsList: jest.fn(),}))const VIEW_PROPS: DataQualityChecksLogicProps = { subjectType: 'view', subjectId: 'view-1' }@@ -129,27 +108,11 @@ describe('dataQualityChecksLogic', () => {beforeEach(() => {jest.clearAllMocks()silenceKeaLoadersErrors()- ;(warehouseSavedQueriesChecksList as jest.Mock).mockResolvedValue({ results: [buildCheck()] })- ;(warehouseTablesChecksList as jest.Mock).mockResolvedValue({ results: [] })- ;(warehouseSavedQueriesChecksHealthRetrieve as jest.Mock).mockResolvedValue({- health: 'healthy',- checks_total: 1,- checks_failing: 0,- })- ;(warehouseTablesChecksHealthRetrieve as jest.Mock).mockResolvedValue({- health: 'unknown',- checks_total: 0,- checks_failing: 0,- })- ;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })- ;(warehouseTablesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })- ;(dataCatalogMetricsChecksList as jest.Mock).mockResolvedValue({ results: [] })- ;(dataCatalogMetricsChecksHealthRetrieve as jest.Mock).mockResolvedValue({- health: 'unknown',- checks_total: 0,- checks_failing: 0,- })- ;(dataCatalogMetricsCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({ results: [buildCheck()] })+ ;(dataQualityChecksHealthList as jest.Mock).mockResolvedValue([+ { health: 'healthy', checks_total: 1, checks_failing: 0 },+ ])+ ;(dataQualityRunsList as jest.Mock).mockResolvedValue({ results: [] })})afterEach(() => {@@ -158,27 +121,21 @@ describe('dataQualityChecksLogic', () => {logic?.unmount()})- it.each<[DataQualityChecksLogicProps, jest.Mock, jest.Mock]>([- [- { subjectType: 'metric', subjectId: 'metric-1' },- dataCatalogMetricsChecksList as jest.Mock,- warehouseTablesChecksList as jest.Mock,- ],- [VIEW_PROPS, warehouseSavedQueriesChecksList as jest.Mock, warehouseTablesChecksList as jest.Mock],- [- { subjectType: 'table', subjectId: 'table-1' },- warehouseTablesChecksList as jest.Mock,- warehouseSavedQueriesChecksList as jest.Mock,- ],- ])('routes requests to the %o subject family', async (props, expected, notExpected) => {+ it.each<DataQualityChecksLogicProps>([+ { subjectType: 'metric', subjectId: 'metric-1' },+ VIEW_PROPS,+ { subjectType: 'table', subjectId: 'table-1' },+ ])('narrows the project-wide routes to its own %o subject', async (props) => {await mountLogic(props)- expect(expected).toHaveBeenCalledWith('1', props.subjectId, { limit: 100 })- expect(notExpected).not.toHaveBeenCalled()+ const subject = { subject_type: props.subjectType, subject_uuid: props.subjectId }+ expect(dataQualityChecksList).toHaveBeenCalledWith('1', { ...subject, limit: 100 })+ expect(dataQualityChecksHealthList).toHaveBeenCalledWith('1', subject)+ expect(dataQualityRunsList).toHaveBeenCalledWith('1', { ...subject, limit: 20 })})it('keeps a failed metric check load distinct from an empty result and can retry', async () => {- ;(dataCatalogMetricsChecksList as jest.Mock).mockRejectedValueOnce(new Error('Service unavailable'))+ ;(dataQualityChecksList as jest.Mock).mockRejectedValueOnce(new Error('Service unavailable'))await mountLogic({ subjectType: 'metric', subjectId: 'metric-1' })expect(logic.values.checksLoadError).toBe('Service unavailable')expect(logic.values.checksLoaded).toBe(false)@@ -190,7 +147,7 @@ describe('dataQualityChecksLogic', () => {it('keeps the loaded checks when a later refresh fails', async () => {await mountLogic()- ;(warehouseSavedQueriesChecksList as jest.Mock).mockRejectedValueOnce(new Error('Service unavailable'))+ ;(dataQualityChecksList as jest.Mock).mockRejectedValueOnce(new Error('Service unavailable'))logic.actions.loadChecks()await expectLogic(logic).toFinishAllListeners()@@ -200,7 +157,7 @@ describe('dataQualityChecksLogic', () => {})it('fails closed without a toast when the subject is forbidden', async () => {- ;(warehouseSavedQueriesChecksList as jest.Mock).mockRejectedValue(forbidden())+ ;(dataQualityChecksList as jest.Mock).mockRejectedValue(forbidden())await mountLogic()@@ -211,13 +168,13 @@ describe('dataQualityChecksLogic', () => {// A failed history request leaves the loader's empty default behind, which the table would// otherwise present as "no check runs yet" - a claim the request never established.it('marks the run history as failed, and clears that once a retry succeeds', async () => {- ;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockRejectedValue(new Error('boom'))+ ;(dataQualityRunsList as jest.Mock).mockRejectedValue(new Error('boom'))await mountLogic()expect(logic.values.suiteRuns).toEqual([])expect(logic.values.suiteRunsError).toBe(true)- ;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [] })+ ;(dataQualityRunsList as jest.Mock).mockResolvedValue({ results: [] })await expectLogic(logic, () => {logic.actions.loadSuiteRuns()@@ -227,31 +184,29 @@ describe('dataQualityChecksLogic', () => {})it('drops the deleted row and refreshes health', async () => {- ;(warehouseSavedQueriesChecksDestroy as jest.Mock).mockResolvedValue(undefined)+ ;(dataQualityChecksDestroy as jest.Mock).mockResolvedValue(undefined)await mountLogic()logic.actions.deleteCheck('check-1')await expectLogic(logic).toFinishAllListeners()expect(logic.values.checks).toEqual([])- expect(warehouseSavedQueriesChecksHealthRetrieve).toHaveBeenCalledTimes(2)+ expect(dataQualityChecksHealthList).toHaveBeenCalledTimes(2)})it('patches only the enabled flag when a check is toggled', async () => {- ;(warehouseSavedQueriesChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck({ enabled: false }))+ ;(dataQualityChecksPartialUpdate as jest.Mock).mockResolvedValue(buildCheck({ enabled: false }))await mountLogic()logic.actions.toggleCheckEnabled('check-1', false)await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksPartialUpdate).toHaveBeenCalledWith('1', 'view-1', 'check-1', {- enabled: false,- })+ expect(dataQualityChecksPartialUpdate).toHaveBeenCalledWith('1', 'check-1', { enabled: false })expect(logic.values.enabledChecksCount).toEqual(0)})it('skips polling and refreshes when a run comes back already finished', async () => {- ;(warehouseSavedQueriesChecksRunCreate as jest.Mock).mockResolvedValue(+ ;(dataQualityChecksRunCreate as jest.Mock).mockResolvedValue(buildSuiteRun({ status: 'completed', checks_passed: 2 }))await mountLogic()@@ -260,8 +215,8 @@ describe('dataQualityChecksLogic', () => {await expectLogic(logic).toFinishAllListeners()expect(logic.values.isSuiteRunning).toBe(false)- expect(warehouseSavedQueriesCheckSuiteRunsRetrieve).not.toHaveBeenCalled()- expect(warehouseSavedQueriesChecksList).toHaveBeenCalledTimes(2)+ expect(dataQualityRunsRetrieve).not.toHaveBeenCalled()+ expect(dataQualityChecksList).toHaveBeenCalledTimes(2)// pluralize() joins the count to the noun with a non-breaking space.expect(lemonToast.success).toHaveBeenCalledWith('All 2\u00a0checks passed')})@@ -269,20 +224,20 @@ describe('dataQualityChecksLogic', () => {it('reloads the run history after completion when it was empty', async () => {// An empty history must still refresh after a run finishes, rather than stay on// "No runs yet", so the reload cannot be conditional on the list having rows.- ;(warehouseSavedQueriesChecksRunCreate as jest.Mock).mockResolvedValue(+ ;(dataQualityChecksRunCreate as jest.Mock).mockResolvedValue(buildSuiteRun({ status: 'completed', checks_passed: 1 }))await mountLogic()- ;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockClear()+ ;(dataQualityRunsList as jest.Mock).mockClear()logic.actions.runCheck('check-1')await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesCheckSuiteRunsList).toHaveBeenCalledTimes(1)+ expect(dataQualityRunsList).toHaveBeenCalledTimes(1)})it('says nothing ran when run all matches no enabled check', async () => {- ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun({ status: 'empty' }))+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun({ status: 'empty' }))await mountLogic()logic.actions.runAll()@@ -293,8 +248,8 @@ describe('dataQualityChecksLogic', () => {})it('reloads the checks once the polled run finishes', async () => {- ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())- ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock)+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(dataQualityRunsRetrieve as jest.Mock).mockResolvedValueOnce(buildSuiteRun()).mockResolvedValue(buildSuiteRun({ status: 'completed', checks_passed: 1, checks_failed: 1 }))await mountLogic()@@ -312,9 +267,9 @@ describe('dataQualityChecksLogic', () => {it('ignores a stale poll after a newer run has replaced the active one', async () => {// A retrieve can still be in flight when a second run starts. The stale terminal response// must not finish the old run and dispose the newer run's poll.- ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun({ id: 'suite-1' }))+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun({ id: 'suite-1' }))let resolveRetrieve: (run: DataQualitySuiteRunApi) => void = () => {}- ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mockReturnValue(+ ;(dataQualityRunsRetrieve as jest.Mock).mockReturnValue(new Promise<DataQualitySuiteRunApi>((resolve) => {resolveRetrieve = resolve})@@ -341,7 +296,7 @@ describe('dataQualityChecksLogic', () => {// Two starts can be in flight at once: the pending guard is per check, and "Run all" is not// blocked by it. A slower earlier request must not replace the run the panel is tracking.let resolveFirst: (run: DataQualitySuiteRunApi) => void = () => {}- ;(warehouseSavedQueriesChecksRunCreate as jest.Mock)+ ;(dataQualityChecksRunCreate as jest.Mock).mockReturnValueOnce(new Promise<DataQualitySuiteRunApi>((resolve) => {resolveFirst = resolve@@ -363,29 +318,27 @@ describe('dataQualityChecksLogic', () => {it('reloads an expanded suite run detail once the run finishes', async () => {// A suite adopted mid-flight can be expanded while it is still running, caching partial rows.- ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())- ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock)+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(dataQualityRunsRetrieve as jest.Mock).mockResolvedValueOnce(buildSuiteRun()).mockResolvedValue(buildSuiteRun({ status: 'completed', checks_passed: 1 }))- ;(warehouseSavedQueriesCheckSuiteRunsCheckRunsList as jest.Mock).mockResolvedValue([])+ ;(dataQualityRunsCheckRunsList as jest.Mock).mockResolvedValue([])await mountLogic()await startRunUnderFakeTimers()logic.actions.loadSuiteRunCheckRuns('suite-1')await drainListeners()- const whileRunning = (warehouseSavedQueriesCheckSuiteRunsCheckRunsList as jest.Mock).mock.calls.length+ const whileRunning = (dataQualityRunsCheckRunsList as jest.Mock).mock.calls.lengthawait advancePoll(3000)await advancePoll(3000)- expect((warehouseSavedQueriesCheckSuiteRunsCheckRunsList as jest.Mock).mock.calls.length).toBeGreaterThan(- whileRunning- )+ expect((dataQualityRunsCheckRunsList as jest.Mock).mock.calls.length).toBeGreaterThan(whileRunning)})it('stops polling a run that never finishes', async () => {- ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())- ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(dataQualityRunsRetrieve as jest.Mock).mockResolvedValue(buildSuiteRun())await mountLogic()await startRunUnderFakeTimers()@@ -397,18 +350,16 @@ describe('dataQualityChecksLogic', () => {expect(logic.values.pollTimedOut).toBe(true)expect(logic.values.isSuiteRunning).toBe(false)- const pollsBeforeGivingUp = (warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length+ const pollsBeforeGivingUp = (dataQualityRunsRetrieve as jest.Mock).mock.calls.lengthawait advancePoll(15000)- expect((warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length).toEqual(- pollsBeforeGivingUp- )+ expect((dataQualityRunsRetrieve as jest.Mock).mock.calls.length).toEqual(pollsBeforeGivingUp)})it('stops polling a run whose retrieve keeps failing', async () => {// A request that keeps rejecting (e.g. a 500 or the flag turned off mid-run) must still honor// the 15 minute cap instead of retrying forever and leaving the panel stuck running.- ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())- ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mockRejectedValue(new Error('boom'))+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(dataQualityRunsRetrieve as jest.Mock).mockRejectedValue(new Error('boom'))await mountLogic()await startRunUnderFakeTimers()@@ -420,41 +371,40 @@ describe('dataQualityChecksLogic', () => {expect(logic.values.pollTimedOut).toBe(true)expect(logic.values.isSuiteRunning).toBe(false)- const pollsBeforeGivingUp = (warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length+ const pollsBeforeGivingUp = (dataQualityRunsRetrieve as jest.Mock).mock.calls.lengthawait advancePoll(15000)- expect((warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length).toEqual(- pollsBeforeGivingUp- )+ expect((dataQualityRunsRetrieve as jest.Mock).mock.calls.length).toEqual(pollsBeforeGivingUp)})it('stops polling and denies access when a poll is forbidden', async () => {// A permanent 403 mid-run (flag off, or query access revoked) should take the access-denied// path at once rather than retrying until the 15 minute cap.- ;(warehouseSavedQueriesChecksRunAllCreate as jest.Mock).mockResolvedValue(buildSuiteRun())- ;(warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mockRejectedValue(forbidden())+ ;(dataQualityRunsCreate as jest.Mock).mockResolvedValue(buildSuiteRun())+ ;(dataQualityRunsRetrieve as jest.Mock).mockRejectedValue(forbidden())await mountLogic()await startRunUnderFakeTimers()await advancePoll(3000)expect(logic.values.accessDenied).toBe(true)- const pollsBeforeDenied = (warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length+ const pollsBeforeDenied = (dataQualityRunsRetrieve as jest.Mock).mock.calls.lengthawait advancePoll(15000)- expect((warehouseSavedQueriesCheckSuiteRunsRetrieve as jest.Mock).mock.calls.length).toEqual(pollsBeforeDenied)+ expect((dataQualityRunsRetrieve as jest.Mock).mock.calls.length).toEqual(pollsBeforeDenied)})it('adopts a run that was already in flight on mount, without a second request', async () => {- ;(warehouseSavedQueriesCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [buildSuiteRun()] })+ ;(dataQualityRunsList as jest.Mock).mockResolvedValue({ results: [buildSuiteRun()] })await mountLogic()// Adoption reads the newest row of the history this logic already loads, so mounting hits// the list endpoint once rather than twice.- expect(warehouseSavedQueriesCheckSuiteRunsList).toHaveBeenCalledTimes(1)+ expect(dataQualityRunsList).toHaveBeenCalledTimes(1)expect(logic.values.isSuiteRunning).toBe(true)})it('adopts the run the first metric check schedules once the worker writes it', async () => {+ ;(dataQualityChecksList as jest.Mock).mockResolvedValue({ results: [] })await mountLogic({ subjectType: 'metric', subjectId: 'metric-1' })expect(logic.values.checks).toEqual([])@@ -463,7 +413,7 @@ describe('dataQualityChecksLogic', () => {await drainListeners()expect(logic.values.isSuiteRunning).toBe(false)- ;(dataCatalogMetricsCheckSuiteRunsList as jest.Mock).mockResolvedValue({ results: [buildSuiteRun()] })+ ;(dataQualityRunsList as jest.Mock).mockResolvedValue({ results: [buildSuiteRun()] })await advancePoll(2000)expect(logic.values.isSuiteRunning).toBe(true)@@ -471,13 +421,13 @@ describe('dataQualityChecksLogic', () => {it('does not look for a scheduled run after a first check on a warehouse subject', async () => {await mountLogic({ subjectType: 'table', subjectId: 'table-1' })- const listCallsAfterMount = (warehouseTablesCheckSuiteRunsList as jest.Mock).mock.calls.length+ const listCallsAfterMount = (dataQualityRunsList as jest.Mock).mock.calls.lengthjest.useFakeTimers()logic.actions.upsertCheck(buildCheck())await advancePoll(2000)- expect((warehouseTablesCheckSuiteRunsList as jest.Mock).mock.calls.length).toEqual(listCallsAfterMount)+ expect((dataQualityRunsList as jest.Mock).mock.calls.length).toEqual(listCallsAfterMount)})// kea-test-utils waits on real timers, so the polling tests settle listeners by drainingdiff --git a/products/data_quality/frontend/dataQualityChecksLogic.ts b/products/data_quality/frontend/dataQualityChecksLogic.tsindex 425e1404a71a..8041964a104e 100644--- a/products/data_quality/frontend/dataQualityChecksLogic.ts+++ b/products/data_quality/frontend/dataQualityChecksLogic.ts@@ -12,6 +12,7 @@ import type {DataQualitySubjectHealthApi,DataQualitySuiteRunApi,} from './generated/api.schemas'+import type { DataQualityOverviewCheckApi } from './generated/api.schemas'import { openFailingRowsInSqlEditor } from './openFailingRows'import { isTerminalSuiteRun, suiteRunOutcome, suiteRunPollListeners, suiteRunSummary } from './suiteRuns'@@ -96,10 +97,10 @@ export interface dataQualityChecksLogicActions {errorObject?: any}loadChecksSuccess: (- checks: DataQualityCheckApi[],+ checks: DataQualityOverviewCheckApi[],payload?: any) => {- checks: DataQualityCheckApi[]+ checks: DataQualityOverviewCheckApi[]payload?: any}loadHealth: () => any@@ -369,7 +370,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([// Assigned one by one rather than spread: kea-typegen walks this object literal and crashes// on a spread element, which has no property name.const poll = suiteRunPollListeners({- retrieve: (suiteRunId) => checksApi.suiteRunRetrieve(subjectRef(props), suiteRunId),+ retrieve: (suiteRunId) => checksApi.suiteRunRetrieve(suiteRunId),// A permanent 403 -- the flag turned off mid-run, or query access revoked -- takes the// panel's access-denied path immediately, like every other request here.onPollError: (error) => {@@ -403,7 +404,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([}actions.setCheckPending('deleting', checkId, true)try {- await checksApi.destroy(subjectRef(props), checkId)+ await checksApi.destroy(checkId)actions.removeCheck(checkId)actions.loadHealth()} catch (error) {@@ -418,7 +419,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([}actions.setCheckPending('toggling', checkId, true)try {- actions.upsertCheck(await checksApi.partialUpdate(subjectRef(props), checkId, { enabled }))+ actions.upsertCheck(await checksApi.partialUpdate(checkId, { enabled }))actions.loadHealth()} catch (error) {lemonToast.error(apiErrorDetail(error) ?? 'Could not update the check. Try again.')@@ -432,7 +433,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([}actions.setCheckPending('loadingRuns', checkId, true)try {- actions.setCheckRuns(checkId, await checksApi.runs(subjectRef(props), checkId))+ actions.setCheckRuns(checkId, await checksApi.runs(checkId))} catch (error) {lemonToast.error(apiErrorDetail(error) ?? 'Could not load the run history. Try again.')} finally {@@ -442,7 +443,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([openFailingRows: async ({ checkId }) => {await openFailingRowsInSqlEditor({cachedRuns: values.checkRunsByCheckId[checkId],- fetchRuns: () => checksApi.runs(subjectRef(props), checkId),+ fetchRuns: () => checksApi.runs(checkId),onRunsFetched: (runs) => actions.setCheckRuns(checkId, runs),})},@@ -452,10 +453,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([}actions.setCheckPending('loadingSuiteRunRuns', suiteRunId, true)try {- actions.setSuiteRunCheckRuns(- suiteRunId,- await checksApi.suiteRunCheckRuns(subjectRef(props), suiteRunId)- )+ actions.setSuiteRunCheckRuns(suiteRunId, await checksApi.suiteRunCheckRuns(suiteRunId))} catch (error) {lemonToast.error(apiErrorDetail(error) ?? 'Could not load the run details. Try again.')} finally {@@ -473,7 +471,7 @@ export const dataQualityChecksLogic = kea<dataQualityChecksLogicType>([cache.suiteStartToken = (cache.suiteStartToken ?? 0) + 1const startToken = cache.suiteStartTokentry {- const started = await checksApi.run(subjectRef(props), checkId)+ const started = await checksApi.run(checkId)if (cache.suiteStartToken === startToken) {actions.setActiveSuiteRun(started)}diff --git a/products/data_quality/frontend/dataQualityScheduleLogic.test.ts b/products/data_quality/frontend/dataQualityScheduleLogic.test.tsindex 6445de92b178..162d9bf7e690 100644--- a/products/data_quality/frontend/dataQualityScheduleLogic.test.ts+++ b/products/data_quality/frontend/dataQualityScheduleLogic.test.ts@@ -5,14 +5,11 @@ import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'import { dataQualityScheduleLogic } from './dataQualityScheduleLogic'-import {- dataCatalogMetricsChecksScheduleRetrieve,- dataCatalogMetricsChecksSchedulePartialUpdate,-} from './generated/api'+import { dataQualityChecksScheduleRetrieve, dataQualityChecksSchedulePartialUpdate } from './generated/api'jest.mock('./generated/api', () => ({- dataCatalogMetricsChecksScheduleRetrieve: jest.fn(),- dataCatalogMetricsChecksSchedulePartialUpdate: jest.fn(),+ dataQualityChecksScheduleRetrieve: jest.fn(),+ dataQualityChecksSchedulePartialUpdate: jest.fn(),}))const SCHEDULE = {@@ -31,7 +28,7 @@ describe('dataQualityScheduleLogic', () => {jest.clearAllMocks()initKeaTests()silenceKeaLoadersErrors()- ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock).mockResolvedValue(SCHEDULE)+ ;(dataQualityChecksScheduleRetrieve as jest.Mock).mockResolvedValue(SCHEDULE)logic = dataQualityScheduleLogic({ metricId: 'metric-1' })})@@ -44,13 +41,15 @@ describe('dataQualityScheduleLogic', () => {logic.mount()await expectLogic(logic).toFinishAllListeners()expect(logic.values.schedule).toEqual(SCHEDULE)- ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockResolvedValue({+ ;(dataQualityChecksSchedulePartialUpdate as jest.Mock).mockResolvedValue({...SCHEDULE,interval: '6hour',})logic.actions.updateSchedule({ interval: '6hour' })await expectLogic(logic).toFinishAllListeners()- expect(dataCatalogMetricsChecksSchedulePartialUpdate).toHaveBeenCalledWith('997', 'metric-1', {+ expect(dataQualityChecksSchedulePartialUpdate).toHaveBeenCalledWith('997', {+ subject_type: 'metric',+ subject_uuid: 'metric-1',interval: '6hour',})expect(logic.values.schedule).toMatchObject({ interval: '6hour', enabled: true })@@ -59,13 +58,13 @@ describe('dataQualityScheduleLogic', () => {it('keeps the persisted schedule visible after a rejected edit and can retry', async () => {logic.mount()await expectLogic(logic).toFinishAllListeners()- ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(new Error('Could not save'))+ ;(dataQualityChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(new Error('Could not save'))logic.actions.updateSchedule({ enabled: false })await expectLogic(logic).toFinishAllListeners()expect(logic.values.schedule?.enabled).toBe(true)expect(logic.values.scheduleError).toBeTruthy()expect(logic.values.scheduleLoading).toBe(false)- ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockResolvedValue({ ...SCHEDULE, enabled: false })+ ;(dataQualityChecksSchedulePartialUpdate as jest.Mock).mockResolvedValue({ ...SCHEDULE, enabled: false })logic.actions.updateSchedule({ enabled: false })await expectLogic(logic).toFinishAllListeners()expect(logic.values.schedule?.enabled).toBe(false)@@ -74,8 +73,8 @@ describe('dataQualityScheduleLogic', () => {it('refetches persisted state when an edit response is lost', async () => {logic.mount()await expectLogic(logic).toFinishAllListeners()- ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(new Error('Connection lost'))- ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock).mockResolvedValue({+ ;(dataQualityChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(new Error('Connection lost'))+ ;(dataQualityChecksScheduleRetrieve as jest.Mock).mockResolvedValue({...SCHEDULE,enabled: false,next_run_at: null,@@ -90,15 +89,15 @@ describe('dataQualityScheduleLogic', () => {it('reports a denied edit without refetching the schedule', async () => {logic.mount()await expectLogic(logic).toFinishAllListeners()- ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock).mockClear()- ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(+ ;(dataQualityChecksScheduleRetrieve as jest.Mock).mockClear()+ ;(dataQualityChecksSchedulePartialUpdate as jest.Mock).mockRejectedValue(new ApiError('Forbidden', 403, undefined, {detail: 'You do not have permission to perform this action.',}))logic.actions.updateSchedule({ enabled: false })await expectLogic(logic).toFinishAllListeners()- expect(dataCatalogMetricsChecksScheduleRetrieve).not.toHaveBeenCalled()+ expect(dataQualityChecksScheduleRetrieve).not.toHaveBeenCalled()expect(logic.values.scheduleError).toEqual({message: 'You do not have permission to perform this action.',uncertain: false,@@ -110,13 +109,13 @@ describe('dataQualityScheduleLogic', () => {logic.mount()await expectLogic(logic).toFinishAllListeners()let resolveRefresh!: (schedule: typeof SCHEDULE) => void- ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock).mockReturnValueOnce(+ ;(dataQualityChecksScheduleRetrieve as jest.Mock).mockReturnValueOnce(new Promise((resolve) => {resolveRefresh = resolve}))logic.actions.refreshSchedule()- ;(dataCatalogMetricsChecksSchedulePartialUpdate as jest.Mock).mockResolvedValue({ ...SCHEDULE, enabled: false })+ ;(dataQualityChecksSchedulePartialUpdate as jest.Mock).mockResolvedValue({ ...SCHEDULE, enabled: false })await expectLogic(logic, () => logic.actions.updateSchedule({ enabled: false })).toDispatchActions(['updateScheduleSuccess',])@@ -131,7 +130,7 @@ describe('dataQualityScheduleLogic', () => {refreshSchedule = handler as () => voidreturn 1})- ;(dataCatalogMetricsChecksScheduleRetrieve as jest.Mock)+ ;(dataQualityChecksScheduleRetrieve as jest.Mock).mockResolvedValueOnce(SCHEDULE).mockResolvedValueOnce({ ...SCHEDULE, next_run_at: '2026-09-06T00:00:00Z' })diff --git a/products/data_quality/frontend/dataQualityScheduleLogic.ts b/products/data_quality/frontend/dataQualityScheduleLogic.tsindex 5f87c2962b0a..9274b893c64b 100644--- a/products/data_quality/frontend/dataQualityScheduleLogic.ts+++ b/products/data_quality/frontend/dataQualityScheduleLogic.ts@@ -1,10 +1,9 @@import { LogicWrapper, MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'import { loaders } from 'kea-loaders'-import { ApiConfig, ApiError } from 'lib/api'+import { ApiError } from 'lib/api'-import { apiErrorDetail } from './checksApi'-import * as api from './generated/api'+import { DataQualitySubjectRef, apiErrorDetail, checksApi } from './checksApi'import type { DataQualityCheckScheduleApi, PatchedDataQualityCheckScheduleUpdateApi } from './generated/api.schemas'const SCHEDULE_REFRESH_INTERVAL_MS = 30_000@@ -13,6 +12,10 @@ export interface DataQualityScheduleLogicProps {metricId: string}+function subjectRef(props: DataQualityScheduleLogicProps): DataQualitySubjectRef {+ return { subjectType: 'metric', subjectId: props.metricId }+}+export interface DataQualityScheduleError {message: stringuncertain: boolean@@ -95,26 +98,16 @@ export const dataQualityScheduleLogic: LogicWrapper<dataQualityScheduleLogicTypeschedule: [null as DataQualityCheckScheduleApi | null,{- loadSchedule: async () =>- api.dataCatalogMetricsChecksScheduleRetrieve(String(ApiConfig.getCurrentTeamId()), props.metricId),+ loadSchedule: async () => checksApi.schedule(subjectRef(props)),updateSchedule: async (patch: PatchedDataQualityCheckScheduleUpdateApi) => {try {- return await api.dataCatalogMetricsChecksSchedulePartialUpdate(- String(ApiConfig.getCurrentTeamId()),- props.metricId,- patch- )+ return await checksApi.updateSchedule(subjectRef(props), patch)} catch (error) {if (isDefinitiveRejection(error)) {throw error}try {- actions.loadScheduleSuccess(- await api.dataCatalogMetricsChecksScheduleRetrieve(- String(ApiConfig.getCurrentTeamId()),- props.metricId- )- )+ actions.loadScheduleSuccess(await checksApi.schedule(subjectRef(props)))} catch {// The edit can have committed even when neither response reaches us.}@@ -148,10 +141,7 @@ export const dataQualityScheduleLogic: LogicWrapper<dataQualityScheduleLogicType}const previousSchedule = values.scheduletry {- const schedule = await api.dataCatalogMetricsChecksScheduleRetrieve(- String(ApiConfig.getCurrentTeamId()),- props.metricId- )+ const schedule = await checksApi.schedule(subjectRef(props))if (!values.scheduleLoading && values.schedule === previousSchedule) {actions.refreshScheduleSuccess(schedule)}diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.tsindex bd305ffaa371..1ac7c2406216 100644--- a/products/data_quality/frontend/generated/api.schemas.ts+++ b/products/data_quality/frontend/generated/api.schemas.ts@@ -7,51 +7,6 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/-export interface DataQualitySuiteRunApi {- readonly id: string- /** manual, materialization, source_sync, or scheduled. */- readonly trigger: string- /** running, completed, failed, or empty (nothing matched the trigger). */- readonly status: string- /**- * 'table', 'view', or 'metric' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.- * @nullable- */- readonly subject_type: string | null- /**- * Set when the run targets exactly one subject.- * @nullable- */- readonly subject_uuid: string | null- readonly workflow_id: string- readonly checks_passed: number- readonly checks_failed: number- readonly checks_errored: number- readonly checks_skipped: number- /** @nullable */- readonly started_at: string | null- /** @nullable */- readonly finished_at: string | null- /** Why the suite itself failed, as opposed to an individual check. */- readonly error: string- readonly created_at: string-}--export interface PaginatedDataQualitySuiteRunListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: DataQualitySuiteRunApi[]-}--/**- * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.- * @nullable- */-export type DataQualityCheckRunApiCheckConfig = { [key: string]: unknown } | null-/*** * `table` - table* * `view` - view@@ -98,68 +53,6 @@ export const DataQualityCheckSeverityEnumApi = {Warn: 'warn',} as const-export interface DataQualityCheckRunApi {- readonly id: string- /**- * The definition executed. Nulled rather than cascaded so history outlives hard deletes.- * @nullable- */- readonly quality_check: string | null- /**- * Name the check carries now, so a run can be told from the others in its suite. Null when the check is unnamed, has been hard deleted, or is out of your reach today -- describe the run by check_type and column_name instead.- * @nullable- */- readonly check_name: string | null- readonly suite_run: string- readonly subject_type: SubjectTypeEnumApi- readonly subject_uuid: string- readonly subject_name: string- /** Which assertion this run made.- *- * * `not_null` - not_null- * * `unique` - unique- * * `accepted_values` - accepted_values- * * `relationships` - relationships- * * `row_count` - row_count- * * `freshness` - freshness- * * `custom_sql` - custom_sql */- readonly check_type: CheckTypeEnumApi- readonly column_name: string- /**- * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.- * @nullable- */- readonly check_config: DataQualityCheckRunApiCheckConfig- /** Severity this run was judged at. Null for runs recorded before snapshots existed.- *- * * `error` - error- * * `warn` - warn */- readonly check_severity: DataQualityCheckSeverityEnumApi | null- /** passed, failed, errored, or skipped. */- readonly status: string- /**- * Rows violating the assertion. Null for bounds checks like row_count.- * @nullable- */- readonly failed_row_count: number | null- /**- * The check's headline number, recorded on passes too.- * @nullable- */- readonly observed_value: number | null- /** The HogQL that ran. Re-run it to see the offending rows. */- readonly compiled_query: string- /** Compilation or execution failure, when status is 'errored'. */- readonly error: string- /** @nullable */- readonly duration_ms: number | null- /** @nullable */- readonly started_at: string | null- /** @nullable */- readonly finished_at: string | null- readonly created_at: string-}-/*** * `user` - user* * `ai_generated` - ai_generated@@ -231,12 +124,16 @@ export interface UserBasicApi {/*** Type-specific configuration, validated against the check type's JSON schema.*/-export type DataQualityCheckApiConfig = { [key: string]: unknown }+export type DataQualityOverviewCheckApiConfig = { [key: string]: unknown }/**- * The subject is implied by the URL (the parent saved query or table), never part of the body.+ * A check plus where its subject can be opened, for the project-wide list.+ *+ * The per-subject surfaces already know their parent; only this one lists checks across every+ * table and view, so only this one needs to say where each subject lives. The ids are resolved+ * for a whole page at once and handed in through ``subject_locations`` in the context.*/-export interface DataQualityCheckApi {+export interface DataQualityOverviewCheckApi {readonly id: string/** Optional identifier-safe handle, unique per project. Omit to address the check by id. */name?: string@@ -249,7 +146,7 @@ export interface DataQualityCheckApi {* * `metric` - metric */readonly subject_type: SubjectTypeEnumApi/**- * Id of the table, view, or metric being checked, from the parent resource in the URL.+ * Id of the table, view, or metric being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid: string | null@@ -273,7 +170,7 @@ export interface DataQualityCheckApi {* * `custom_sql` - custom_sql */check_type: CheckTypeEnumApi/** Type-specific configuration, validated against the check type's JSON schema. */- config?: DataQualityCheckApiConfig+ config?: DataQualityOverviewCheckApiConfig/** 'error' failures mark the subject failing and notify; 'warn' failures only surface.** * `error` - error@@ -331,46 +228,63 @@ export interface DataQualityCheckApi {readonly created_at: string/** @nullable */readonly updated_at: string | null+ /**+ * Data modeling node of the view this check audits, or null when it is on no DAG or the subject is a table.+ * @nullable+ */+ readonly subject_node_id: string | null+ /**+ * Warehouse source of the table this check audits, or null when the subject is a view.+ * @nullable+ */+ readonly subject_source_id: string | null+ /**+ * Warehouse source schema of the table this check audits, or null when the subject is a view.+ * @nullable+ */+ readonly subject_schema_id: string | null+ /**+ * Current metric name for opening its Tests tab, or null for other subjects.+ * @nullable+ */+ readonly subject_metric_name: string | null}-export interface PaginatedDataQualityCheckListApi {+export interface PaginatedDataQualityOverviewCheckListApi {count: number/** @nullable */next?: string | null/** @nullable */previous?: string | null- results: DataQualityCheckApi[]+ results: DataQualityOverviewCheckApi[]}/*** Type-specific configuration, validated against the check type's JSON schema.*/-export type PatchedDataQualityCheckApiConfig = { [key: string]: unknown }+export type DataQualityCheckCreateApiConfig = { [key: string]: unknown }/**- * The subject is implied by the URL (the parent saved query or table), never part of the body.+ * The create body, where the subject is named for the only time in a check's life.*/-export interface PatchedDataQualityCheckApi {- readonly id?: string+export interface DataQualityCheckCreateApi {+ readonly id: string/** Optional identifier-safe handle, unique per project. Omit to address the check by id. */name?: string/** Why this check exists and what a failure means. */description?: string- /** Kind of catalog object being checked: 'table', 'view', or 'metric'.+ /** Kind of catalog object to check: 'table', 'view', or 'metric'.** * `table` - table* * `view` - view* * `metric` - metric */- readonly subject_type?: SubjectTypeEnumApi- /**- * Id of the table, view, or metric being checked, from the parent resource in the URL.- * @nullable- */- readonly subject_uuid?: string | null+ subject_type: SubjectTypeEnumApi+ /** Id of the table, view, or metric to check. */+ subject_uuid: string/** Queryable name of the subject, refreshed on every run. */- readonly subject_name?: string+ readonly subject_name: string/** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */- readonly subject_status?: string+ readonly subject_status: string/*** Column the check applies to. Omit for table-scoped types like row_count.* @maxLength 400@@ -385,9 +299,9 @@ export interface PatchedDataQualityCheckApi {* * `row_count` - row_count* * `freshness` - freshness* * `custom_sql` - custom_sql */- check_type?: CheckTypeEnumApi+ check_type: CheckTypeEnumApi/** Type-specific configuration, validated against the check type's JSON schema. */- config?: PatchedDataQualityCheckApiConfig+ config?: DataQualityCheckCreateApiConfig/** 'error' failures mark the subject failing and notify; 'warn' failures only surface.** * `error` - error@@ -401,26 +315,26 @@ export interface PatchedDataQualityCheckApi {* Email of the human accountable for this check, or null.* @nullable*/- readonly owner?: string | null+ readonly owner: string | null/*** When the check last executed.* @nullable*/- readonly last_run_at?: string | null+ readonly last_run_at: string | null/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */- readonly last_status?: string+ readonly last_status: string/*** When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/- readonly last_succeeded_at?: string | null+ readonly last_succeeded_at: string | null/*** When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.* @nullable*/- readonly failing_since?: string | null+ readonly failing_since: string | null/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */- readonly fingerprint?: string+ readonly fingerprint: string/** Whether a human ('user') or an agent ('ai_generated') authored this check.** * `user` - user@@ -441,137 +355,131 @@ export interface PatchedDataQualityCheckApi {/** AI author's reasoning, surfaced as review context. */reasoning?: string/** User who first created this check. */- readonly created_by?: UserBasicApi- readonly created_at?: string+ readonly created_by: UserBasicApi+ readonly created_at: string/** @nullable */- readonly updated_at?: string | null+ readonly updated_at: string | null}/**- * JSON schema the config object is validated against.- */-export type DataQualityCheckTypeApiConfigSchema = { [key: string]: unknown }--/**- * One entry of the check-type catalog, so an agent can author config without guessing.+ * Type-specific configuration, validated against the check type's JSON schema.*/-export interface DataQualityCheckTypeApi {- /** Value to pass as check_type. */- check_type: string- /** What the check asserts and what counts as a failure. */- description: string- /** Whether column_name must be set for this type. */- requires_column: boolean- /** JSON schema the config object is validated against. */- config_schema: DataQualityCheckTypeApiConfigSchema-}+export type DataQualityCheckApiConfig = { [key: string]: unknown }/**- * Per-subject rollup, the same rule the information_schema.data_quality_health table uses.+ * A check as it reads back, and everything an edit may change about it.+ *+ * The subject is not one of those: it is writable only on ``DataQualityCheckCreate``.*/-export interface DataQualitySubjectHealthApi {- /** 'table', 'view', or 'metric'. */- subject_type: string- /** Id of the table, view, or metric. */- subject_uuid: string- /** failing (an error-severity check failed), erroring (a check could not run), warn (only warn-severity failures), healthy, or unknown (nothing has run yet). */- health: string- /** How many enabled, non-deleted checks cover this subject. */- checks_total: number- /** How many of those checks last reported a failure. */- checks_failing: number-}--export interface DataQualityOutputColumnApi {- /** Output column name available through the {metric} relation. */- name: string+export interface DataQualityCheckApi {+ readonly id: string+ /** Optional identifier-safe handle, unique per project. Omit to address the check by id. */+ name?: string+ /** Why this check exists and what a failure means. */+ description?: string+ /** Kind of catalog object being checked: 'table', 'view', or 'metric'.+ *+ * * `table` - table+ * * `view` - view+ * * `metric` - metric */+ readonly subject_type: SubjectTypeEnumApi/**- * ClickHouse type, or null when it could not be inferred.+ * Id of the table, view, or metric being checked. Null once the subject is deleted.* @nullable*/- type: string | null-}--export interface DataQualityOutputSchemaApi {- /** Columns returned by the saved metric query. */- columns: DataQualityOutputColumnApi[]-}--/**- * * `1hour` - 1hour- * * `6hour` - 6hour- * * `12hour` - 12hour- * * `24hour` - 24hour- * * `7day` - 7day- */-export type DataQualityScheduleIntervalEnumApi =- (typeof DataQualityScheduleIntervalEnumApi)[keyof typeof DataQualityScheduleIntervalEnumApi]--export const DataQualityScheduleIntervalEnumApi = {- '1hour': '1hour',- '6hour': '6hour',- '12hour': '12hour',- '24hour': '24hour',- '7day': '7day',-} as const--export interface DataQualityCheckScheduleApi {- /** 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+ readonly subject_uuid: string | null+ /** Queryable name of the subject, refreshed on every run. */+ readonly subject_name: string+ /** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */+ readonly subject_status: string/**- * Next scheduled execution time, if enabled.+ * Column the check applies to. Omit for table-scoped types like row_count.+ * @maxLength 400+ */+ column_name?: string+ /** Which assertion to make. Determines the shape of config; see /check_types/.+ *+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql */+ check_type: CheckTypeEnumApi+ /** Type-specific configuration, validated against the check type's JSON schema. */+ config?: DataQualityCheckApiConfig+ /** 'error' failures mark the subject failing and notify; 'warn' failures only surface.+ *+ * * `error` - error+ * * `warn` - warn */+ severity?: DataQualityCheckSeverityEnumApi+ /** Disabled checks are never run by any trigger. */+ enabled?: boolean+ /** Free-form string labels for grouping and filtering. */+ tags?: string[]+ /**+ * Email of the human accountable for this check, or null.* @nullable*/- readonly next_run_at: string | null+ readonly owner: string | null/**- * Most recent visible scheduled suite execution time.+ * When the check last executed.* @nullable*/readonly last_run_at: string | null+ /** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */+ readonly last_status: string/**- * Most recent visible scheduled suite.+ * When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/- readonly last_suite_run: string | null-}--export interface PatchedDataQualityCheckScheduleUpdateApi {- /** How often all enabled checks on the metric run.+ readonly last_succeeded_at: string | null+ /**+ * When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.+ * @nullable+ */+ readonly failing_since: string | null+ /** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */+ readonly fingerprint: string+ /** Whether a human ('user') or an agent ('ai_generated') authored this check.*- * * `1hour` - 1hour- * * `6hour` - 6hour- * * `12hour` - 12hour- * * `24hour` - 24hour- * * `7day` - 7day */- interval?: DataQualityScheduleIntervalEnumApi- /** Whether checks run automatically on this schedule. */- enabled?: boolean+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnumApi+ /**+ * Model that generated the check, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string+ /**+ * AI author's confidence in the check, 0-1.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ confidence?: number | null+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string+ /** User who first created this check. */+ readonly created_by: UserBasicApi+ readonly created_at: string+ /** @nullable */+ readonly updated_at: string | null}/*** Type-specific configuration, validated against the check type's JSON schema.*/-export type DataQualityOverviewCheckApiConfig = { [key: string]: unknown }+export type PatchedDataQualityCheckApiConfig = { [key: string]: unknown }/**- * A check plus where its subject can be opened, for the project-wide list.+ * A check as it reads back, and everything an edit may change about it.*- * The per-subject surfaces already know their parent; only this one lists checks across every- * table and view, so only this one needs to say where each subject lives. The ids are resolved- * for a whole page at once and handed in through ``subject_locations`` in the context.+ * The subject is not one of those: it is writable only on ``DataQualityCheckCreate``.*/-export interface DataQualityOverviewCheckApi {- readonly id: string+export interface PatchedDataQualityCheckApi {+ readonly id?: string/** Optional identifier-safe handle, unique per project. Omit to address the check by id. */name?: string/** Why this check exists and what a failure means. */@@ -581,16 +489,16 @@ export interface DataQualityOverviewCheckApi {* * `table` - table* * `view` - view* * `metric` - metric */- readonly subject_type: SubjectTypeEnumApi+ readonly subject_type?: SubjectTypeEnumApi/**- * Id of the table, view, or metric being checked, from the parent resource in the URL.+ * Id of the table, view, or metric being checked. Null once the subject is deleted.* @nullable*/- readonly subject_uuid: string | null+ readonly subject_uuid?: string | null/** Queryable name of the subject, refreshed on every run. */- readonly subject_name: string+ readonly subject_name?: string/** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */- readonly subject_status: string+ readonly subject_status?: string/*** Column the check applies to. Omit for table-scoped types like row_count.* @maxLength 400@@ -605,9 +513,9 @@ export interface DataQualityOverviewCheckApi {* * `row_count` - row_count* * `freshness` - freshness* * `custom_sql` - custom_sql */- check_type: CheckTypeEnumApi+ check_type?: CheckTypeEnumApi/** Type-specific configuration, validated against the check type's JSON schema. */- config?: DataQualityOverviewCheckApiConfig+ config?: PatchedDataQualityCheckApiConfig/** 'error' failures mark the subject failing and notify; 'warn' failures only surface.** * `error` - error@@ -621,26 +529,26 @@ export interface DataQualityOverviewCheckApi {* Email of the human accountable for this check, or null.* @nullable*/- readonly owner: string | null+ readonly owner?: string | null/*** When the check last executed.* @nullable*/- readonly last_run_at: string | null+ readonly last_run_at?: string | null/** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */- readonly last_status: string+ readonly last_status?: string/*** When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.* @nullable*/- readonly last_succeeded_at: string | null+ readonly last_succeeded_at?: string | null/*** When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.* @nullable*/- readonly failing_since: string | null+ readonly failing_since?: string | null/** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */- readonly fingerprint: string+ readonly fingerprint?: string/** Whether a human ('user') or an agent ('ai_generated') authored this check.** * `user` - user@@ -661,39 +569,143 @@ export interface DataQualityOverviewCheckApi {/** AI author's reasoning, surfaced as review context. */reasoning?: string/** User who first created this check. */- readonly created_by: UserBasicApi- readonly created_at: string+ readonly created_by?: UserBasicApi+ readonly created_at?: string/** @nullable */- readonly updated_at: string | null+ readonly updated_at?: string | null+}++export interface DataQualitySuiteRunApi {+ readonly id: string+ /** manual, materialization, source_sync, or scheduled. */+ readonly trigger: string+ /** running, completed, failed, or empty (nothing matched the trigger). */+ readonly status: string/**- * Data modeling node of the view this check audits, or null when it is on no DAG or the subject is a table.+ * 'table', 'view', or 'metric' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.* @nullable*/- readonly subject_node_id: string | null+ readonly subject_type: string | null/**- * Warehouse source of the table this check audits, or null when the subject is a view.+ * Set when the run targets exactly one subject.* @nullable*/- readonly subject_source_id: string | null+ readonly subject_uuid: string | null+ readonly workflow_id: string+ readonly checks_passed: number+ readonly checks_failed: number+ readonly checks_errored: number+ readonly checks_skipped: number+ /** @nullable */+ readonly started_at: string | null+ /** @nullable */+ readonly finished_at: string | null+ /** Why the suite itself failed, as opposed to an individual check. */+ readonly error: string+ readonly created_at: string+}++/**+ * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.+ * @nullable+ */+export type DataQualityCheckRunApiCheckConfig = { [key: string]: unknown } | null++export interface DataQualityCheckRunApi {+ readonly id: string/**- * Warehouse source schema of the table this check audits, or null when the subject is a view.+ * The definition executed. Nulled rather than cascaded so history outlives hard deletes.* @nullable*/- readonly subject_schema_id: string | null+ readonly quality_check: string | null/**- * Current metric name for opening its Tests tab, or null for other subjects.+ * Name the check carries now, so a run can be told from the others in its suite. Null when the check is unnamed, has been hard deleted, or is out of your reach today -- describe the run by check_type and column_name instead.* @nullable*/- readonly subject_metric_name: string | null-}--export interface PaginatedDataQualityOverviewCheckListApi {- count: number+ readonly check_name: string | null+ readonly suite_run: string+ readonly subject_type: SubjectTypeEnumApi+ readonly subject_uuid: string+ readonly subject_name: string+ /** Which assertion this run made.+ *+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql */+ readonly check_type: CheckTypeEnumApi+ readonly column_name: string+ /**+ * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.+ * @nullable+ */+ readonly check_config: DataQualityCheckRunApiCheckConfig+ /** Severity this run was judged at. Null for runs recorded before snapshots existed.+ *+ * * `error` - error+ * * `warn` - warn */+ readonly check_severity: DataQualityCheckSeverityEnumApi | null+ /** passed, failed, errored, or skipped. */+ readonly status: string+ /**+ * Rows violating the assertion. Null for bounds checks like row_count.+ * @nullable+ */+ readonly failed_row_count: number | null+ /**+ * The check's headline number, recorded on passes too.+ * @nullable+ */+ readonly observed_value: number | null+ /** The HogQL that ran. Re-run it to see the offending rows. */+ readonly compiled_query: string+ /** Compilation or execution failure, when status is 'errored'. */+ readonly error: string/** @nullable */- next?: string | null+ readonly duration_ms: number | null/** @nullable */- previous?: string | null- results: DataQualityOverviewCheckApi[]+ readonly started_at: string | null+ /** @nullable */+ readonly finished_at: string | null+ readonly created_at: string+}++/**+ * JSON schema the config object is validated against.+ */+export type DataQualityCheckTypeApiConfigSchema = { [key: string]: unknown }++/**+ * One entry of the check-type catalog, so an agent can author config without guessing.+ */+export interface DataQualityCheckTypeApi {+ /** Value to pass as check_type. */+ check_type: string+ /** What the check asserts and what counts as a failure. */+ description: string+ /** Whether column_name must be set for this type. */+ requires_column: boolean+ /** JSON schema the config object is validated against. */+ config_schema: DataQualityCheckTypeApiConfigSchema+}++/**+ * Per-subject rollup, the same rule the information_schema.data_quality_health table uses.+ */+export interface DataQualitySubjectHealthApi {+ /** 'table', 'view', or 'metric'. */+ subject_type: string+ /** Id of the table, view, or metric. */+ subject_uuid: string+ /** failing (an error-severity check failed), erroring (a check could not run), warn (only warn-severity failures), healthy, or unknown (nothing has run yet). */+ health: string+ /** How many enabled, non-deleted checks cover this subject. */+ checks_total: number+ /** How many of those checks last reported a failure. */+ checks_failing: number}export interface DataQualityMetricSubjectApi {@@ -705,15 +717,150 @@ export interface DataQualityMetricSubjectApi {display_name: string}+export interface DataQualityOutputColumnApi {+ /** Output column name available through the {metric} relation. */+ name: string+ /**+ * ClickHouse type, or null when it could not be inferred.+ * @nullable+ */+ type: string | null+}++export interface DataQualityOutputSchemaApi {+ /** Columns returned by the saved metric query. */+ columns: DataQualityOutputColumnApi[]+}++/**+ * * `1hour` - 1hour+ * * `6hour` - 6hour+ * * `12hour` - 12hour+ * * `24hour` - 24hour+ * * `7day` - 7day+ */+export type DataQualityScheduleIntervalEnumApi =+ (typeof DataQualityScheduleIntervalEnumApi)[keyof typeof DataQualityScheduleIntervalEnumApi]++export const DataQualityScheduleIntervalEnumApi = {+ '1hour': '1hour',+ '6hour': '6hour',+ '12hour': '12hour',+ '24hour': '24hour',+ '7day': '7day',+} as const++export interface DataQualityCheckScheduleApi {+ /** 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+}++/**+ * Which subject's schedule to change, and what to change about it.+ */+export interface PatchedDataQualityCheckScheduleUpdateApi {+ /** Kind of catalog object: 'table', 'view', or 'metric'.+ *+ * * `table` - table+ * * `view` - view+ * * `metric` - metric */+ subject_type?: SubjectTypeEnumApi+ /** Id of the table, view, or metric. */+ subject_uuid?: string+ /** How often all enabled checks on the subject run.+ *+ * * `1hour` - 1hour+ * * `6hour` - 6hour+ * * `12hour` - 12hour+ * * `24hour` - 24hour+ * * `7day` - 7day */+ interval?: DataQualityScheduleIntervalEnumApi+ /** Whether checks run automatically on this schedule. */+ enabled?: boolean+}++/**+ * Column name to ClickHouse type. Empty for a metric, and for a view that has not run yet.+ */+export type DataQualitySubjectApiColumns = { [key: string]: string }++/**+ * One thing a check can be authored on, whatever kind it is.+ */+export interface DataQualitySubjectApi {+ /** Kind of object: 'table', 'view', or 'metric'. Pass it back as subject_type when creating a check.+ *+ * * `table` - table+ * * `view` - view+ * * `metric` - metric */+ subject_type: SubjectTypeEnumApi+ /** Id of the subject. Pass it back as subject_uuid when creating a check. */+ id: string+ /** Queryable name of the subject. */+ name: string+ /** Label shown in the data catalog. Blank for tables and views. */+ display_name: 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. */+ editable: boolean+}++export interface PaginatedDataQualitySuiteRunListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: DataQualitySuiteRunApi[]+}+/*** What to run in a project-wide suite run.*/export interface DataQualityRunRequestApi {/** Ids of the checks to run. Omit to run every enabled check in the project. */check_ids?: string[]+ /** Narrow the run to one subject. Pass subject_uuid with it. Ignored when check_ids is given.+ *+ * * `table` - table+ * * `view` - view+ * * `metric` - metric */+ subject_type?: SubjectTypeEnumApi+ /** Id of the subject to run every enabled check on. Pass subject_type with it. */+ subject_uuid?: string}-export type DataCatalogMetricsCheckSuiteRunsListParams = {+export type DataQualityChecksListParams = {+ /**+ * Only the checks that make this assertion. See /check_types/.+ */+ check_type?: DataQualityChecksListCheckType/*** Number of results to return per page.*/@@ -722,64 +869,115 @@ export type DataCatalogMetricsCheckSuiteRunsListParams = {* The initial index from which to return the results.*/offset?: number-}--export type DataCatalogMetricsChecksListParams = {/**- * Number of results to return per page.+ * Kind of catalog object: 'table', 'view', or 'metric'.*/- limit?: number+ subject_type?: DataQualityChecksListSubjectType/**- * The initial index from which to return the results.+ * Id of the table, view, or metric.*/- offset?: number+ subject_uuid?: string}-export type DataQualityChecksListParams = {- /**- * Number of results to return per page.- */- limit?: number+export type DataQualityChecksListCheckType =+ (typeof DataQualityChecksListCheckType)[keyof typeof DataQualityChecksListCheckType]++export const DataQualityChecksListCheckType = {+ AcceptedValues: 'accepted_values',+ CustomSql: 'custom_sql',+ Freshness: 'freshness',+ NotNull: 'not_null',+ Relationships: 'relationships',+ RowCount: 'row_count',+ Unique: 'unique',+} as const++export type DataQualityChecksListSubjectType =+ (typeof DataQualityChecksListSubjectType)[keyof typeof DataQualityChecksListSubjectType]++export const DataQualityChecksListSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+} as const++export type DataQualityChecksCheckTypesListParams = {/**- * The initial index from which to return the results.+ * Kind of catalog object: 'table', 'view', or 'metric'.*/- offset?: number+ subject_type?: DataQualityChecksCheckTypesListSubjectType}-export type DataQualityRunsListParams = {+export type DataQualityChecksCheckTypesListSubjectType =+ (typeof DataQualityChecksCheckTypesListSubjectType)[keyof typeof DataQualityChecksCheckTypesListSubjectType]++export const DataQualityChecksCheckTypesListSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+} as const++export type DataQualityChecksHealthListParams = {/**- * Number of results to return per page.+ * Kind of catalog object: 'table', 'view', or 'metric'.*/- limit?: number+ subject_type?: DataQualityChecksHealthListSubjectType/**- * The initial index from which to return the results.+ * Id of the table, view, or metric.*/- offset?: number+ subject_uuid?: string}-export type WarehouseSavedQueriesCheckSuiteRunsListParams = {+export type DataQualityChecksHealthListSubjectType =+ (typeof DataQualityChecksHealthListSubjectType)[keyof typeof DataQualityChecksHealthListSubjectType]++export const DataQualityChecksHealthListSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+} as const++export type DataQualityChecksOutputSchemaRetrieveParams = {/**- * Number of results to return per page.+ * Kind of catalog object: 'table', 'view', or 'metric'.*/- limit?: number+ subject_type?: DataQualityChecksOutputSchemaRetrieveSubjectType/**- * The initial index from which to return the results.+ * Id of the table, view, or metric.*/- offset?: number+ subject_uuid?: string}-export type WarehouseSavedQueriesChecksListParams = {+export type DataQualityChecksOutputSchemaRetrieveSubjectType =+ (typeof DataQualityChecksOutputSchemaRetrieveSubjectType)[keyof typeof DataQualityChecksOutputSchemaRetrieveSubjectType]++export const DataQualityChecksOutputSchemaRetrieveSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+} as const++export type DataQualityChecksScheduleRetrieveParams = {/**- * Number of results to return per page.+ * Kind of catalog object: 'table', 'view', or 'metric'.*/- limit?: number+ subject_type?: DataQualityChecksScheduleRetrieveSubjectType/**- * The initial index from which to return the results.+ * Id of the table, view, or metric.*/- offset?: number+ subject_uuid?: string}-export type WarehouseTablesCheckSuiteRunsListParams = {+export type DataQualityChecksScheduleRetrieveSubjectType =+ (typeof DataQualityChecksScheduleRetrieveSubjectType)[keyof typeof DataQualityChecksScheduleRetrieveSubjectType]++export const DataQualityChecksScheduleRetrieveSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+} as const++export type DataQualityRunsListParams = {/*** Number of results to return per page.*/@@ -788,15 +986,21 @@ export type WarehouseTablesCheckSuiteRunsListParams = {* The initial index from which to return the results.*/offset?: number-}--export type WarehouseTablesChecksListParams = {/**- * Number of results to return per page.+ * Kind of catalog object: 'table', 'view', or 'metric'.*/- limit?: number+ subject_type?: DataQualityRunsListSubjectType/**- * The initial index from which to return the results.+ * Id of the table, view, or metric.*/- offset?: number+ subject_uuid?: string}++export type DataQualityRunsListSubjectType =+ (typeof DataQualityRunsListSubjectType)[keyof typeof DataQualityRunsListSubjectType]++export const DataQualityRunsListSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+} as constdiff --git a/products/data_quality/frontend/generated/api.ts b/products/data_quality/frontend/generated/api.tsindex 3242b954383a..88f230126f5f 100644--- a/products/data_quality/frontend/generated/api.ts+++ b/products/data_quality/frontend/generated/api.ts@@ -9,28 +9,27 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {- DataCatalogMetricsCheckSuiteRunsListParams,- DataCatalogMetricsChecksListParams,DataQualityCheckApi,+ DataQualityCheckCreateApi,DataQualityCheckRunApi,DataQualityCheckScheduleApi,DataQualityCheckTypeApi,+ DataQualityChecksCheckTypesListParams,+ DataQualityChecksHealthListParams,DataQualityChecksListParams,+ DataQualityChecksOutputSchemaRetrieveParams,+ DataQualityChecksScheduleRetrieveParams,DataQualityMetricSubjectApi,DataQualityOutputSchemaApi,DataQualityRunRequestApi,DataQualityRunsListParams,+ DataQualitySubjectApi,DataQualitySubjectHealthApi,DataQualitySuiteRunApi,- PaginatedDataQualityCheckListApi,PaginatedDataQualityOverviewCheckListApi,PaginatedDataQualitySuiteRunListApi,PatchedDataQualityCheckApi,PatchedDataQualityCheckScheduleUpdateApi,- WarehouseSavedQueriesCheckSuiteRunsListParams,- WarehouseSavedQueriesChecksListParams,- WarehouseTablesCheckSuiteRunsListParams,- WarehouseTablesChecksListParams,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -50,11 +49,7 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>-export const getDataCatalogMetricsCheckSuiteRunsListUrl = (- projectId: string,- metricId: string,- params?: DataCatalogMetricsCheckSuiteRunsListParams-) => {+export const getDataQualityChecksListUrl = (projectId: string, params?: DataQualityChecksListParams) => {const normalizedParams = new URLSearchParams()Object.entries(params || {}).forEach(([key, value]) => {@@ -66,166 +61,76 @@ export const getDataCatalogMetricsCheckSuiteRunsListUrl = (const stringifiedParams = normalizedParams.toString()return stringifiedParams.length > 0- ? `/api/projects/${projectId}/data_catalog/metrics/${metricId}/check_suite_runs/?${stringifiedParams}`- : `/api/projects/${projectId}/data_catalog/metrics/${metricId}/check_suite_runs/`-}--/**- * Read-only reports for this subject's check-suite executions.- */-export const dataCatalogMetricsCheckSuiteRunsList = async (- projectId: string,- metricId: string,- params?: DataCatalogMetricsCheckSuiteRunsListParams,- options?: RequestInit-): Promise<PaginatedDataQualitySuiteRunListApi> => {- return apiMutator<PaginatedDataQualitySuiteRunListApi>(- getDataCatalogMetricsCheckSuiteRunsListUrl(projectId, metricId, params),- {- ...options,- method: 'GET',- }- )-}--export const getDataCatalogMetricsCheckSuiteRunsRetrieveUrl = (projectId: string, metricId: string, id: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/check_suite_runs/${id}/`+ ? `/api/projects/${projectId}/data_quality_checks/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_quality_checks/`}/**- * Read-only reports for this subject's check-suite executions.+ * Every check in the project. Narrow it to one subject with subject_type and subject_uuid, or to one assertion with check_type.*/-export const dataCatalogMetricsCheckSuiteRunsRetrieve = async (+export const dataQualityChecksList = async (projectId: string,- metricId: string,- id: string,+ params?: DataQualityChecksListParams,options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getDataCatalogMetricsCheckSuiteRunsRetrieveUrl(projectId, metricId, id), {+): Promise<PaginatedDataQualityOverviewCheckListApi> => {+ return apiMutator<PaginatedDataQualityOverviewCheckListApi>(getDataQualityChecksListUrl(projectId, params), {...options,method: 'GET',})}-export const getDataCatalogMetricsCheckSuiteRunsCheckRunsListUrl = (- projectId: string,- metricId: string,- id: string-) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/check_suite_runs/${id}/check_runs/`-}--/**- * Every check execution in this suite run.- */-export const dataCatalogMetricsCheckSuiteRunsCheckRunsList = async (- projectId: string,- metricId: string,- id: string,- options?: RequestInit-): Promise<DataQualityCheckRunApi[]> => {- return apiMutator<DataQualityCheckRunApi[]>(- getDataCatalogMetricsCheckSuiteRunsCheckRunsListUrl(projectId, metricId, id),- {- ...options,- method: 'GET',- }- )-}--export const getDataCatalogMetricsChecksListUrl = (- projectId: string,- metricId: string,- params?: DataCatalogMetricsChecksListParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/?${stringifiedParams}`- : `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/`-}--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const dataCatalogMetricsChecksList = async (- projectId: string,- metricId: string,- params?: DataCatalogMetricsChecksListParams,- options?: RequestInit-): Promise<PaginatedDataQualityCheckListApi> => {- return apiMutator<PaginatedDataQualityCheckListApi>(- getDataCatalogMetricsChecksListUrl(projectId, metricId, params),- {- ...options,- method: 'GET',- }- )-}--export const getDataCatalogMetricsChecksCreateUrl = (projectId: string, metricId: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/`+export const getDataQualityChecksCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_quality_checks/`}/**- * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.+ * Create a check on the table, view or metric named by subject_type and subject_uuid, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.*/-export const dataCatalogMetricsChecksCreate = async (+export const dataQualityChecksCreate = async (projectId: string,- metricId: string,- dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,+ dataQualityCheckCreateApi: NonReadonly<DataQualityCheckCreateApi>,options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getDataCatalogMetricsChecksCreateUrl(projectId, metricId), {+): Promise<DataQualityCheckCreateApi> => {+ return apiMutator<DataQualityCheckCreateApi>(getDataQualityChecksCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dataQualityCheckApi),+ body: JSON.stringify(dataQualityCheckCreateApi),})}-export const getDataCatalogMetricsChecksRetrieveUrl = (projectId: string, metricId: string, id: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/`+export const getDataQualityChecksRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_quality_checks/${id}/`}/**- * CRUD for one subject's checks, plus the actions that run them and report on them.+ * Every check in the project: authoring, running, results, health, and schedules.*/-export const dataCatalogMetricsChecksRetrieve = async (+export const dataQualityChecksRetrieve = async (projectId: string,- metricId: string,id: string,options?: RequestInit): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getDataCatalogMetricsChecksRetrieveUrl(projectId, metricId, id), {+ return apiMutator<DataQualityCheckApi>(getDataQualityChecksRetrieveUrl(projectId, id), {...options,method: 'GET',})}-export const getDataCatalogMetricsChecksUpdateUrl = (projectId: string, metricId: string, id: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/`+export const getDataQualityChecksUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_quality_checks/${id}/`}/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.+ * Edit this check in place, including what it asserts (check_type, column_name, config). The subject it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.*/-export const dataCatalogMetricsChecksUpdate = async (+export const dataQualityChecksUpdate = async (projectId: string,- metricId: string,id: string,dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,options?: RequestInit): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getDataCatalogMetricsChecksUpdateUrl(projectId, metricId, id), {+ return apiMutator<DataQualityCheckApi>(getDataQualityChecksUpdateUrl(projectId, id), {...options,method: 'PUT',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -233,21 +138,20 @@ export const dataCatalogMetricsChecksUpdate = async (})}-export const getDataCatalogMetricsChecksPartialUpdateUrl = (projectId: string, metricId: string, id: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/`+export const getDataQualityChecksPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_quality_checks/${id}/`}/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.+ * Edit this check in place, including what it asserts (check_type, column_name, config). The subject it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.*/-export const dataCatalogMetricsChecksPartialUpdate = async (+export const dataQualityChecksPartialUpdate = async (projectId: string,- metricId: string,id: string,patchedDataQualityCheckApi?: NonReadonly<PatchedDataQualityCheckApi>,options?: RequestInit): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getDataCatalogMetricsChecksPartialUpdateUrl(projectId, metricId, id), {+ return apiMutator<DataQualityCheckApi>(getDataQualityChecksPartialUpdateUrl(projectId, id), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -255,184 +159,90 @@ export const dataCatalogMetricsChecksPartialUpdate = async (})}-export const getDataCatalogMetricsChecksDestroyUrl = (projectId: string, metricId: string, id: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/`+export const getDataQualityChecksDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_quality_checks/${id}/`}/**- * CRUD for one subject's checks, plus the actions that run them and report on them.+ * Every check in the project: authoring, running, results, health, and schedules.*/-export const dataCatalogMetricsChecksDestroy = async (- projectId: string,- metricId: string,- id: string,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getDataCatalogMetricsChecksDestroyUrl(projectId, metricId, id), {+export const dataQualityChecksDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getDataQualityChecksDestroyUrl(projectId, id), {...options,method: 'DELETE',})}-export const getDataCatalogMetricsChecksRunCreateUrl = (projectId: string, metricId: string, id: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/run/`+export const getDataQualityChecksRunCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_quality_checks/${id}/run/`}/*** Run this check now. Returns the suite run to poll for the report.*/-export const dataCatalogMetricsChecksRunCreate = async (+export const dataQualityChecksRunCreate = async (projectId: string,- metricId: string,id: string,options?: RequestInit): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getDataCatalogMetricsChecksRunCreateUrl(projectId, metricId, id), {+ return apiMutator<DataQualitySuiteRunApi>(getDataQualityChecksRunCreateUrl(projectId, id), {...options,method: 'POST',})}-export const getDataCatalogMetricsChecksRunsListUrl = (projectId: string, metricId: string, id: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/runs/`+export const getDataQualityChecksRunsListUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_quality_checks/${id}/runs/`}/*** Recent run history for this check, newest first.*/-export const dataCatalogMetricsChecksRunsList = async (+export const dataQualityChecksRunsList = async (projectId: string,- metricId: string,id: string,options?: RequestInit): Promise<DataQualityCheckRunApi[]> => {- return apiMutator<DataQualityCheckRunApi[]>(getDataCatalogMetricsChecksRunsListUrl(projectId, metricId, id), {+ return apiMutator<DataQualityCheckRunApi[]>(getDataQualityChecksRunsListUrl(projectId, id), {...options,method: 'GET',})}-export const getDataCatalogMetricsChecksCheckTypesListUrl = (projectId: string, metricId: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/check_types/`-}--/**- * The check types this project can author, with the JSON schema of each type's config.- */-export const dataCatalogMetricsChecksCheckTypesList = async (+export const getDataQualityChecksCheckTypesListUrl = (projectId: string,- metricId: string,- options?: RequestInit-): Promise<DataQualityCheckTypeApi[]> => {- return apiMutator<DataQualityCheckTypeApi[]>(getDataCatalogMetricsChecksCheckTypesListUrl(projectId, metricId), {- ...options,- method: 'GET',- })-}--export const getDataCatalogMetricsChecksHealthRetrieveUrl = (projectId: string, metricId: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/health/`-}+ params?: DataQualityChecksCheckTypesListParams+) => {+ const normalizedParams = new URLSearchParams()-/**- * Health rollup for this table or view, from the denormalized status of its checks.- */-export const dataCatalogMetricsChecksHealthRetrieve = async (- projectId: string,- metricId: string,- options?: RequestInit-): Promise<DataQualitySubjectHealthApi> => {- return apiMutator<DataQualitySubjectHealthApi>(getDataCatalogMetricsChecksHealthRetrieveUrl(projectId, metricId), {- ...options,- method: 'GET',+ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }})-}-export const getDataCatalogMetricsChecksOutputSchemaRetrieveUrl = (projectId: string, metricId: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/output_schema/`-}--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const dataCatalogMetricsChecksOutputSchemaRetrieve = async (- projectId: string,- metricId: string,- options?: RequestInit-): Promise<DataQualityOutputSchemaApi> => {- return apiMutator<DataQualityOutputSchemaApi>(- getDataCatalogMetricsChecksOutputSchemaRetrieveUrl(projectId, metricId),- {- ...options,- method: 'GET',- }- )-}+ const stringifiedParams = normalizedParams.toString()-export const getDataCatalogMetricsChecksRunAllCreateUrl = (projectId: string, metricId: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/run_all/`+ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/data_quality_checks/check_types/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_quality_checks/check_types/`}/**- * Run every enabled check on this table or view. Returns the suite run to poll.+ * The check types this project can author, with the JSON schema of each type's config. Pass subject_type to narrow it to the types that kind of subject supports.*/-export const dataCatalogMetricsChecksRunAllCreate = async (+export const dataQualityChecksCheckTypesList = async (projectId: string,- metricId: string,+ params?: DataQualityChecksCheckTypesListParams,options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getDataCatalogMetricsChecksRunAllCreateUrl(projectId, metricId), {+): Promise<DataQualityCheckTypeApi[]> => {+ return apiMutator<DataQualityCheckTypeApi[]>(getDataQualityChecksCheckTypesListUrl(projectId, params), {...options,- method: 'POST',+ method: 'GET',})}-export const getDataCatalogMetricsChecksScheduleRetrieveUrl = (projectId: string, metricId: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/schedule/`-}--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const dataCatalogMetricsChecksScheduleRetrieve = async (- projectId: string,- metricId: string,- options?: RequestInit-): Promise<DataQualityCheckScheduleApi> => {- return apiMutator<DataQualityCheckScheduleApi>(- getDataCatalogMetricsChecksScheduleRetrieveUrl(projectId, metricId),- {- ...options,- method: 'GET',- }- )-}--export const getDataCatalogMetricsChecksSchedulePartialUpdateUrl = (projectId: string, metricId: string) => {- return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/schedule/`-}--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const dataCatalogMetricsChecksSchedulePartialUpdate = async (- projectId: string,- metricId: string,- patchedDataQualityCheckScheduleUpdateApi?: PatchedDataQualityCheckScheduleUpdateApi,- options?: RequestInit-): Promise<DataQualityCheckScheduleApi> => {- return apiMutator<DataQualityCheckScheduleApi>(- getDataCatalogMetricsChecksSchedulePartialUpdateUrl(projectId, metricId),- {- ...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedDataQualityCheckScheduleUpdateApi),- }- )-}--export const getDataQualityChecksListUrl = (projectId: string, params?: DataQualityChecksListParams) => {+export const getDataQualityChecksHealthListUrl = (projectId: string, params?: DataQualityChecksHealthListParams) => {const normalizedParams = new URLSearchParams()Object.entries(params || {}).forEach(([key, value]) => {@@ -444,40 +254,19 @@ export const getDataQualityChecksListUrl = (projectId: string, params?: DataQualconst stringifiedParams = normalizedParams.toString()return stringifiedParams.length > 0- ? `/api/projects/${projectId}/data_quality_checks/?${stringifiedParams}`- : `/api/projects/${projectId}/data_quality_checks/`-}--/**- * Every check in the project, and the health of every subject that has one.- *- * The per-subject surfaces answer "what is wrong with this table". This answers "what is wrong- * across the project", which they cannot: each is nested under one parent. Read-only -- authoring- * still happens against the subject that owns the check.- */-export const dataQualityChecksList = async (- projectId: string,- params?: DataQualityChecksListParams,- options?: RequestInit-): Promise<PaginatedDataQualityOverviewCheckListApi> => {- return apiMutator<PaginatedDataQualityOverviewCheckListApi>(getDataQualityChecksListUrl(projectId, params), {- ...options,- method: 'GET',- })-}--export const getDataQualityChecksHealthListUrl = (projectId: string) => {- return `/api/projects/${projectId}/data_quality_checks/health/`+ ? `/api/projects/${projectId}/data_quality_checks/health/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_quality_checks/health/`}/**- * Health rollup for every table and view in the project that has checks.+ * Health rollup per subject, for every subject in the project that has checks. Narrow it to one subject with subject_type and subject_uuid.*/export const dataQualityChecksHealthList = async (projectId: string,+ params?: DataQualityChecksHealthListParams,options?: RequestInit): Promise<DataQualitySubjectHealthApi[]> => {- return apiMutator<DataQualitySubjectHealthApi[]>(getDataQualityChecksHealthListUrl(projectId), {+ return apiMutator<DataQualitySubjectHealthApi[]>(getDataQualityChecksHealthListUrl(projectId, params), {...options,method: 'GET',})@@ -488,11 +277,7 @@ export const getDataQualityChecksMetricSubjectsListUrl = (projectId: string) =>}/**- * Every check in the project, and the health of every subject that has one.- *- * The per-subject surfaces answer "what is wrong with this table". This answers "what is wrong- * across the project", which they cannot: each is nested under one parent. Read-only -- authoring- * still happens against the subject that owns the check.+ * Every check in the project: authoring, running, results, health, and schedules.*/export const dataQualityChecksMetricSubjectsList = async (projectId: string,@@ -504,7 +289,10 @@ export const dataQualityChecksMetricSubjectsList = async (})}-export const getDataQualityRunsListUrl = (projectId: string, params?: DataQualityRunsListParams) => {+export const getDataQualityChecksOutputSchemaRetrieveUrl = (+ projectId: string,+ params?: DataQualityChecksOutputSchemaRetrieveParams+) => {const normalizedParams = new URLSearchParams()Object.entries(params || {}).forEach(([key, value]) => {@@ -516,74 +304,27 @@ export const getDataQualityRunsListUrl = (projectId: string, params?: DataQualitconst stringifiedParams = normalizedParams.toString()return stringifiedParams.length > 0- ? `/api/projects/${projectId}/data_quality_runs/?${stringifiedParams}`- : `/api/projects/${projectId}/data_quality_runs/`-}--/**- * Project-wide check runs: start one over a selection, and read every run the project has had.- *- * The per-subject surfaces only serve runs scoped to their own subject, so this is where a sweep- * across several subjects -- a manual project-wide run, a materialization, a source sync -- is- * readable. Scoped to `warehouse_objects` because it spans tables and views at once.- */-export const dataQualityRunsList = async (- projectId: string,- params?: DataQualityRunsListParams,- options?: RequestInit-): Promise<PaginatedDataQualitySuiteRunListApi> => {- return apiMutator<PaginatedDataQualitySuiteRunListApi>(getDataQualityRunsListUrl(projectId, params), {- ...options,- method: 'GET',- })-}--export const getDataQualityRunsCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/data_quality_runs/`-}--/**- * Run the named checks now, or every enabled check in the project when none are named. Returns the suite run to poll for the report.- */-export const dataQualityRunsCreate = async (- projectId: string,- dataQualityRunRequestApi?: DataQualityRunRequestApi,- options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getDataQualityRunsCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dataQualityRunRequestApi),- })-}--export const getDataQualityRunsRetrieveUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/data_quality_runs/${id}/`+ ? `/api/projects/${projectId}/data_quality_checks/output_schema/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_quality_checks/output_schema/`}/**- * Project-wide check runs: start one over a selection, and read every run the project has had.- *- * The per-subject surfaces only serve runs scoped to their own subject, so this is where a sweep- * across several subjects -- a manual project-wide run, a materialization, a source sync -- is- * readable. Scoped to `warehouse_objects` because it spans tables and views at once.+ * Columns the subject's query returns, for authoring a check against them. Metrics only.*/-export const dataQualityRunsRetrieve = async (+export const dataQualityChecksOutputSchemaRetrieve = async (projectId: string,- id: string,+ params?: DataQualityChecksOutputSchemaRetrieveParams,options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getDataQualityRunsRetrieveUrl(projectId, id), {+): Promise<DataQualityOutputSchemaApi> => {+ return apiMutator<DataQualityOutputSchemaApi>(getDataQualityChecksOutputSchemaRetrieveUrl(projectId, params), {...options,method: 'GET',})}-export const getWarehouseSavedQueriesCheckSuiteRunsListUrl = (+export const getDataQualityChecksScheduleRetrieveUrl = (projectId: string,- savedQueryId: string,- params?: WarehouseSavedQueriesCheckSuiteRunsListParams+ params?: DataQualityChecksScheduleRetrieveParams) => {const normalizedParams = new URLSearchParams()@@ -596,85 +337,62 @@ export const getWarehouseSavedQueriesCheckSuiteRunsListUrl = (const stringifiedParams = normalizedParams.toString()return stringifiedParams.length > 0- ? `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/check_suite_runs/?${stringifiedParams}`- : `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/check_suite_runs/`+ ? `/api/projects/${projectId}/data_quality_checks/schedule/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_quality_checks/schedule/`}/**- * Read-only reports for this subject's check-suite executions.+ * The schedule every enabled check on this subject runs on.*/-export const warehouseSavedQueriesCheckSuiteRunsList = async (+export const dataQualityChecksScheduleRetrieve = async (projectId: string,- savedQueryId: string,- params?: WarehouseSavedQueriesCheckSuiteRunsListParams,+ params?: DataQualityChecksScheduleRetrieveParams,options?: RequestInit-): Promise<PaginatedDataQualitySuiteRunListApi> => {- return apiMutator<PaginatedDataQualitySuiteRunListApi>(- getWarehouseSavedQueriesCheckSuiteRunsListUrl(projectId, savedQueryId, params),- {- ...options,- method: 'GET',- }- )+): Promise<DataQualityCheckScheduleApi> => {+ return apiMutator<DataQualityCheckScheduleApi>(getDataQualityChecksScheduleRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })}-export const getWarehouseSavedQueriesCheckSuiteRunsRetrieveUrl = (- projectId: string,- savedQueryId: string,- id: string-) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/check_suite_runs/${id}/`+export const getDataQualityChecksSchedulePartialUpdateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_quality_checks/schedule/`}/**- * Read-only reports for this subject's check-suite executions.+ * Change how often this subject's checks run, or stop running them automatically. Name the subject with subject_type and subject_uuid in the body.*/-export const warehouseSavedQueriesCheckSuiteRunsRetrieve = async (+export const dataQualityChecksSchedulePartialUpdate = async (projectId: string,- savedQueryId: string,- id: string,+ patchedDataQualityCheckScheduleUpdateApi?: PatchedDataQualityCheckScheduleUpdateApi,options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(- getWarehouseSavedQueriesCheckSuiteRunsRetrieveUrl(projectId, savedQueryId, id),- {- ...options,- method: 'GET',- }- )+): Promise<DataQualityCheckScheduleApi> => {+ return apiMutator<DataQualityCheckScheduleApi>(getDataQualityChecksSchedulePartialUpdateUrl(projectId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedDataQualityCheckScheduleUpdateApi),+ })}-export const getWarehouseSavedQueriesCheckSuiteRunsCheckRunsListUrl = (- projectId: string,- savedQueryId: string,- id: string-) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/check_suite_runs/${id}/check_runs/`+export const getDataQualityChecksSubjectsListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_quality_checks/subjects/`}/**- * Every check execution in this suite run.+ * Everything in this project you can author a check on, with each subject's columns.*/-export const warehouseSavedQueriesCheckSuiteRunsCheckRunsList = async (+export const dataQualityChecksSubjectsList = async (projectId: string,- savedQueryId: string,- id: string,options?: RequestInit-): Promise<DataQualityCheckRunApi[]> => {- return apiMutator<DataQualityCheckRunApi[]>(- getWarehouseSavedQueriesCheckSuiteRunsCheckRunsListUrl(projectId, savedQueryId, id),- {- ...options,- method: 'GET',- }- )+): Promise<DataQualitySubjectApi[]> => {+ return apiMutator<DataQualitySubjectApi[]>(getDataQualityChecksSubjectsListUrl(projectId), {+ ...options,+ method: 'GET',+ })}-export const getWarehouseSavedQueriesChecksListUrl = (- projectId: string,- savedQueryId: string,- params?: WarehouseSavedQueriesChecksListParams-) => {+export const getDataQualityRunsListUrl = (projectId: string, params?: DataQualityRunsListParams) => {const normalizedParams = new URLSearchParams()Object.entries(params || {}).forEach(([key, value]) => {@@ -686,540 +404,79 @@ export const getWarehouseSavedQueriesChecksListUrl = (const stringifiedParams = normalizedParams.toString()return stringifiedParams.length > 0- ? `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/?${stringifiedParams}`- : `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/`+ ? `/api/projects/${projectId}/data_quality_runs/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_quality_runs/`}/**- * CRUD for one subject's checks, plus the actions that run them and report on them.+ * Every check-suite run in the project, newest first. Narrow it to one subject with subject_type and subject_uuid.*/-export const warehouseSavedQueriesChecksList = async (+export const dataQualityRunsList = async (projectId: string,- savedQueryId: string,- params?: WarehouseSavedQueriesChecksListParams,+ params?: DataQualityRunsListParams,options?: RequestInit-): Promise<PaginatedDataQualityCheckListApi> => {- return apiMutator<PaginatedDataQualityCheckListApi>(- getWarehouseSavedQueriesChecksListUrl(projectId, savedQueryId, params),- {- ...options,- method: 'GET',- }- )+): Promise<PaginatedDataQualitySuiteRunListApi> => {+ return apiMutator<PaginatedDataQualitySuiteRunListApi>(getDataQualityRunsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })}-export const getWarehouseSavedQueriesChecksCreateUrl = (projectId: string, savedQueryId: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/`+export const getDataQualityRunsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_quality_runs/`}/**- * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.+ * Run checks now: the ones named by check_ids, every enabled check on the subject named by subject_type and subject_uuid, or every enabled check in the project when neither is given. Returns the suite run to poll for the report.*/-export const warehouseSavedQueriesChecksCreate = async (+export const dataQualityRunsCreate = async (projectId: string,- savedQueryId: string,- dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,+ dataQualityRunRequestApi?: DataQualityRunRequestApi,options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getWarehouseSavedQueriesChecksCreateUrl(projectId, savedQueryId), {+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getDataQualityRunsCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dataQualityCheckApi),+ body: JSON.stringify(dataQualityRunRequestApi),})}-export const getWarehouseSavedQueriesChecksRetrieveUrl = (projectId: string, savedQueryId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/`+export const getDataQualityRunsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_quality_runs/${id}/`}/**- * CRUD for one subject's checks, plus the actions that run them and report on them.+ * Check-suite executions: start one over a selection, and read every run the project has had.+ *+ * A suite run may sweep several subjects at once -- a manual project-wide run, a materialization,+ * a source sync -- so it is reported here rather than under any one of them.*/-export const warehouseSavedQueriesChecksRetrieve = async (+export const dataQualityRunsRetrieve = async (projectId: string,- savedQueryId: string,id: string,options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getWarehouseSavedQueriesChecksRetrieveUrl(projectId, savedQueryId, id), {+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getDataQualityRunsRetrieveUrl(projectId, id), {...options,method: 'GET',})}-export const getWarehouseSavedQueriesChecksUpdateUrl = (projectId: string, savedQueryId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/`+export const getDataQualityRunsCheckRunsListUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/data_quality_runs/${id}/check_runs/`}/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.+ * Every check execution in this suite run.*/-export const warehouseSavedQueriesChecksUpdate = async (+export const dataQualityRunsCheckRunsList = async (projectId: string,- savedQueryId: string,id: string,- dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getWarehouseSavedQueriesChecksUpdateUrl(projectId, savedQueryId, id), {- ...options,- method: 'PUT',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dataQualityCheckApi),- })-}--export const getWarehouseSavedQueriesChecksPartialUpdateUrl = (projectId: string, savedQueryId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/`-}--/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.- */-export const warehouseSavedQueriesChecksPartialUpdate = async (- projectId: string,- savedQueryId: string,- id: string,- patchedDataQualityCheckApi?: NonReadonly<PatchedDataQualityCheckApi>,- options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(- getWarehouseSavedQueriesChecksPartialUpdateUrl(projectId, savedQueryId, id),- {- ...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedDataQualityCheckApi),- }- )-}--export const getWarehouseSavedQueriesChecksDestroyUrl = (projectId: string, savedQueryId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/`-}--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const warehouseSavedQueriesChecksDestroy = async (- projectId: string,- savedQueryId: string,- id: string,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getWarehouseSavedQueriesChecksDestroyUrl(projectId, savedQueryId, id), {- ...options,- method: 'DELETE',- })-}--export const getWarehouseSavedQueriesChecksRunCreateUrl = (projectId: string, savedQueryId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/run/`-}--/**- * Run this check now. Returns the suite run to poll for the report.- */-export const warehouseSavedQueriesChecksRunCreate = async (- projectId: string,- savedQueryId: string,- id: string,- options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getWarehouseSavedQueriesChecksRunCreateUrl(projectId, savedQueryId, id), {- ...options,- method: 'POST',- })-}--export const getWarehouseSavedQueriesChecksRunsListUrl = (projectId: string, savedQueryId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/runs/`-}--/**- * Recent run history for this check, newest first.- */-export const warehouseSavedQueriesChecksRunsList = async (- projectId: string,- savedQueryId: string,- id: string,- options?: RequestInit-): Promise<DataQualityCheckRunApi[]> => {- return apiMutator<DataQualityCheckRunApi[]>(- getWarehouseSavedQueriesChecksRunsListUrl(projectId, savedQueryId, id),- {- ...options,- method: 'GET',- }- )-}--export const getWarehouseSavedQueriesChecksCheckTypesListUrl = (projectId: string, savedQueryId: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/check_types/`-}--/**- * The check types this project can author, with the JSON schema of each type's config.- */-export const warehouseSavedQueriesChecksCheckTypesList = async (- projectId: string,- savedQueryId: string,- options?: RequestInit-): Promise<DataQualityCheckTypeApi[]> => {- return apiMutator<DataQualityCheckTypeApi[]>(- getWarehouseSavedQueriesChecksCheckTypesListUrl(projectId, savedQueryId),- {- ...options,- method: 'GET',- }- )-}--export const getWarehouseSavedQueriesChecksHealthRetrieveUrl = (projectId: string, savedQueryId: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/health/`-}--/**- * Health rollup for this table or view, from the denormalized status of its checks.- */-export const warehouseSavedQueriesChecksHealthRetrieve = async (- projectId: string,- savedQueryId: string,- options?: RequestInit-): Promise<DataQualitySubjectHealthApi> => {- return apiMutator<DataQualitySubjectHealthApi>(- getWarehouseSavedQueriesChecksHealthRetrieveUrl(projectId, savedQueryId),- {- ...options,- method: 'GET',- }- )-}--export const getWarehouseSavedQueriesChecksRunAllCreateUrl = (projectId: string, savedQueryId: string) => {- return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/run_all/`-}--/**- * Run every enabled check on this table or view. Returns the suite run to poll.- */-export const warehouseSavedQueriesChecksRunAllCreate = async (- projectId: string,- savedQueryId: string,- options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getWarehouseSavedQueriesChecksRunAllCreateUrl(projectId, savedQueryId), {- ...options,- method: 'POST',- })-}--export const getWarehouseTablesCheckSuiteRunsListUrl = (- projectId: string,- tableId: string,- params?: WarehouseTablesCheckSuiteRunsListParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/warehouse_tables/${tableId}/check_suite_runs/?${stringifiedParams}`- : `/api/projects/${projectId}/warehouse_tables/${tableId}/check_suite_runs/`-}--/**- * Read-only reports for this subject's check-suite executions.- */-export const warehouseTablesCheckSuiteRunsList = async (- projectId: string,- tableId: string,- params?: WarehouseTablesCheckSuiteRunsListParams,- options?: RequestInit-): Promise<PaginatedDataQualitySuiteRunListApi> => {- return apiMutator<PaginatedDataQualitySuiteRunListApi>(- getWarehouseTablesCheckSuiteRunsListUrl(projectId, tableId, params),- {- ...options,- method: 'GET',- }- )-}--export const getWarehouseTablesCheckSuiteRunsRetrieveUrl = (projectId: string, tableId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/check_suite_runs/${id}/`-}--/**- * Read-only reports for this subject's check-suite executions.- */-export const warehouseTablesCheckSuiteRunsRetrieve = async (- projectId: string,- tableId: string,- id: string,- options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getWarehouseTablesCheckSuiteRunsRetrieveUrl(projectId, tableId, id), {- ...options,- method: 'GET',- })-}--export const getWarehouseTablesCheckSuiteRunsCheckRunsListUrl = (projectId: string, tableId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/check_suite_runs/${id}/check_runs/`-}--/**- * Every check execution in this suite run.- */-export const warehouseTablesCheckSuiteRunsCheckRunsList = async (- projectId: string,- tableId: string,- id: string,- options?: RequestInit-): Promise<DataQualityCheckRunApi[]> => {- return apiMutator<DataQualityCheckRunApi[]>(- getWarehouseTablesCheckSuiteRunsCheckRunsListUrl(projectId, tableId, id),- {- ...options,- method: 'GET',- }- )-}--export const getWarehouseTablesChecksListUrl = (- projectId: string,- tableId: string,- params?: WarehouseTablesChecksListParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : String(value))- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/?${stringifiedParams}`- : `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/`-}--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const warehouseTablesChecksList = async (- projectId: string,- tableId: string,- params?: WarehouseTablesChecksListParams,- options?: RequestInit-): Promise<PaginatedDataQualityCheckListApi> => {- return apiMutator<PaginatedDataQualityCheckListApi>(getWarehouseTablesChecksListUrl(projectId, tableId, params), {- ...options,- method: 'GET',- })-}--export const getWarehouseTablesChecksCreateUrl = (projectId: string, tableId: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/`-}--/**- * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.- */-export const warehouseTablesChecksCreate = async (- projectId: string,- tableId: string,- dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,- options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getWarehouseTablesChecksCreateUrl(projectId, tableId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dataQualityCheckApi),- })-}--export const getWarehouseTablesChecksRetrieveUrl = (projectId: string, tableId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/`-}--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const warehouseTablesChecksRetrieve = async (- projectId: string,- tableId: string,- id: string,- options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getWarehouseTablesChecksRetrieveUrl(projectId, tableId, id), {+): Promise<DataQualityCheckRunApi[]> => {+ return apiMutator<DataQualityCheckRunApi[]>(getDataQualityRunsCheckRunsListUrl(projectId, id), {...options,method: 'GET',})}--export const getWarehouseTablesChecksUpdateUrl = (projectId: string, tableId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/`-}--/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.- */-export const warehouseTablesChecksUpdate = async (- projectId: string,- tableId: string,- id: string,- dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,- options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getWarehouseTablesChecksUpdateUrl(projectId, tableId, id), {- ...options,- method: 'PUT',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dataQualityCheckApi),- })-}--export const getWarehouseTablesChecksPartialUpdateUrl = (projectId: string, tableId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/`-}--/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.- */-export const warehouseTablesChecksPartialUpdate = async (- projectId: string,- tableId: string,- id: string,- patchedDataQualityCheckApi?: NonReadonly<PatchedDataQualityCheckApi>,- options?: RequestInit-): Promise<DataQualityCheckApi> => {- return apiMutator<DataQualityCheckApi>(getWarehouseTablesChecksPartialUpdateUrl(projectId, tableId, id), {- ...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedDataQualityCheckApi),- })-}--export const getWarehouseTablesChecksDestroyUrl = (projectId: string, tableId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/`-}--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const warehouseTablesChecksDestroy = async (- projectId: string,- tableId: string,- id: string,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getWarehouseTablesChecksDestroyUrl(projectId, tableId, id), {- ...options,- method: 'DELETE',- })-}--export const getWarehouseTablesChecksRunCreateUrl = (projectId: string, tableId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/run/`-}--/**- * Run this check now. Returns the suite run to poll for the report.- */-export const warehouseTablesChecksRunCreate = async (- projectId: string,- tableId: string,- id: string,- options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getWarehouseTablesChecksRunCreateUrl(projectId, tableId, id), {- ...options,- method: 'POST',- })-}--export const getWarehouseTablesChecksRunsListUrl = (projectId: string, tableId: string, id: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/runs/`-}--/**- * Recent run history for this check, newest first.- */-export const warehouseTablesChecksRunsList = async (- projectId: string,- tableId: string,- id: string,- options?: RequestInit-): Promise<DataQualityCheckRunApi[]> => {- return apiMutator<DataQualityCheckRunApi[]>(getWarehouseTablesChecksRunsListUrl(projectId, tableId, id), {- ...options,- method: 'GET',- })-}--export const getWarehouseTablesChecksCheckTypesListUrl = (projectId: string, tableId: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/check_types/`-}--/**- * The check types this project can author, with the JSON schema of each type's config.- */-export const warehouseTablesChecksCheckTypesList = async (- projectId: string,- tableId: string,- options?: RequestInit-): Promise<DataQualityCheckTypeApi[]> => {- return apiMutator<DataQualityCheckTypeApi[]>(getWarehouseTablesChecksCheckTypesListUrl(projectId, tableId), {- ...options,- method: 'GET',- })-}--export const getWarehouseTablesChecksHealthRetrieveUrl = (projectId: string, tableId: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/health/`-}--/**- * Health rollup for this table or view, from the denormalized status of its checks.- */-export const warehouseTablesChecksHealthRetrieve = async (- projectId: string,- tableId: string,- options?: RequestInit-): Promise<DataQualitySubjectHealthApi> => {- return apiMutator<DataQualitySubjectHealthApi>(getWarehouseTablesChecksHealthRetrieveUrl(projectId, tableId), {- ...options,- method: 'GET',- })-}--export const getWarehouseTablesChecksRunAllCreateUrl = (projectId: string, tableId: string) => {- return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/run_all/`-}--/**- * Run every enabled check on this table or view. Returns the suite run to poll.- */-export const warehouseTablesChecksRunAllCreate = async (- projectId: string,- tableId: string,- options?: RequestInit-): Promise<DataQualitySuiteRunApi> => {- return apiMutator<DataQualitySuiteRunApi>(getWarehouseTablesChecksRunAllCreateUrl(projectId, tableId), {- ...options,- method: 'POST',- })-}diff --git a/products/data_quality/frontend/generated/api.zod.ts b/products/data_quality/frontend/generated/api.zod.tsindex 63170d34f5bc..418e39a57dc0 100644--- a/products/data_quality/frontend/generated/api.zod.ts+++ b/products/data_quality/frontend/generated/api.zod.ts@@ -10,293 +10,40 @@import * as zod from 'zod'/**- * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.+ * Create a check on the table, view or metric named by subject_type and subject_uuid, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.*/-export const dataCatalogMetricsChecksCreateBodyNameOneMax = 128+export const dataQualityChecksCreateBodyNameOneMax = 128-export const dataCatalogMetricsChecksCreateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const dataCatalogMetricsChecksCreateBodyNameTwoMax = 0+export const dataQualityChecksCreateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataQualityChecksCreateBodyNameTwoMax = 0-export const dataCatalogMetricsChecksCreateBodyColumnNameMax = 400+export const dataQualityChecksCreateBodyColumnNameMax = 400-export const dataCatalogMetricsChecksCreateBodyAiModelMax = 128+export const dataQualityChecksCreateBodyAiModelMax = 128-export const dataCatalogMetricsChecksCreateBodyConfidenceMin = 0-export const dataCatalogMetricsChecksCreateBodyConfidenceMax = 1+export const dataQualityChecksCreateBodyConfidenceMin = 0+export const dataQualityChecksCreateBodyConfidenceMax = 1-export const DataCatalogMetricsChecksCreateBody = /* @__PURE__ */ zod+export const DataQualityChecksCreateBody = /* @__PURE__ */ zod.object({name: zod.union([- zod- .string()- .max(dataCatalogMetricsChecksCreateBodyNameOneMax)- .regex(dataCatalogMetricsChecksCreateBodyNameOneRegExp),- zod.string().max(dataCatalogMetricsChecksCreateBodyNameTwoMax),+ zod.string().max(dataQualityChecksCreateBodyNameOneMax).regex(dataQualityChecksCreateBodyNameOneRegExp),+ zod.string().max(dataQualityChecksCreateBodyNameTwoMax),]).optional().describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),description: zod.string().optional().describe('Why this check exists and what a failure means.'),- column_name: zod- .string()- .max(dataCatalogMetricsChecksCreateBodyColumnNameMax)- .optional()- .describe('Column the check applies to. Omit for table-scoped types like row_count.'),- check_type: zod- .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])- .describe(- '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- )+ subject_type: zod+ .enum(['table', 'view', 'metric'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric').describe(- 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- ),- config: zod- .record(zod.string(), zod.unknown())- .optional()- .describe("Type-specific configuration, validated against the check type's JSON schema."),- severity: zod- .enum(['error', 'warn'])- .describe('\* `error` - error\n\* `warn` - warn')- .optional()- .describe(- "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"+ "Kind of catalog object to check: 'table', 'view', or 'metric'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric"),- enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),- tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),- created_source: zod- .enum(['user', 'ai_generated'])- .describe('\* `user` - user\n\* `ai_generated` - ai_generated')- .optional()- .describe(- "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"- ),- ai_model: zod- .string()- .max(dataCatalogMetricsChecksCreateBodyAiModelMax)- .optional()- .describe('Model that generated the check, if AI-authored.'),- confidence: zod- .number()- .min(dataCatalogMetricsChecksCreateBodyConfidenceMin)- .max(dataCatalogMetricsChecksCreateBodyConfidenceMax)- .nullish()- .describe("AI author's confidence in the check, 0-1."),- reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),- })- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')--/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.- */-export const dataCatalogMetricsChecksUpdateBodyNameOneMax = 128--export const dataCatalogMetricsChecksUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const dataCatalogMetricsChecksUpdateBodyNameTwoMax = 0--export const dataCatalogMetricsChecksUpdateBodyColumnNameMax = 400--export const dataCatalogMetricsChecksUpdateBodyAiModelMax = 128--export const dataCatalogMetricsChecksUpdateBodyConfidenceMin = 0-export const dataCatalogMetricsChecksUpdateBodyConfidenceMax = 1--export const DataCatalogMetricsChecksUpdateBody = /* @__PURE__ */ zod- .object({- name: zod- .union([- zod- .string()- .max(dataCatalogMetricsChecksUpdateBodyNameOneMax)- .regex(dataCatalogMetricsChecksUpdateBodyNameOneRegExp),- zod.string().max(dataCatalogMetricsChecksUpdateBodyNameTwoMax),- ])- .optional()- .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),- description: zod.string().optional().describe('Why this check exists and what a failure means.'),- column_name: zod- .string()- .max(dataCatalogMetricsChecksUpdateBodyColumnNameMax)- .optional()- .describe('Column the check applies to. Omit for table-scoped types like row_count.'),- check_type: zod- .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])- .describe(- '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- )- .describe(- 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- ),- config: zod- .record(zod.string(), zod.unknown())- .optional()- .describe("Type-specific configuration, validated against the check type's JSON schema."),- severity: zod- .enum(['error', 'warn'])- .describe('\* `error` - error\n\* `warn` - warn')- .optional()- .describe(- "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"- ),- enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),- tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),- created_source: zod- .enum(['user', 'ai_generated'])- .describe('\* `user` - user\n\* `ai_generated` - ai_generated')- .optional()- .describe(- "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"- ),- ai_model: zod- .string()- .max(dataCatalogMetricsChecksUpdateBodyAiModelMax)- .optional()- .describe('Model that generated the check, if AI-authored.'),- confidence: zod- .number()- .min(dataCatalogMetricsChecksUpdateBodyConfidenceMin)- .max(dataCatalogMetricsChecksUpdateBodyConfidenceMax)- .nullish()- .describe("AI author's confidence in the check, 0-1."),- reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),- })- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')--/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.- */-export const dataCatalogMetricsChecksPartialUpdateBodyNameOneMax = 128--export const dataCatalogMetricsChecksPartialUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const dataCatalogMetricsChecksPartialUpdateBodyNameTwoMax = 0--export const dataCatalogMetricsChecksPartialUpdateBodyColumnNameMax = 400--export const dataCatalogMetricsChecksPartialUpdateBodyAiModelMax = 128--export const dataCatalogMetricsChecksPartialUpdateBodyConfidenceMin = 0-export const dataCatalogMetricsChecksPartialUpdateBodyConfidenceMax = 1--export const DataCatalogMetricsChecksPartialUpdateBody = /* @__PURE__ */ zod- .object({- name: zod- .union([- zod- .string()- .max(dataCatalogMetricsChecksPartialUpdateBodyNameOneMax)- .regex(dataCatalogMetricsChecksPartialUpdateBodyNameOneRegExp),- zod.string().max(dataCatalogMetricsChecksPartialUpdateBodyNameTwoMax),- ])- .optional()- .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),- description: zod.string().optional().describe('Why this check exists and what a failure means.'),- column_name: zod- .string()- .max(dataCatalogMetricsChecksPartialUpdateBodyColumnNameMax)- .optional()- .describe('Column the check applies to. Omit for table-scoped types like row_count.'),- check_type: zod- .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])- .describe(- '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- )- .optional()- .describe(- 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- ),- config: zod- .record(zod.string(), zod.unknown())- .optional()- .describe("Type-specific configuration, validated against the check type's JSON schema."),- severity: zod- .enum(['error', 'warn'])- .describe('\* `error` - error\n\* `warn` - warn')- .optional()- .describe(- "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"- ),- enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),- tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),- created_source: zod- .enum(['user', 'ai_generated'])- .describe('\* `user` - user\n\* `ai_generated` - ai_generated')- .optional()- .describe(- "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"- ),- ai_model: zod- .string()- .max(dataCatalogMetricsChecksPartialUpdateBodyAiModelMax)- .optional()- .describe('Model that generated the check, if AI-authored.'),- confidence: zod- .number()- .min(dataCatalogMetricsChecksPartialUpdateBodyConfidenceMin)- .max(dataCatalogMetricsChecksPartialUpdateBodyConfidenceMax)- .nullish()- .describe("AI author's confidence in the check, 0-1."),- reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),- })- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')--/**- * CRUD for one subject's checks, plus the actions that run them and report on them.- */-export const DataCatalogMetricsChecksSchedulePartialUpdateBody = /* @__PURE__ */ zod.object({- interval: zod- .enum(['1hour', '6hour', '12hour', '24hour', '7day'])- .describe(- '\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day'- )- .optional()- .describe(- 'How often all enabled checks on the metric run.\n\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day'- ),- enabled: zod.boolean().optional().describe('Whether checks run automatically on this schedule.'),-})--/**- * Run the named checks now, or every enabled check in the project when none are named. Returns the suite run to poll for the report.- */-export const DataQualityRunsCreateBody = /* @__PURE__ */ zod- .object({- check_ids: zod- .array(zod.uuid())- .optional()- .describe('Ids of the checks to run. Omit to run every enabled check in the project.'),- })- .describe('What to run in a project-wide suite run.')--/**- * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.- */-export const warehouseSavedQueriesChecksCreateBodyNameOneMax = 128--export const warehouseSavedQueriesChecksCreateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseSavedQueriesChecksCreateBodyNameTwoMax = 0--export const warehouseSavedQueriesChecksCreateBodyColumnNameMax = 400--export const warehouseSavedQueriesChecksCreateBodyAiModelMax = 128--export const warehouseSavedQueriesChecksCreateBodyConfidenceMin = 0-export const warehouseSavedQueriesChecksCreateBodyConfidenceMax = 1--export const WarehouseSavedQueriesChecksCreateBody = /* @__PURE__ */ zod- .object({- name: zod- .union([- zod- .string()- .max(warehouseSavedQueriesChecksCreateBodyNameOneMax)- .regex(warehouseSavedQueriesChecksCreateBodyNameOneRegExp),- zod.string().max(warehouseSavedQueriesChecksCreateBodyNameTwoMax),- ])- .optional()- .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),- description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ subject_uuid: zod.uuid().describe('Id of the table, view, or metric to check.'),column_name: zod.string()- .max(warehouseSavedQueriesChecksCreateBodyColumnNameMax)+ .max(dataQualityChecksCreateBodyColumnNameMax).optional().describe('Column the check applies to. Omit for table-scoped types like row_count.'),check_type: zod@@ -329,50 +76,47 @@ export const WarehouseSavedQueriesChecksCreateBody = /* @__PURE__ */ zod),ai_model: zod.string()- .max(warehouseSavedQueriesChecksCreateBodyAiModelMax)+ .max(dataQualityChecksCreateBodyAiModelMax).optional().describe('Model that generated the check, if AI-authored.'),confidence: zod.number()- .min(warehouseSavedQueriesChecksCreateBodyConfidenceMin)- .max(warehouseSavedQueriesChecksCreateBodyConfidenceMax)+ .min(dataQualityChecksCreateBodyConfidenceMin)+ .max(dataQualityChecksCreateBodyConfidenceMax).nullish().describe("AI author's confidence in the check, 0-1."),reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),})- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')+ .describe("The create body, where the subject is named for the only time in a check's life.")/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.+ * Edit this check in place, including what it asserts (check_type, column_name, config). The subject it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.*/-export const warehouseSavedQueriesChecksUpdateBodyNameOneMax = 128+export const dataQualityChecksUpdateBodyNameOneMax = 128-export const warehouseSavedQueriesChecksUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseSavedQueriesChecksUpdateBodyNameTwoMax = 0+export const dataQualityChecksUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataQualityChecksUpdateBodyNameTwoMax = 0-export const warehouseSavedQueriesChecksUpdateBodyColumnNameMax = 400+export const dataQualityChecksUpdateBodyColumnNameMax = 400-export const warehouseSavedQueriesChecksUpdateBodyAiModelMax = 128+export const dataQualityChecksUpdateBodyAiModelMax = 128-export const warehouseSavedQueriesChecksUpdateBodyConfidenceMin = 0-export const warehouseSavedQueriesChecksUpdateBodyConfidenceMax = 1+export const dataQualityChecksUpdateBodyConfidenceMin = 0+export const dataQualityChecksUpdateBodyConfidenceMax = 1-export const WarehouseSavedQueriesChecksUpdateBody = /* @__PURE__ */ zod+export const DataQualityChecksUpdateBody = /* @__PURE__ */ zod.object({name: zod.union([- zod- .string()- .max(warehouseSavedQueriesChecksUpdateBodyNameOneMax)- .regex(warehouseSavedQueriesChecksUpdateBodyNameOneRegExp),- zod.string().max(warehouseSavedQueriesChecksUpdateBodyNameTwoMax),+ zod.string().max(dataQualityChecksUpdateBodyNameOneMax).regex(dataQualityChecksUpdateBodyNameOneRegExp),+ zod.string().max(dataQualityChecksUpdateBodyNameTwoMax),]).optional().describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),description: zod.string().optional().describe('Why this check exists and what a failure means.'),column_name: zod.string()- .max(warehouseSavedQueriesChecksUpdateBodyColumnNameMax)+ .max(dataQualityChecksUpdateBodyColumnNameMax).optional().describe('Column the check applies to. Omit for table-scoped types like row_count.'),check_type: zod@@ -405,50 +149,52 @@ export const WarehouseSavedQueriesChecksUpdateBody = /* @__PURE__ */ zod),ai_model: zod.string()- .max(warehouseSavedQueriesChecksUpdateBodyAiModelMax)+ .max(dataQualityChecksUpdateBodyAiModelMax).optional().describe('Model that generated the check, if AI-authored.'),confidence: zod.number()- .min(warehouseSavedQueriesChecksUpdateBodyConfidenceMin)- .max(warehouseSavedQueriesChecksUpdateBodyConfidenceMax)+ .min(dataQualityChecksUpdateBodyConfidenceMin)+ .max(dataQualityChecksUpdateBodyConfidenceMax).nullish().describe("AI author's confidence in the check, 0-1."),reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),})- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')+ .describe(+ 'A check as it reads back, and everything an edit may change about it.\n\nThe subject is not one of those: it is writable only on ``DataQualityCheckCreate``.'+ )/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.+ * Edit this check in place, including what it asserts (check_type, column_name, config). The subject it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.*/-export const warehouseSavedQueriesChecksPartialUpdateBodyNameOneMax = 128+export const dataQualityChecksPartialUpdateBodyNameOneMax = 128-export const warehouseSavedQueriesChecksPartialUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseSavedQueriesChecksPartialUpdateBodyNameTwoMax = 0+export const dataQualityChecksPartialUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataQualityChecksPartialUpdateBodyNameTwoMax = 0-export const warehouseSavedQueriesChecksPartialUpdateBodyColumnNameMax = 400+export const dataQualityChecksPartialUpdateBodyColumnNameMax = 400-export const warehouseSavedQueriesChecksPartialUpdateBodyAiModelMax = 128+export const dataQualityChecksPartialUpdateBodyAiModelMax = 128-export const warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMin = 0-export const warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMax = 1+export const dataQualityChecksPartialUpdateBodyConfidenceMin = 0+export const dataQualityChecksPartialUpdateBodyConfidenceMax = 1-export const WarehouseSavedQueriesChecksPartialUpdateBody = /* @__PURE__ */ zod+export const DataQualityChecksPartialUpdateBody = /* @__PURE__ */ zod.object({name: zod.union([zod.string()- .max(warehouseSavedQueriesChecksPartialUpdateBodyNameOneMax)- .regex(warehouseSavedQueriesChecksPartialUpdateBodyNameOneRegExp),- zod.string().max(warehouseSavedQueriesChecksPartialUpdateBodyNameTwoMax),+ .max(dataQualityChecksPartialUpdateBodyNameOneMax)+ .regex(dataQualityChecksPartialUpdateBodyNameOneRegExp),+ zod.string().max(dataQualityChecksPartialUpdateBodyNameTwoMax),]).optional().describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),description: zod.string().optional().describe('Why this check exists and what a failure means.'),column_name: zod.string()- .max(warehouseSavedQueriesChecksPartialUpdateBodyColumnNameMax)+ .max(dataQualityChecksPartialUpdateBodyColumnNameMax).optional().describe('Column the check applies to. Omit for table-scoped types like row_count.'),check_type: zod@@ -482,244 +228,66 @@ export const WarehouseSavedQueriesChecksPartialUpdateBody = /* @__PURE__ */ zod),ai_model: zod.string()- .max(warehouseSavedQueriesChecksPartialUpdateBodyAiModelMax)+ .max(dataQualityChecksPartialUpdateBodyAiModelMax).optional().describe('Model that generated the check, if AI-authored.'),confidence: zod.number()- .min(warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMin)- .max(warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMax)+ .min(dataQualityChecksPartialUpdateBodyConfidenceMin)+ .max(dataQualityChecksPartialUpdateBodyConfidenceMax).nullish().describe("AI author's confidence in the check, 0-1."),reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),})- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')+ .describe(+ 'A check as it reads back, and everything an edit may change about it.\n\nThe subject is not one of those: it is writable only on ``DataQualityCheckCreate``.'+ )/**- * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.+ * Change how often this subject's checks run, or stop running them automatically. Name the subject with subject_type and subject_uuid in the body.*/-export const warehouseTablesChecksCreateBodyNameOneMax = 128--export const warehouseTablesChecksCreateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseTablesChecksCreateBodyNameTwoMax = 0--export const warehouseTablesChecksCreateBodyColumnNameMax = 400--export const warehouseTablesChecksCreateBodyAiModelMax = 128--export const warehouseTablesChecksCreateBodyConfidenceMin = 0-export const warehouseTablesChecksCreateBodyConfidenceMax = 1--export const WarehouseTablesChecksCreateBody = /* @__PURE__ */ zod+export const DataQualityChecksSchedulePartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod- .union([- zod- .string()- .max(warehouseTablesChecksCreateBodyNameOneMax)- .regex(warehouseTablesChecksCreateBodyNameOneRegExp),- zod.string().max(warehouseTablesChecksCreateBodyNameTwoMax),- ])+ subject_type: zod+ .enum(['table', 'view', 'metric'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric').optional()- .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),- description: zod.string().optional().describe('Why this check exists and what a failure means.'),- column_name: zod- .string()- .max(warehouseTablesChecksCreateBodyColumnNameMax)- .optional()- .describe('Column the check applies to. Omit for table-scoped types like row_count.'),- check_type: zod- .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])- .describe(- '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- ).describe(- 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'+ "Kind of catalog object: 'table', 'view', or 'metric'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric"),- config: zod- .record(zod.string(), zod.unknown())- .optional()- .describe("Type-specific configuration, validated against the check type's JSON schema."),- severity: zod- .enum(['error', 'warn'])- .describe('\* `error` - error\n\* `warn` - warn')- .optional()- .describe(- "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"- ),- enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),- tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),- created_source: zod- .enum(['user', 'ai_generated'])- .describe('\* `user` - user\n\* `ai_generated` - ai_generated')- .optional()+ subject_uuid: zod.uuid().optional().describe('Id of the table, view, or metric.'),+ interval: zod+ .enum(['1hour', '6hour', '12hour', '24hour', '7day']).describe(- "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"- ),- ai_model: zod- .string()- .max(warehouseTablesChecksCreateBodyAiModelMax)- .optional()- .describe('Model that generated the check, if AI-authored.'),- confidence: zod- .number()- .min(warehouseTablesChecksCreateBodyConfidenceMin)- .max(warehouseTablesChecksCreateBodyConfidenceMax)- .nullish()- .describe("AI author's confidence in the check, 0-1."),- reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),- })- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')--/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.- */-export const warehouseTablesChecksUpdateBodyNameOneMax = 128--export const warehouseTablesChecksUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseTablesChecksUpdateBodyNameTwoMax = 0--export const warehouseTablesChecksUpdateBodyColumnNameMax = 400--export const warehouseTablesChecksUpdateBodyAiModelMax = 128--export const warehouseTablesChecksUpdateBodyConfidenceMin = 0-export const warehouseTablesChecksUpdateBodyConfidenceMax = 1--export const WarehouseTablesChecksUpdateBody = /* @__PURE__ */ zod- .object({- name: zod- .union([- zod- .string()- .max(warehouseTablesChecksUpdateBodyNameOneMax)- .regex(warehouseTablesChecksUpdateBodyNameOneRegExp),- zod.string().max(warehouseTablesChecksUpdateBodyNameTwoMax),- ])- .optional()- .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),- description: zod.string().optional().describe('Why this check exists and what a failure means.'),- column_name: zod- .string()- .max(warehouseTablesChecksUpdateBodyColumnNameMax)- .optional()- .describe('Column the check applies to. Omit for table-scoped types like row_count.'),- check_type: zod- .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])- .describe(- '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'+ '\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day')- .describe(- 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- ),- config: zod- .record(zod.string(), zod.unknown())- .optional()- .describe("Type-specific configuration, validated against the check type's JSON schema."),- severity: zod- .enum(['error', 'warn'])- .describe('\* `error` - error\n\* `warn` - warn')- .optional()- .describe(- "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"- ),- enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),- tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),- created_source: zod- .enum(['user', 'ai_generated'])- .describe('\* `user` - user\n\* `ai_generated` - ai_generated').optional().describe(- "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"+ 'How often all enabled checks on the subject run.\n\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day'),- ai_model: zod- .string()- .max(warehouseTablesChecksUpdateBodyAiModelMax)- .optional()- .describe('Model that generated the check, if AI-authored.'),- confidence: zod- .number()- .min(warehouseTablesChecksUpdateBodyConfidenceMin)- .max(warehouseTablesChecksUpdateBodyConfidenceMax)- .nullish()- .describe("AI author's confidence in the check, 0-1."),- reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+ enabled: zod.boolean().optional().describe('Whether checks run automatically on this schedule.'),})- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')+ .describe("Which subject's schedule to change, and what to change about it.")/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.+ * Run checks now: the ones named by check_ids, every enabled check on the subject named by subject_type and subject_uuid, or every enabled check in the project when neither is given. Returns the suite run to poll for the report.*/-export const warehouseTablesChecksPartialUpdateBodyNameOneMax = 128--export const warehouseTablesChecksPartialUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseTablesChecksPartialUpdateBodyNameTwoMax = 0--export const warehouseTablesChecksPartialUpdateBodyColumnNameMax = 400--export const warehouseTablesChecksPartialUpdateBodyAiModelMax = 128--export const warehouseTablesChecksPartialUpdateBodyConfidenceMin = 0-export const warehouseTablesChecksPartialUpdateBodyConfidenceMax = 1--export const WarehouseTablesChecksPartialUpdateBody = /* @__PURE__ */ zod+export const DataQualityRunsCreateBody = /* @__PURE__ */ zod.object({- name: zod- .union([- zod- .string()- .max(warehouseTablesChecksPartialUpdateBodyNameOneMax)- .regex(warehouseTablesChecksPartialUpdateBodyNameOneRegExp),- zod.string().max(warehouseTablesChecksPartialUpdateBodyNameTwoMax),- ])- .optional()- .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),- description: zod.string().optional().describe('Why this check exists and what a failure means.'),- column_name: zod- .string()- .max(warehouseTablesChecksPartialUpdateBodyColumnNameMax)- .optional()- .describe('Column the check applies to. Omit for table-scoped types like row_count.'),- check_type: zod- .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])- .describe(- '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- )- .optional()- .describe(- 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- ),- config: zod- .record(zod.string(), zod.unknown())- .optional()- .describe("Type-specific configuration, validated against the check type's JSON schema."),- severity: zod- .enum(['error', 'warn'])- .describe('\* `error` - error\n\* `warn` - warn')+ check_ids: zod+ .array(zod.uuid()).optional()- .describe(- "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"- ),- enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),- tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),- created_source: zod- .enum(['user', 'ai_generated'])- .describe('\* `user` - user\n\* `ai_generated` - ai_generated')+ .describe('Ids of the checks to run. Omit to run every enabled check in the project.'),+ subject_type: zod+ .enum(['table', 'view', 'metric'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric').optional().describe(- "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"+ 'Narrow the run to one subject. Pass subject_uuid with it. Ignored when check_ids is given.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric'),- ai_model: zod- .string()- .max(warehouseTablesChecksPartialUpdateBodyAiModelMax)+ subject_uuid: zod+ .uuid().optional()- .describe('Model that generated the check, if AI-authored.'),- confidence: zod- .number()- .min(warehouseTablesChecksPartialUpdateBodyConfidenceMin)- .max(warehouseTablesChecksPartialUpdateBodyConfidenceMax)- .nullish()- .describe("AI author's confidence in the check, 0-1."),- reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+ .describe('Id of the subject to run every enabled check on. Pass subject_type with it.'),})- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')+ .describe('What to run in a project-wide suite run.')diff --git a/products/data_quality/frontend/overview/DataQualityOverview.test.tsx b/products/data_quality/frontend/overview/DataQualityOverview.test.tsxindex 0d6c6fe17e05..0827b151eb64 100644--- a/products/data_quality/frontend/overview/DataQualityOverview.test.tsx+++ b/products/data_quality/frontend/overview/DataQualityOverview.test.tsx@@ -11,8 +11,8 @@ import {dataQualityChecksMetricSubjectsList,dataQualityRunsCreate,dataQualityRunsRetrieve,- warehouseSavedQueriesChecksCheckTypesList,- warehouseSavedQueriesChecksRunsList,+ dataQualityChecksCheckTypesList,+ dataQualityChecksRunsList,} from 'products/data_quality/frontend/generated/api'import type { DataQualityOverviewCheckApi } from 'products/data_quality/frontend/generated/api.schemas'@@ -59,15 +59,12 @@ jest.mock('products/data_quality/frontend/generated/api', () => ({dataQualityChecksMetricSubjectsList: jest.fn(),dataQualityRunsCreate: jest.fn(),dataQualityRunsRetrieve: jest.fn(),- warehouseSavedQueriesChecksRunsList: jest.fn(),- warehouseSavedQueriesChecksDestroy: jest.fn(),- warehouseTablesChecksDestroy: jest.fn(),- warehouseSavedQueriesChecksCheckTypesList: jest.fn(),- warehouseTablesChecksCheckTypesList: jest.fn(),- warehouseSavedQueriesChecksCreate: jest.fn(),- warehouseSavedQueriesChecksPartialUpdate: jest.fn(),- warehouseTablesChecksCreate: jest.fn(),- warehouseTablesChecksPartialUpdate: jest.fn(),+ dataQualityChecksRunsList: jest.fn(),+ dataQualityChecksDestroy: jest.fn(),+ dataQualityChecksCheckTypesList: jest.fn(),+ dataQualityChecksCreate: jest.fn(),+ dataQualityChecksPartialUpdate: jest.fn(),+ dataQualityChecksSubjectsList: jest.fn(),}))function buildCheck(@@ -144,7 +141,7 @@ describe('DataQualityOverview', () => {error: '',});(dataQualityRunsRetrieve as jest.Mock).mockResolvedValue({ id: 'suite-1', status: 'running' })- ;(warehouseSavedQueriesChecksRunsList as jest.Mock).mockResolvedValue([+ ;(dataQualityChecksRunsList as jest.Mock).mockResolvedValue([{id: 'run-1',status: 'failed',@@ -156,7 +153,7 @@ describe('DataQualityOverview', () => {started_at: null,},])- ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock).mockResolvedValue([+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockResolvedValue([{ check_type: 'not_null', description: '', requires_column: true, config_schema: {} },])})@@ -281,7 +278,7 @@ describe('DataQualityOverview', () => {})it('shows a retry when the check type catalog cannot load', async () => {- ;(warehouseSavedQueriesChecksCheckTypesList as jest.Mock).mockRejectedValueOnce(new Error('down'))+ ;(dataQualityChecksCheckTypesList as jest.Mock).mockRejectedValueOnce(new Error('down'))await renderOverview()fireEvent.click(queryAll('[data-attr="data-quality-overview-check-actions"]')[0])diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.tsindex 92785682ee2b..408c566105b1 100644--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts@@ -7,13 +7,12 @@ import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'import {- dataCatalogMetricsChecksDestroy,+ dataQualityChecksDestroy,dataQualityChecksHealthList,dataQualityChecksList,+ dataQualityChecksRunsList,dataQualityRunsCreate,dataQualityRunsRetrieve,- warehouseSavedQueriesChecksDestroy,- warehouseSavedQueriesChecksRunsList,} from 'products/data_quality/frontend/generated/api'import type {DataQualityOverviewCheckApi,@@ -41,15 +40,12 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({}))jest.mock('products/data_quality/frontend/generated/api', () => ({- dataCatalogMetricsChecksDestroy: jest.fn(),- dataQualityChecksList: jest.fn(),+ dataQualityChecksDestroy: jest.fn(),dataQualityChecksHealthList: jest.fn(),+ dataQualityChecksList: jest.fn(),+ dataQualityChecksRunsList: jest.fn(),dataQualityRunsCreate: jest.fn(),dataQualityRunsRetrieve: jest.fn(),- warehouseSavedQueriesChecksDestroy: jest.fn(),- warehouseTablesChecksDestroy: jest.fn(),- warehouseSavedQueriesChecksRunsList: jest.fn(),- warehouseTablesChecksRunsList: jest.fn(),}))function buildCheck(@@ -376,33 +372,20 @@ describe('dataQualityOverviewLogic', () => {})it('removes a deleted check and refreshes the snapshot', async () => {- ;(warehouseSavedQueriesChecksDestroy as jest.Mock).mockResolvedValue(undefined)+ ;(dataQualityChecksDestroy as jest.Mock).mockResolvedValue(undefined)await mountLogic()const loadsBeforeDelete = (dataQualityChecksList as jest.Mock).mock.calls.lengthlogic.actions.deleteCheck(buildCheck('check-1', 'orders', 'failed'))await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksDestroy).toHaveBeenCalledWith('1', 'uuid-orders', 'check-1')+ expect(dataQualityChecksDestroy).toHaveBeenCalledWith('1', 'check-1')expect((dataQualityChecksList as jest.Mock).mock.calls.length).toBeGreaterThan(loadsBeforeDelete)expect(lemonToast.success).toHaveBeenCalledWith('Check deleted')})- it('deletes a metric check through its catalog route', async () => {- ;(dataCatalogMetricsChecksDestroy as jest.Mock).mockResolvedValue(undefined)- await mountLogic()-- logic.actions.deleteCheck(- buildCheck('check-1', 'signups', 'failed', { subject_type: 'metric', subject_uuid: 'uuid-signups' })- )- await expectLogic(logic).toFinishAllListeners()-- expect(dataCatalogMetricsChecksDestroy).toHaveBeenCalledWith('1', 'uuid-signups', 'check-1')- expect(lemonToast.success).toHaveBeenCalledWith('Check deleted')- })-it('keeps the row and says so when a delete fails', async () => {- ;(warehouseSavedQueriesChecksDestroy as jest.Mock).mockRejectedValue(new Error('down'))+ ;(dataQualityChecksDestroy as jest.Mock).mockRejectedValue(new Error('down'))await mountLogic()logic.actions.deleteCheck(buildCheck('check-1', 'orders', 'failed'))@@ -414,7 +397,7 @@ describe('dataQualityOverviewLogic', () => {})it('deletes a check once when the confirmation is submitted twice', async () => {- ;(warehouseSavedQueriesChecksDestroy as jest.Mock).mockResolvedValue(undefined)+ ;(dataQualityChecksDestroy as jest.Mock).mockResolvedValue(undefined)await mountLogic()const check = buildCheck('check-1', 'orders', 'failed')@@ -422,7 +405,7 @@ describe('dataQualityOverviewLogic', () => {logic.actions.deleteCheck(check)await expectLogic(logic).toFinishAllListeners()- expect(warehouseSavedQueriesChecksDestroy).toHaveBeenCalledTimes(1)+ expect(dataQualityChecksDestroy).toHaveBeenCalledTimes(1)})it('reloads the rows once the polled run finishes', async () => {@@ -450,18 +433,16 @@ describe('dataQualityOverviewLogic', () => {// A row expanded before the run caches its history; loadOverview refreshes status and// rollups but not those runs, so without a reload the just-finished run is missing until a// collapse and re-expand.- ;(warehouseSavedQueriesChecksRunsList as jest.Mock).mockResolvedValue([{ compiled_query: 'SELECT 1' }])+ ;(dataQualityChecksRunsList as jest.Mock).mockResolvedValue([{ compiled_query: 'SELECT 1' }])await mountLogic()logic.actions.loadCheckRuns(buildCheck('check-1', 'orders', 'failed'))await expectLogic(logic).toFinishAllListeners()- const runsLoadsBeforeFinish = (warehouseSavedQueriesChecksRunsList as jest.Mock).mock.calls.length+ const runsLoadsBeforeFinish = (dataQualityChecksRunsList as jest.Mock).mock.calls.lengthlogic.actions.finishSuiteRun(buildSuiteRun({ status: 'completed', checks_passed: 3 }))await expectLogic(logic).toFinishAllListeners()- expect((warehouseSavedQueriesChecksRunsList as jest.Mock).mock.calls.length).toBeGreaterThan(- runsLoadsBeforeFinish- )+ expect((dataQualityChecksRunsList as jest.Mock).mock.calls.length).toBeGreaterThan(runsLoadsBeforeFinish)})it('stops polling a run that never finishes', async () => {@@ -490,7 +471,7 @@ describe('dataQualityOverviewLogic', () => {],['past runs whose query was cleared', [{ compiled_query: '' }, { compiled_query: 'SELECT 1' }], 'SELECT 1'],])('opens the failing rows of %s', async (_case, runs, expected) => {- ;(warehouseSavedQueriesChecksRunsList as jest.Mock).mockResolvedValue(runs)+ ;(dataQualityChecksRunsList as jest.Mock).mockResolvedValue(runs)await mountLogic()logic.actions.openFailingRows(buildCheck('check-1', 'orders', 'failed'))@@ -504,7 +485,7 @@ describe('dataQualityOverviewLogic', () => {['the check has never run', []],['every run has lost its query to retention', [{ compiled_query: '' }]],])('says why there is nothing to open when %s', async (_case, runs) => {- ;(warehouseSavedQueriesChecksRunsList as jest.Mock).mockResolvedValue(runs)+ ;(dataQualityChecksRunsList as jest.Mock).mockResolvedValue(runs)await mountLogic()logic.actions.openFailingRows(buildCheck('check-1', 'orders', 'failed'))diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.tsindex 05f6dfa92bfc..97252f2e2c7e 100644--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts@@ -5,7 +5,7 @@ import { ApiConfig } from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { urls } from 'scenes/urls'-import { DataQualitySubjectRef, apiErrorDetail, checksApi } from 'products/data_quality/frontend/checksApi'+import { apiErrorDetail, checksApi } from 'products/data_quality/frontend/checksApi'import {dataQualityChecksHealthList,dataQualityChecksList,@@ -71,10 +71,6 @@ export function subjectKeyOf(subjectType: string, subjectUuid: string | null | ureturn `${subjectType}:${subjectUuid ?? ''}`}-function subjectRefOf(check: DataQualityOverviewCheckApi): DataQualitySubjectRef {- return { subjectType: check.subject_type, subjectId: check.subject_uuid ?? '' }-}-/** Where the subject's own page lives, or null when it has none and the name renders as text. */export function subjectDetailUrl(check: DataQualityOverviewCheckApi): string | null {if (check.subject_type === 'metric') {@@ -610,7 +606,7 @@ export const dataQualityOverviewLogic = kea<dataQualityOverviewLogicType>([}actions.setRunsLoading(check.id, true)try {- actions.setCheckRuns(check.id, await checksApi.runs(subjectRefOf(check), check.id))+ actions.setCheckRuns(check.id, await checksApi.runs(check.id))} catch (error) {lemonToast.error(apiErrorDetail(error) ?? 'Could not load the run history. Try again.')} finally {@@ -620,7 +616,7 @@ export const dataQualityOverviewLogic = kea<dataQualityOverviewLogicType>([openFailingRows: async ({ check }) => {await openFailingRowsInSqlEditor({cachedRuns: values.checkRunsByCheckId[check.id],- fetchRuns: () => checksApi.runs(subjectRefOf(check), check.id),+ fetchRuns: () => checksApi.runs(check.id),onRunsFetched: (runs) => actions.setCheckRuns(check.id, runs),})},@@ -640,10 +636,7 @@ export const dataQualityOverviewLogic = kea<dataQualityOverviewLogicType>([}actions.setCheckDeleting(check.id, true)try {- await checksApi.destroy(- { subjectType: check.subject_type, subjectId: check.subject_uuid ?? '' },- check.id- )+ await checksApi.destroy(check.id)actions.removeCheck(check.id)actions.loadOverview()lemonToast.success('Check deleted')diff --git a/products/data_quality/mcp/tools.yaml b/products/data_quality/mcp/tools.yamlindex bab5d7738355..f8ae907de1a2 100644--- a/products/data_quality/mcp/tools.yaml+++ b/products/data_quality/mcp/tools.yaml@@ -9,76 +9,25 @@ feature: data_qualityurl_prefix: /ui_apps: {}tools:- data-catalog-metrics-check-suite-runs-check-runs-list:- operation: data_catalog_metrics_check_suite_runs_check_runs_list- enabled: false- data-catalog-metrics-check-suite-runs-list:- operation: data_catalog_metrics_check_suite_runs_list- enabled: false- data-catalog-metrics-check-suite-runs-retrieve:- operation: data_catalog_metrics_check_suite_runs_retrieve- enabled: false- data-catalog-metrics-checks-check-types-list:- operation: data_catalog_metrics_checks_check_types_list- enabled: false- data-catalog-metrics-checks-create:- operation: data_catalog_metrics_checks_create- enabled: false- data-catalog-metrics-checks-destroy:- operation: data_catalog_metrics_checks_destroy- enabled: false- data-catalog-metrics-checks-health-retrieve:- operation: data_catalog_metrics_checks_health_retrieve- enabled: false- data-catalog-metrics-checks-list:- operation: data_catalog_metrics_checks_list- enabled: false- data-catalog-metrics-checks-output-schema-retrieve:- operation: data_catalog_metrics_checks_output_schema_retrieve- enabled: false- data-catalog-metrics-checks-partial-update:- operation: data_catalog_metrics_checks_partial_update- enabled: false- data-catalog-metrics-checks-retrieve:- operation: data_catalog_metrics_checks_retrieve- enabled: false- data-catalog-metrics-checks-run-all-create:- operation: data_catalog_metrics_checks_run_all_create- enabled: false- data-catalog-metrics-checks-run-create:- operation: data_catalog_metrics_checks_run_create- enabled: false- data-catalog-metrics-checks-runs-list:- operation: data_catalog_metrics_checks_runs_list- enabled: false- data-catalog-metrics-checks-schedule-partial-update:- operation: data_catalog_metrics_checks_schedule_partial_update- enabled: false- data-catalog-metrics-checks-schedule-retrieve:- operation: data_catalog_metrics_checks_schedule_retrieve- enabled: false- data-catalog-metrics-checks-update:- operation: data_catalog_metrics_checks_update- enabled: false- data-quality-check-create-on-table:- operation: warehouse_tables_checks_create+ data-quality-check-create:+ operation: data_quality_checks_createenabled: truescopes:- - warehouse_table:write- query:readannotations:readOnly: falsedestructive: falseidempotent: true- title: Create a data quality check on a table+ title: Create a data quality checkdescription: |- Add a dbt-test-style assertion to a synced warehouse table; the table's id is the table_id- path parameter. 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), 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.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.- Prefer a generic type over custom_sql. Config per type:+ On a table or a view, prefer a generic type over custom_sql. Config per type:- 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@@ -87,182 +36,109 @@ tools:- 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.- Use severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but- not acting on. Checks run automatically after each sync of the table; there is nothing to schedule.- inject_body:- created_source: ai_generated- feature_flag: data-quality-checks- data-quality-check-create-on-view:- operation: warehouse_saved_queries_checks_create- enabled: true- scopes:- - warehouse_view:write- - query:read- annotations:- readOnly: false- destructive: false- idempotent: true- title: Create a data quality check on a view- description: |- Add a dbt-test-style assertion to a saved query (view or materialized view); the view's id is- the saved_query_id path parameter. 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.-- Prefer a generic type over custom_sql. Config per type:- - 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.- - 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.+ 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. Checks run automatically when the view refreshes; there is nothing to schedule.+ 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.inject_body:created_source: ai_generatedfeature_flag: data-quality-checks- data-quality-check-delete-on-table:- operation: warehouse_tables_checks_destroy+ data-quality-check-delete:+ operation: data_quality_checks_destroyenabled: truescopes:- - warehouse_table:write- query:readannotations:readOnly: falsedestructive: trueidempotent: true- title: Delete a data quality check on a table+ title: Delete a data quality checkdescription: >Delete a check. The API soft-deletes it, so its run history stays queryable insystem.information_schema.data_quality_check_runs and past failures can still be dated.feature_flag: data-quality-checks- data-quality-check-delete-on-view:- operation: warehouse_saved_queries_checks_destroy- enabled: true- scopes:- - warehouse_view:write- - query:read- annotations:- readOnly: false- destructive: true- idempotent: true- title: Delete a data quality check on a view- description: >- Delete a check. The API soft-deletes it, so its run history stays queryable in- system.information_schema.data_quality_check_runs and past failures can still be dated.- feature_flag: data-quality-checks- data-quality-check-results-on-table:- operation: warehouse_tables_checks_runs_list- enabled: true- scopes:- - warehouse_table:read- - query:read- annotations:- readOnly: true- destructive: false- idempotent: true- title: Recent results of a data quality check on a table- description: >- The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending- rows — re-run that query to investigate a failure.- feature_flag: data-quality-checks- data-quality-check-results-on-view:- operation: warehouse_saved_queries_checks_runs_list+ data-quality-check-results:+ operation: data_quality_checks_runs_listenabled: truescopes:- - warehouse_view:read- query:readannotations:readOnly: truedestructive: falseidempotent: true- title: Recent results of a data quality check on a view+ title: Recent results of a data quality checkdescription: >The check's newest runs, including the failing-row count and the compiled HogQL that selects the offendingrows — re-run that query to investigate a failure.feature_flag: data-quality-checks- data-quality-check-run-on-table:- operation: warehouse_tables_checks_run_create+ data-quality-check-run:+ operation: data_quality_checks_run_createenabled: truescopes:- - warehouse_table:write- query:readannotations:readOnly: falsedestructive: falseidempotent: false- title: Run a data quality check on a table+ title: Run a data quality checkdescription: >Run one check now. Returns a suite run to poll; read the outcome fromsystem.information_schema.data_quality_check_runs once it finishes.feature_flag: data-quality-checks- data-quality-check-run-on-view:- operation: warehouse_saved_queries_checks_run_create+ data-quality-check-schedule:+ operation: data_quality_checks_schedule_partial_updateenabled: truescopes:- - warehouse_view:write- query:readannotations:readOnly: falsedestructive: false- idempotent: false- title: Run a data quality check on a view+ idempotent: true+ title: Change when a metric's data quality checks rundescription: >- Run one check now. Returns a suite run to poll; read the outcome from- system.information_schema.data_quality_check_runs once it finishes.+ Set how often every enabled check on a metric runs, or stop running them automatically. Name the subject+ with subject_type 'metric' and subject_uuid. Only a metric runs its checks on a schedule: a table's checks+ run after each sync of it, and a view's when the view refreshes, so naming either one is rejected. A metric+ gets a schedule when it takes its first check, so this fails with a 404 until then.+ param_overrides:+ subject_type:+ required: true+ subject_uuid:+ required: truefeature_flag: data-quality-checksdata-quality-check-types:- operation: warehouse_saved_queries_checks_check_types_list+ operation: data_quality_checks_check_types_listenabled: truescopes:- - warehouse_view:read+ - query:readannotations:readOnly: truedestructive: falseidempotent: truetitle: List data quality check typesdescription: >- The check types this project can author, each with the JSON schema its config is validated against. Static- catalog — the saved_query_id path parameter can be any view's id.+ The check types this project can author, each with the JSON schema its config is validated against. Pass+ subject_type to see only the types that kind of subject supports.feature_flag: data-quality-checks- data-quality-check-update-on-table:- operation: warehouse_tables_checks_partial_update+ data-quality-check-update:+ operation: data_quality_checks_partial_updateenabled: truescopes:- - warehouse_table:write- query:readannotations:readOnly: falsedestructive: falseidempotent: true- title: Update a data quality check on a table+ title: Update a data quality checkdescription: >Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it- asserts (check_type, column_name, config). The table it audits is fixed. The check keeps its id, run- history, latest status, and latest run time. A definition or name another active check already holds comes- back as a field error, with nothing written. Deleted checks release their definition, so it can be authored- again as a new check.- feature_flag: data-quality-checks- data-quality-check-update-on-view:- operation: warehouse_saved_queries_checks_partial_update- enabled: true- scopes:- - warehouse_view:write- - query:read- annotations:- readOnly: false- destructive: false- idempotent: true- title: Update a data quality check on a view- description: >- Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it- asserts (check_type, column_name, config). The view it audits is fixed. The check keeps its id, run history,- latest status, and latest run time. A definition or name another active check already holds comes back as a- field error, with nothing written. Deleted checks release their definition, so it can be authored again as a- new check.+ asserts (check_type, column_name, config). The subject it audits is fixed, so subject_type and subject_uuid+ are ignored here. The check keeps its id, run history, latest status, and latest run time. A definition or+ name another active check already holds comes back as a field error, with nothing written. Deleted checks+ release their definition, so it can be authored again as a new check.feature_flag: data-quality-checksdata-quality-checks-health-list:operation: data_quality_checks_health_list@@ -273,6 +149,21 @@ tools:data-quality-checks-metric-subjects-list:operation: data_quality_checks_metric_subjects_listenabled: false+ data-quality-checks-output-schema-retrieve:+ operation: data_quality_checks_output_schema_retrieve+ enabled: false+ data-quality-checks-retrieve:+ operation: data_quality_checks_retrieve+ enabled: false+ data-quality-checks-schedule-retrieve:+ operation: data_quality_checks_schedule_retrieve+ enabled: false+ data-quality-checks-update:+ operation: data_quality_checks_update+ enabled: false+ data-quality-runs-check-runs-list:+ operation: data_quality_runs_check_runs_list+ enabled: falsedata-quality-runs-create:operation: data_quality_runs_createenabled: false@@ -282,54 +173,18 @@ tools:data-quality-runs-retrieve:operation: data_quality_runs_retrieveenabled: false- warehouse-saved-queries-check-suite-runs-check-runs-list:- operation: warehouse_saved_queries_check_suite_runs_check_runs_list- enabled: false- warehouse-saved-queries-check-suite-runs-list:- operation: warehouse_saved_queries_check_suite_runs_list- enabled: false- warehouse-saved-queries-check-suite-runs-retrieve:- operation: warehouse_saved_queries_check_suite_runs_retrieve- enabled: false- warehouse-saved-queries-checks-health-retrieve:- operation: warehouse_saved_queries_checks_health_retrieve- enabled: false- warehouse-saved-queries-checks-list:- operation: warehouse_saved_queries_checks_list- enabled: false- warehouse-saved-queries-checks-retrieve:- operation: warehouse_saved_queries_checks_retrieve- enabled: false- warehouse-saved-queries-checks-run-all-create:- operation: warehouse_saved_queries_checks_run_all_create- enabled: false- warehouse-saved-queries-checks-update:- operation: warehouse_saved_queries_checks_update- enabled: false- warehouse-tables-check-suite-runs-check-runs-list:- operation: warehouse_tables_check_suite_runs_check_runs_list- enabled: false- warehouse-tables-check-suite-runs-list:- operation: warehouse_tables_check_suite_runs_list- enabled: false- warehouse-tables-check-suite-runs-retrieve:- operation: warehouse_tables_check_suite_runs_retrieve- enabled: false- warehouse-tables-checks-check-types-list:- operation: warehouse_tables_checks_check_types_list- enabled: false- warehouse-tables-checks-health-retrieve:- operation: warehouse_tables_checks_health_retrieve- enabled: false- warehouse-tables-checks-list:- operation: warehouse_tables_checks_list- enabled: false- warehouse-tables-checks-retrieve:- operation: warehouse_tables_checks_retrieve- enabled: false- warehouse-tables-checks-run-all-create:- operation: warehouse_tables_checks_run_all_create- enabled: false- warehouse-tables-checks-update:- operation: warehouse_tables_checks_update- enabled: false+ data-quality-subjects:+ operation: data_quality_checks_subjects_list+ enabled: true+ scopes:+ - query:read+ annotations:+ readOnly: true+ destructive: false+ 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.+ feature_flag: data-quality-checksdiff --git a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md b/products/data_quality/skills/authoring-data-quality-checks/SKILL.mdindex b010313bb249..c8b9223f3a99 100644--- a/products/data_quality/skills/authoring-data-quality-checks/SKILL.md+++ b/products/data_quality/skills/authoring-data-quality-checks/SKILL.md@@ -70,8 +70,11 @@ Reach for these first, in roughly this order:Call `posthog:data-quality-check-types` for each type's exact config schema rather than guessing.-Checks live on the subject they audit: create them with `data-quality-check-create-on-view`-(`saved_query_id` path parameter) or `data-quality-check-create-on-table` (`table_id`).+One tool set covers every kind of subject. Call `posthog:data-quality-subjects` for the tables,+views and metrics you can read, then pass the `subject_type` and `id` it gives you as+`subject_type` and `subject_uuid` in `posthog:data-quality-check-create`. Only a subject marked+`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 catalog metrics@@ -92,10 +95,9 @@ through a subquery. Metric check SQL cannot define CTEs, including nested CTEs abindings. CTEs and saved parameters inside the metric definition remain supported. Other placeholdersare not accepted in the check.-Use the metric's Tests tab or the nested REST endpoints under-`/api/projects/{project_id}/data_catalog/metrics/{metric_id}/checks/`. The catalog metric detail-endpoint uses the metric name, but nested check endpoints use its UUID. The metric check-type-endpoint offers only Custom SQL. Do not assume the table/view MCP tools accept metric subjects.+Use the metric's Tests tab, or `posthog:data-quality-check-create` with `subject_type: "metric"`.+The catalog addresses a metric by name, but a check names it by UUID. Pass `subject_type=metric` to+`posthog:data-quality-check-types` and it offers only Custom SQL.Saving validates SQL composition without executing it. Run the check to verify column names andresults. Every run reloads the saved metric: if an edit removes a column used by the check, the next@@ -128,16 +130,15 @@ Disabling or deleting every check preserves the schedule preferences. Deleting tAuthor, run once, read the result. A check nobody has run is a guess.-1. `posthog:data-quality-check-create-on-view` (or `-on-table`)-2. `posthog:data-quality-check-run-on-view` (or `-on-table`) — returns a suite run+1. `posthog:data-quality-check-create`+2. `posthog:data-quality-check-run` — returns a suite run3. Poll `system.information_schema.data_quality_check_runs` (or- `posthog:data-quality-check-results-on-view`/`-on-table`) for the outcome+ `posthog:data-quality-check-results`) for the outcomeA `failed` result on the first run is the interesting case: either you found real bad data, or theassertion is wrong. Take the `compiled_query` off the run, execute it with `posthog:execute-sql`, andlook at what it actually matched before reporting anything. That `compiled_query` comes from-`posthog:data-quality-check-results-on-view`/`-on-table`; the information_schema poll in step 3 does-not return it. An `errored` result is never a data+`posthog:data-quality-check-results`; the information_schema poll in step 3 does not return it. An `errored` result is never a dataproblem — the query could not run at all, usually a column name typo or a subject that no longerexists.diff --git a/products/data_warehouse/backend/routes.py b/products/data_warehouse/backend/routes.pyindex cbd856f09234..af397c9bf25d 100644--- a/products/data_warehouse/backend/routes.py+++ b/products/data_warehouse/backend/routes.py@@ -1,7 +1,6 @@from posthog.api.routing import RouterRegistryimport products.data_warehouse.backend.presentation.views.fix_hogql as fix_hogql-from products.data_quality.backend.presentation import views as data_quality_viewsfrom products.data_warehouse.backend.presentation.views import (column_annotation,data_modeling_job,@@ -21,48 +20,19 @@ from products.data_warehouse.backend.presentation.views.saved_query import (def register_routes(routers: RouterRegistry) -> None:- tables_router = routers.projects.register(- r"warehouse_tables", table.TableViewSet, "project_warehouse_tables", ["team_id"]- )+ routers.projects.register(r"warehouse_tables", table.TableViewSet, "project_warehouse_tables", ["team_id"])routers.projects.register(r"warehouse_saved_query_folders",saved_query_folders.DataWarehouseSavedQueryFolderViewSet,"project_warehouse_saved_query_folders",["team_id"],)- saved_queries_router = routers.projects.register(+ routers.projects.register(r"warehouse_saved_queries",saved_query_viewset.DataWarehouseSavedQueryViewSet,"project_warehouse_saved_queries",["team_id"],)- # Data quality checks hang off the subjects they audit, the way run/materialize/resume do.- # The viewsets are owned by the data_quality product; this product owns the sub-route- # (dashboards -> sharing precedent).- saved_queries_router.register(- r"checks",- data_quality_views.SavedQueryCheckViewSet,- "project_warehouse_saved_query_checks",- ["team_id", "saved_query_id"],- )- saved_queries_router.register(- r"check_suite_runs",- data_quality_views.SavedQuerySuiteRunViewSet,- "project_warehouse_saved_query_check_suite_runs",- ["team_id", "saved_query_id"],- )- tables_router.register(- r"checks",- data_quality_views.TableCheckViewSet,- "project_warehouse_table_checks",- ["team_id", "table_id"],- )- tables_router.register(- r"check_suite_runs",- data_quality_views.TableSuiteRunViewSet,- "project_warehouse_table_check_suite_runs",- ["team_id", "table_id"],- )routers.projects.register(r"warehouse_view_links", view_link.ViewLinkViewSet, "project_warehouse_view_links", ["team_id"])diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex 233afbeaf96b..1e1ace76f01c 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -44,7 +44,10 @@ from products.warehouse_sources.backend.models.external_data_job import ()from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema as _ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource as _ExternalDataSource-from products.warehouse_sources.backend.models.table import DataWarehouseTable as _DataWarehouseTable+from products.warehouse_sources.backend.models.table import (+ HIDDEN_COLUMNS,+ DataWarehouseTable as _DataWarehouseTable,+)# Framework-free helper transforms — re-exported as the public helper surface.from products.warehouse_sources.backend.models.util import (@@ -82,6 +85,8 @@ __all__ = ["resolve_object_by_name","direct_access_table_ids","allowed_table_ids",+ "all_queryable_tables",+ "all_queryable_table_columns","list_tables_for_source","list_jobs_for_source","list_column_statistics",@@ -492,6 +497,64 @@ def _resolve_allowed_table_ids()+def all_queryable_tables(team_id: int) -> list[contracts.DataWarehouseTable]:+ """Every table in this team that is still queryable, with its recorded columns. One query."""+ rows = _DataWarehouseTable.raw_objects.queryable().filter(team_id=team_id)+ return [_to_table(table) for table in rows]+++def all_queryable_table_columns(team_id: int, table_ids: Collection[UUID] | None = None) -> dict[UUID, dict[str, str]]:+ """Each queryable table's columns, by id, under the names HogQL exposes and with their ClickHouse types.++ Not the raw column store: a curated source exposes some raw columns under another name+ (Stripe's ``customer`` answers to ``customer_id``) and the internal sync columns under none at+ all, so a caller reading the store directly hands out names a query cannot resolve.++ ``table_ids`` narrows the tables loaded; ``None`` asks about every one, an empty collection+ about none. One query.+ """+ if table_ids is not None and not table_ids:+ return {}+ rows = (+ _DataWarehouseTable.raw_objects.queryable()+ .filter(team_id=team_id)+ .select_related("external_data_source")+ .only(+ "id",+ "name",+ "columns",+ "external_data_source_id",+ "external_data_source__id",+ "external_data_source__prefix",+ )+ )+ if table_ids is not None:+ rows = rows.filter(id__in=list(table_ids))+ return {table.id: _hogql_visible_columns(table) for table in rows}+++def _hogql_visible_columns(table: _DataWarehouseTable) -> dict[str, str]:+ from products.warehouse_sources.backend.models.external_table_definitions import ( # noqa: PLC0415 -- keeps the HogQL ast import off this module's import path+ get_hogql_column_name_mapping,+ )++ # The same raw -> visible mapping DataWarehouseTable.get_user_facing_columns applies, keeping+ # the stored type rather than the cleaned one so a consumer still reads any Nullable() wrapper.+ hogql_by_raw = get_hogql_column_name_mapping(table.table_name_without_prefix())+ return {+ hogql_by_raw.get(name, name): type_+ for name, entry in (table.columns or {}).items()+ if name not in HIDDEN_COLUMNS and (type_ := _clickhouse_column_type(entry)) is not None+ }+++def _clickhouse_column_type(entry: object) -> str | None:+ # A table records either a bare type string (older rows) or a dict keyed "clickhouse".+ if isinstance(entry, dict):+ entry = entry.get("clickhouse")+ return entry if isinstance(entry, str) else None++def list_tables_for_source(source_id: UUID, team_id: int) -> list[contracts.DataWarehouseTable]:qs = _DataWarehouseTable.objects.filter(team_id=team_id, external_data_source_id=source_id).exclude(deleted=True)return [_to_table(t) for t in qs]diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 16902db540fa..ac468a30e2fb 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3123,28 +3123,13 @@"readOnlyHint": true}},- "data-quality-check-create-on-table": {- "description": "Add a dbt-test-style assertion to a synced warehouse table; the table's id is the table_id\npath parameter. 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\nPrefer 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\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. Checks run automatically after each sync of the table; there is nothing to schedule.",+ "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.","category": "Data quality","feature": "data_quality",- "summary": "Create a data quality check on a table",- "title": "Create a data quality check on a table",- "required_scopes": ["warehouse_table:write", "query:read"],- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- },- "feature_flag": "data-quality-checks"- },- "data-quality-check-create-on-view": {- "description": "Add a dbt-test-style assertion to a saved query (view or materialized view); the view's id is\nthe saved_query_id path parameter. 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\nPrefer 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\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. Checks run automatically when the view refreshes; there is nothing to schedule.",- "category": "Data quality",- "feature": "data_quality",- "summary": "Create a data quality check on a view",- "title": "Create a data quality check on a view",- "required_scopes": ["warehouse_view:write", "query:read"],+ "summary": "Create a data quality check",+ "title": "Create a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -3153,28 +3138,13 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-delete-on-table": {+ "data-quality-check-delete": {"description": "Delete a check. The API soft-deletes it, so its run history stays queryable in system.information_schema.data_quality_check_runs and past failures can still be dated.","category": "Data quality","feature": "data_quality",- "summary": "Delete a data quality check on a table",- "title": "Delete a data quality check on a table",- "required_scopes": ["warehouse_table:write", "query:read"],- "annotations": {- "destructiveHint": true,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- },- "feature_flag": "data-quality-checks"- },- "data-quality-check-delete-on-view": {- "description": "Delete a check. The API soft-deletes it, so its run history stays queryable in system.information_schema.data_quality_check_runs and past failures can still be dated.",- "category": "Data quality",- "feature": "data_quality",- "summary": "Delete a data quality check on a view",- "title": "Delete a data quality check on a view",- "required_scopes": ["warehouse_view:write", "query:read"],+ "summary": "Delete a data quality check",+ "title": "Delete a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": true,"idempotentHint": true,@@ -3183,28 +3153,13 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-results-on-table": {+ "data-quality-check-results": {"description": "The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending rows — re-run that query to investigate a failure.","category": "Data quality","feature": "data_quality",- "summary": "Recent results of a data quality check on a table",- "title": "Recent results of a data quality check on a table",- "required_scopes": ["warehouse_table:read", "query:read"],- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- },- "feature_flag": "data-quality-checks"- },- "data-quality-check-results-on-view": {- "description": "The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending rows — re-run that query to investigate a failure.",- "category": "Data quality",- "feature": "data_quality",- "summary": "Recent results of a data quality check on a view",- "title": "Recent results of a data quality check on a view",- "required_scopes": ["warehouse_view:read", "query:read"],+ "summary": "Recent results of a data quality check",+ "title": "Recent results of a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -3213,13 +3168,13 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-run-on-table": {+ "data-quality-check-run": {"description": "Run one check now. Returns a suite run to poll; read the outcome from system.information_schema.data_quality_check_runs once it finishes.","category": "Data quality","feature": "data_quality",- "summary": "Run a data quality check on a table",- "title": "Run a data quality check on a table",- "required_scopes": ["warehouse_table:write", "query:read"],+ "summary": "Run a data quality check",+ "title": "Run a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": false,@@ -3228,28 +3183,28 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-run-on-view": {- "description": "Run one check now. Returns a suite run to poll; read the outcome from system.information_schema.data_quality_check_runs once it finishes.",+ "data-quality-check-schedule": {+ "description": "Set how often every enabled check on a metric runs, or stop running them automatically. Name the subject with subject_type 'metric' and subject_uuid. Only a metric runs its checks on a schedule: a table's checks run after each sync of it, and a view's when the view refreshes, so naming either one is rejected. A metric gets a schedule when it takes its first check, so this fails with a 404 until then.","category": "Data quality","feature": "data_quality",- "summary": "Run a data quality check on a view",- "title": "Run a data quality check on a view",- "required_scopes": ["warehouse_view:write", "query:read"],+ "summary": "Change when a metric's data quality checks run",+ "title": "Change when a metric's data quality checks run",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,- "idempotentHint": false,+ "idempotentHint": true,"openWorldHint": true,"readOnlyHint": false},"feature_flag": "data-quality-checks"},"data-quality-check-types": {- "description": "The check types this project can author, each with the JSON schema its config is validated against. Static catalog — the saved_query_id path parameter can be any view's id.",+ "description": "The check types this project can author, each with the JSON schema its config is validated against. Pass subject_type to see only the types that kind of subject supports.","category": "Data quality","feature": "data_quality","summary": "List data quality check types","title": "List data quality check types",- "required_scopes": ["warehouse_view:read"],+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -3258,13 +3213,13 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-update-on-table": {- "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The table it audits is fixed. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.",+ "data-quality-check-update": {+ "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The subject it audits is fixed, so subject_type and subject_uuid are ignored here. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.","category": "Data quality","feature": "data_quality",- "summary": "Update a data quality check on a table",- "title": "Update a data quality check on a table",- "required_scopes": ["warehouse_table:write", "query:read"],+ "summary": "Update a data quality check",+ "title": "Update a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -3273,18 +3228,18 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-update-on-view": {- "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The view it audits is fixed. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.",+ "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.","category": "Data quality","feature": "data_quality",- "summary": "Update a data quality check on a view",- "title": "Update a data quality check on a view",- "required_scopes": ["warehouse_view:write", "query:read"],+ "summary": "List what a data quality check can be authored on",+ "title": "List what a data quality check can be authored on",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,"openWorldHint": true,- "readOnlyHint": false+ "readOnlyHint": true},"feature_flag": "data-quality-checks"},diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex cc2e79181792..66ed5f81bfc9 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3138,28 +3138,13 @@"readOnlyHint": true}},- "data-quality-check-create-on-table": {- "description": "Add a dbt-test-style assertion to a synced warehouse table; the table's id is the table_id\npath parameter. 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\nPrefer 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\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. Checks run automatically after each sync of the table; there is nothing to schedule.",+ "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.","category": "Data quality","feature": "data_quality",- "summary": "Create a data quality check on a table",- "title": "Create a data quality check on a table",- "required_scopes": ["warehouse_table:write", "query:read"],- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- },- "feature_flag": "data-quality-checks"- },- "data-quality-check-create-on-view": {- "description": "Add a dbt-test-style assertion to a saved query (view or materialized view); the view's id is\nthe saved_query_id path parameter. 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\nPrefer 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\nUse severity 'error' when bad data should block trusting the model, 'warn' when it is worth surfacing but\nnot acting on. Checks run automatically when the view refreshes; there is nothing to schedule.",- "category": "Data quality",- "feature": "data_quality",- "summary": "Create a data quality check on a view",- "title": "Create a data quality check on a view",- "required_scopes": ["warehouse_view:write", "query:read"],+ "summary": "Create a data quality check",+ "title": "Create a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -3168,28 +3153,13 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-delete-on-table": {+ "data-quality-check-delete": {"description": "Delete a check. The API soft-deletes it, so its run history stays queryable in system.information_schema.data_quality_check_runs and past failures can still be dated.","category": "Data quality","feature": "data_quality",- "summary": "Delete a data quality check on a table",- "title": "Delete a data quality check on a table",- "required_scopes": ["warehouse_table:write", "query:read"],- "annotations": {- "destructiveHint": true,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- },- "feature_flag": "data-quality-checks"- },- "data-quality-check-delete-on-view": {- "description": "Delete a check. The API soft-deletes it, so its run history stays queryable in system.information_schema.data_quality_check_runs and past failures can still be dated.",- "category": "Data quality",- "feature": "data_quality",- "summary": "Delete a data quality check on a view",- "title": "Delete a data quality check on a view",- "required_scopes": ["warehouse_view:write", "query:read"],+ "summary": "Delete a data quality check",+ "title": "Delete a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": true,"idempotentHint": true,@@ -3198,28 +3168,13 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-results-on-table": {+ "data-quality-check-results": {"description": "The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending rows — re-run that query to investigate a failure.","category": "Data quality","feature": "data_quality",- "summary": "Recent results of a data quality check on a table",- "title": "Recent results of a data quality check on a table",- "required_scopes": ["warehouse_table:read", "query:read"],- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- },- "feature_flag": "data-quality-checks"- },- "data-quality-check-results-on-view": {- "description": "The check's newest runs, including the failing-row count and the compiled HogQL that selects the offending rows — re-run that query to investigate a failure.",- "category": "Data quality",- "feature": "data_quality",- "summary": "Recent results of a data quality check on a view",- "title": "Recent results of a data quality check on a view",- "required_scopes": ["warehouse_view:read", "query:read"],+ "summary": "Recent results of a data quality check",+ "title": "Recent results of a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -3228,13 +3183,13 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-run-on-table": {+ "data-quality-check-run": {"description": "Run one check now. Returns a suite run to poll; read the outcome from system.information_schema.data_quality_check_runs once it finishes.","category": "Data quality","feature": "data_quality",- "summary": "Run a data quality check on a table",- "title": "Run a data quality check on a table",- "required_scopes": ["warehouse_table:write", "query:read"],+ "summary": "Run a data quality check",+ "title": "Run a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": false,@@ -3243,28 +3198,28 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-run-on-view": {- "description": "Run one check now. Returns a suite run to poll; read the outcome from system.information_schema.data_quality_check_runs once it finishes.",+ "data-quality-check-schedule": {+ "description": "Set how often every enabled check on a metric runs, or stop running them automatically. Name the subject with subject_type 'metric' and subject_uuid. Only a metric runs its checks on a schedule: a table's checks run after each sync of it, and a view's when the view refreshes, so naming either one is rejected. A metric gets a schedule when it takes its first check, so this fails with a 404 until then.","category": "Data quality","feature": "data_quality",- "summary": "Run a data quality check on a view",- "title": "Run a data quality check on a view",- "required_scopes": ["warehouse_view:write", "query:read"],+ "summary": "Change when a metric's data quality checks run",+ "title": "Change when a metric's data quality checks run",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,- "idempotentHint": false,+ "idempotentHint": true,"openWorldHint": true,"readOnlyHint": false},"feature_flag": "data-quality-checks"},"data-quality-check-types": {- "description": "The check types this project can author, each with the JSON schema its config is validated against. Static catalog — the saved_query_id path parameter can be any view's id.",+ "description": "The check types this project can author, each with the JSON schema its config is validated against. Pass subject_type to see only the types that kind of subject supports.","category": "Data quality","feature": "data_quality","summary": "List data quality check types","title": "List data quality check types",- "required_scopes": ["warehouse_view:read"],+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -3273,13 +3228,13 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-update-on-table": {- "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The table it audits is fixed. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.",+ "data-quality-check-update": {+ "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The subject it audits is fixed, so subject_type and subject_uuid are ignored here. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.","category": "Data quality","feature": "data_quality",- "summary": "Update a data quality check on a table",- "title": "Update a data quality check on a table",- "required_scopes": ["warehouse_table:write", "query:read"],+ "summary": "Update a data quality check",+ "title": "Update a data quality check",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,@@ -3288,18 +3243,18 @@},"feature_flag": "data-quality-checks"},- "data-quality-check-update-on-view": {- "description": "Change any part of a check: its presentation (name, description, severity, enabled, tags) and what it asserts (check_type, column_name, config). The view it audits is fixed. The check keeps its id, run history, latest status, and latest run time. A definition or name another active check already holds comes back as a field error, with nothing written. Deleted checks release their definition, so it can be authored again as a new check.",+ "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.","category": "Data quality","feature": "data_quality",- "summary": "Update a data quality check on a view",- "title": "Update a data quality check on a view",- "required_scopes": ["warehouse_view:write", "query:read"],+ "summary": "List what a data quality check can be authored on",+ "title": "List what a data quality check can be authored on",+ "required_scopes": ["query:read"],"annotations": {"destructiveHint": false,"idempotentHint": true,"openWorldHint": true,- "readOnlyHint": false+ "readOnlyHint": true},"feature_flag": "data-quality-checks"},diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 955efed3ab81..cda33409d2f5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -23896,7 +23896,9 @@ export namespace Schemas {} as const;/**- * The subject is implied by the URL (the parent saved query or table), never part of the body.+ * A check as it reads back, and everything an edit may change about it.+ *+ * The subject is not one of those: it is writable only on ``DataQualityCheckCreate``.*/export interface DataQualityCheck {readonly id: string;@@ -23911,7 +23913,7 @@ export namespace Schemas {* * `metric` - metric */readonly subject_type: SubjectTypeEnum;/**- * Id of the table, view, or metric being checked, from the parent resource in the URL.+ * Id of the table, view, or metric being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid: string | null;@@ -23995,6 +23997,108 @@ export namespace Schemas {readonly updated_at: string | null;}+ /**+ * Type-specific configuration, validated against the check type's JSON schema.+ */+ export type DataQualityCheckCreateConfig = { [key: string]: unknown };++ /**+ * The create body, where the subject is named for the only time in a check's life.+ */+ export interface DataQualityCheckCreate {+ readonly id: string;+ /** Optional identifier-safe handle, unique per project. Omit to address the check by id. */+ name?: string;+ /** Why this check exists and what a failure means. */+ description?: string;+ /** Kind of catalog object to check: 'table', 'view', or 'metric'.+ *+ * * `table` - table+ * * `view` - view+ * * `metric` - metric */+ subject_type: SubjectTypeEnum;+ /** Id of the table, view, or metric to check. */+ subject_uuid: string;+ /** Queryable name of the subject, refreshed on every run. */+ readonly subject_name: string;+ /** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */+ readonly subject_status: string;+ /**+ * Column the check applies to. Omit for table-scoped types like row_count.+ * @maxLength 400+ */+ column_name?: string;+ /** Which assertion to make. Determines the shape of config; see /check_types/.+ *+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql */+ check_type: CheckTypeEnum;+ /** Type-specific configuration, validated against the check type's JSON schema. */+ config?: DataQualityCheckCreateConfig;+ /** 'error' failures mark the subject failing and notify; 'warn' failures only surface.+ *+ * * `error` - error+ * * `warn` - warn */+ severity?: DataQualityCheckSeverityEnum;+ /** Disabled checks are never run by any trigger. */+ enabled?: boolean;+ /** Free-form string labels for grouping and filtering. */+ tags?: string[];+ /**+ * Email of the human accountable for this check, or null.+ * @nullable+ */+ readonly owner: string | null;+ /**+ * When the check last executed.+ * @nullable+ */+ readonly last_run_at: string | null;+ /** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */+ readonly last_status: string;+ /**+ * When the check last passed. Read failing_since for how long a failing check has been failing. Null means it has not passed within the run retention window.+ * @nullable+ */+ readonly last_succeeded_at: string | null;+ /**+ * When the current streak of failing runs started, so a failing check can say how long it has been failing. Null when the check is not failing.+ * @nullable+ */+ readonly failing_since: string | null;+ /** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */+ readonly fingerprint: string;+ /** Whether a human ('user') or an agent ('ai_generated') authored this check.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnum;+ /**+ * Model that generated the check, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string;+ /**+ * AI author's confidence in the check, 0-1.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ confidence?: number | null;+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string;+ /** User who first created this check. */+ readonly created_by: UserBasic;+ readonly created_at: string;+ /** @nullable */+ readonly updated_at: string | null;+ }+/*** Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.* @nullable@@ -24187,7 +24291,7 @@ export namespace Schemas {* * `metric` - metric */readonly subject_type: SubjectTypeEnum;/**- * Id of the table, view, or metric being checked, from the parent resource in the URL.+ * Id of the table, view, or metric being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid: string | null;@@ -24297,6 +24401,41 @@ export namespace Schemas {export interface DataQualityRunRequest {/** Ids of the checks to run. Omit to run every enabled check in the project. */check_ids?: string[];+ /** Narrow the run to one subject. Pass subject_uuid with it. Ignored when check_ids is given.+ *+ * * `table` - table+ * * `view` - view+ * * `metric` - metric */+ subject_type?: SubjectTypeEnum;+ /** Id of the subject to run every enabled check on. Pass subject_type with it. */+ subject_uuid?: string;+ }++ /**+ * Column name to ClickHouse type. Empty for a metric, and for a view that has not run yet.+ */+ export type DataQualitySubjectColumns = {[key: string]: string};++ /**+ * One thing a check can be authored on, whatever kind it is.+ */+ export interface DataQualitySubject {+ /** Kind of object: 'table', 'view', or 'metric'. Pass it back as subject_type when creating a check.+ *+ * * `table` - table+ * * `view` - view+ * * `metric` - metric */+ subject_type: SubjectTypeEnum;+ /** Id of the subject. Pass it back as subject_uuid when creating a check. */+ id: string;+ /** Queryable name of the subject. */+ name: string;+ /** Label shown in the data catalog. Blank for tables and views. */+ display_name: 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. */+ editable: boolean;}/**@@ -59425,15 +59564,6 @@ export namespace Schemas {results: DataModelingJob[];}- export interface PaginatedDataQualityCheckList {- count: number;- /** @nullable */- next?: string | null;- /** @nullable */- previous?: string | null;- results: DataQualityCheck[];- }-export interface PaginatedDataQualityOverviewCheckList {count: number;/** @nullable */@@ -67284,7 +67414,9 @@ export namespace Schemas {export type PatchedDataQualityCheckConfig = { [key: string]: unknown };/**- * The subject is implied by the URL (the parent saved query or table), never part of the body.+ * A check as it reads back, and everything an edit may change about it.+ *+ * The subject is not one of those: it is writable only on ``DataQualityCheckCreate``.*/export interface PatchedDataQualityCheck {readonly id?: string;@@ -67299,7 +67431,7 @@ export namespace Schemas {* * `metric` - metric */readonly subject_type?: SubjectTypeEnum;/**- * Id of the table, view, or metric being checked, from the parent resource in the URL.+ * Id of the table, view, or metric being checked. Null once the subject is deleted.* @nullable*/readonly subject_uuid?: string | null;@@ -67383,8 +67515,19 @@ export namespace Schemas {readonly updated_at?: string | null;}+ /**+ * Which subject's schedule to change, and what to change about it.+ */export interface PatchedDataQualityCheckScheduleUpdate {- /** How often all enabled checks on the metric run.+ /** Kind of catalog object: 'table', 'view', or 'metric'.+ *+ * * `table` - table+ * * `view` - view+ * * `metric` - metric */+ subject_type?: SubjectTypeEnum;+ /** Id of the table, view, or metric. */+ subject_uuid?: string;+ /** How often all enabled checks on the subject run.** * `1hour` - 1hour* * `6hour` - 6hour@@ -101988,28 +102131,6 @@ export namespace Schemas {offset?: number;};- export type DataCatalogMetricsCheckSuiteRunsListParams = {- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- };-- export type DataCatalogMetricsChecksListParams = {- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- };-export type DataCatalogMetricsRunCreateParams = {/*** Cache/execution behavior, same semantics as /query/. Omit to serve a fresh cache hit and calculate blocking when stale.@@ -102143,6 +102264,10 @@ export namespace Schemas {};export type DataQualityChecksListParams = {+ /**+ * Only the checks that make this assertion. See /check_types/.+ */+ check_type?: DataQualityChecksListCheckType;/*** Number of results to return per page.*/@@ -102151,8 +102276,114 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Kind of catalog object: 'table', 'view', or 'metric'.+ */+ subject_type?: DataQualityChecksListSubjectType;+ /**+ * Id of the table, view, or metric.+ */+ subject_uuid?: string;};+ export type DataQualityChecksListCheckType = typeof DataQualityChecksListCheckType[keyof typeof DataQualityChecksListCheckType];+++ export const DataQualityChecksListCheckType = {+ AcceptedValues: 'accepted_values',+ CustomSql: 'custom_sql',+ Freshness: 'freshness',+ NotNull: 'not_null',+ Relationships: 'relationships',+ RowCount: 'row_count',+ Unique: 'unique',+ } as const;++ export type DataQualityChecksListSubjectType = typeof DataQualityChecksListSubjectType[keyof typeof DataQualityChecksListSubjectType];+++ export const DataQualityChecksListSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+ } as const;++ export type DataQualityChecksCheckTypesListParams = {+ /**+ * Kind of catalog object: 'table', 'view', or 'metric'.+ */+ subject_type?: DataQualityChecksCheckTypesListSubjectType;+ };++ export type DataQualityChecksCheckTypesListSubjectType = typeof DataQualityChecksCheckTypesListSubjectType[keyof typeof DataQualityChecksCheckTypesListSubjectType];+++ export const DataQualityChecksCheckTypesListSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+ } as const;++ export type DataQualityChecksHealthListParams = {+ /**+ * Kind of catalog object: 'table', 'view', or 'metric'.+ */+ subject_type?: DataQualityChecksHealthListSubjectType;+ /**+ * Id of the table, view, or metric.+ */+ subject_uuid?: string;+ };++ export type DataQualityChecksHealthListSubjectType = typeof DataQualityChecksHealthListSubjectType[keyof typeof DataQualityChecksHealthListSubjectType];+++ export const DataQualityChecksHealthListSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+ } as const;++ export type DataQualityChecksOutputSchemaRetrieveParams = {+ /**+ * Kind of catalog object: 'table', 'view', or 'metric'.+ */+ subject_type?: DataQualityChecksOutputSchemaRetrieveSubjectType;+ /**+ * Id of the table, view, or metric.+ */+ subject_uuid?: string;+ };++ export type DataQualityChecksOutputSchemaRetrieveSubjectType = typeof DataQualityChecksOutputSchemaRetrieveSubjectType[keyof typeof DataQualityChecksOutputSchemaRetrieveSubjectType];+++ export const DataQualityChecksOutputSchemaRetrieveSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+ } as const;++ export type DataQualityChecksScheduleRetrieveParams = {+ /**+ * Kind of catalog object: 'table', 'view', or 'metric'.+ */+ subject_type?: DataQualityChecksScheduleRetrieveSubjectType;+ /**+ * Id of the table, view, or metric.+ */+ subject_uuid?: string;+ };++ export type DataQualityChecksScheduleRetrieveSubjectType = typeof DataQualityChecksScheduleRetrieveSubjectType[keyof typeof DataQualityChecksScheduleRetrieveSubjectType];+++ export const DataQualityChecksScheduleRetrieveSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+ } as const;+export type DataQualityRunsListParams = {/*** Number of results to return per page.@@ -102162,8 +102393,25 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Kind of catalog object: 'table', 'view', or 'metric'.+ */+ subject_type?: DataQualityRunsListSubjectType;+ /**+ * Id of the table, view, or metric.+ */+ subject_uuid?: string;};+ export type DataQualityRunsListSubjectType = typeof DataQualityRunsListSubjectType[keyof typeof DataQualityRunsListSubjectType];+++ export const DataQualityRunsListSubjectType = {+ Metric: 'metric',+ Table: 'table',+ View: 'view',+ } as const;+export type DataWarehouseCheckDatabaseNameRetrieveParams = {/*** Database name to check@@ -110710,28 +110958,6 @@ export namespace Schemas {search?: string;};- export type WarehouseSavedQueriesCheckSuiteRunsListParams = {- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- };-- export type WarehouseSavedQueriesChecksListParams = {- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- };-export type WarehouseSavedQueryDraftsListParams = {/*** Number of results to return per page.@@ -110758,28 +110984,6 @@ export namespace Schemas {search?: string;};- export type WarehouseTablesCheckSuiteRunsListParams = {- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- };-- export type WarehouseTablesChecksListParams = {- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- };-/*** How the file will be read when the table is created.*/diff --git a/services/mcp/src/generated/data_quality/api.schemas.ts b/services/mcp/src/generated/data_quality/api.schemas.tsindex d5346490d930..cc12d0531a36 100644--- a/services/mcp/src/generated/data_quality/api.schemas.ts+++ b/services/mcp/src/generated/data_quality/api.schemas.ts@@ -3,6 +3,6 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 10 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/diff --git a/services/mcp/src/generated/data_quality/api.ts b/services/mcp/src/generated/data_quality/api.tsindex 8d30ff1b7157..a1c1a378739d 100644--- a/services/mcp/src/generated/data_quality/api.ts+++ b/services/mcp/src/generated/data_quality/api.ts@@ -3,51 +3,54 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 11 enabled ops+ * PostHog API - MCP 8 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'/**- * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.+ * Create a check on the table, view or metric named by subject_type and subject_uuid, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.*/-export const WarehouseSavedQueriesChecksCreateParams = () => zod.object({+export const DataQualityChecksCreateParams = () => zod.object({project_id: zod.string().describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- saved_query_id: zod.string(),})-export const warehouseSavedQueriesChecksCreateBodyNameOneMax = 128+export const dataQualityChecksCreateBodyNameOneMax = 128-export const warehouseSavedQueriesChecksCreateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseSavedQueriesChecksCreateBodyNameTwoMax = 0+export const dataQualityChecksCreateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataQualityChecksCreateBodyNameTwoMax = 0-export const warehouseSavedQueriesChecksCreateBodyColumnNameMax = 400+export const dataQualityChecksCreateBodyColumnNameMax = 400-export const warehouseSavedQueriesChecksCreateBodyAiModelMax = 128+export const dataQualityChecksCreateBodyAiModelMax = 128-export const warehouseSavedQueriesChecksCreateBodyConfidenceMin = 0-export const warehouseSavedQueriesChecksCreateBodyConfidenceMax = 1+export const dataQualityChecksCreateBodyConfidenceMin = 0+export const dataQualityChecksCreateBodyConfidenceMax = 1-export const WarehouseSavedQueriesChecksCreateBody = () => zod+export const DataQualityChecksCreateBody = () => zod.object({name: zod.union([- zod- .string()- .max(warehouseSavedQueriesChecksCreateBodyNameOneMax)- .regex(warehouseSavedQueriesChecksCreateBodyNameOneRegExp),- zod.string().max(warehouseSavedQueriesChecksCreateBodyNameTwoMax),+ zod.string().max(dataQualityChecksCreateBodyNameOneMax).regex(dataQualityChecksCreateBodyNameOneRegExp),+ zod.string().max(dataQualityChecksCreateBodyNameTwoMax),]).optional().describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ subject_type: zod+ .enum(['table', 'view', 'metric'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric')+ .describe(+ "Kind of catalog object to check: 'table', 'view', or 'metric'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric"+ ),+ subject_uuid: zod.string().describe('Id of the table, view, or metric to check.'),column_name: zod.string()- .max(warehouseSavedQueriesChecksCreateBodyColumnNameMax)+ .max(dataQualityChecksCreateBodyColumnNameMax).optional().describe('Column the check applies to. Omit for table-scoped types like row_count.'),check_type: zod@@ -80,60 +83,59 @@ export const WarehouseSavedQueriesChecksCreateBody = () => zod),ai_model: zod.string()- .max(warehouseSavedQueriesChecksCreateBodyAiModelMax)+ .max(dataQualityChecksCreateBodyAiModelMax).optional().describe('Model that generated the check, if AI-authored.'),confidence: zod.number()- .min(warehouseSavedQueriesChecksCreateBodyConfidenceMin)- .max(warehouseSavedQueriesChecksCreateBodyConfidenceMax)+ .min(dataQualityChecksCreateBodyConfidenceMin)+ .max(dataQualityChecksCreateBodyConfidenceMax).nullish().describe("AI author's confidence in the check, 0-1."),reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),})- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')+ .describe("The create body, where the subject is named for the only time in a check's life.")/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.+ * Edit this check in place, including what it asserts (check_type, column_name, config). The subject it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.*/-export const WarehouseSavedQueriesChecksPartialUpdateParams = () => zod.object({+export const DataQualityChecksPartialUpdateParams = () => zod.object({id: zod.string().describe('A UUID string identifying this data quality check.'),project_id: zod.string().describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- saved_query_id: zod.string(),})-export const warehouseSavedQueriesChecksPartialUpdateBodyNameOneMax = 128+export const dataQualityChecksPartialUpdateBodyNameOneMax = 128-export const warehouseSavedQueriesChecksPartialUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseSavedQueriesChecksPartialUpdateBodyNameTwoMax = 0+export const dataQualityChecksPartialUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataQualityChecksPartialUpdateBodyNameTwoMax = 0-export const warehouseSavedQueriesChecksPartialUpdateBodyColumnNameMax = 400+export const dataQualityChecksPartialUpdateBodyColumnNameMax = 400-export const warehouseSavedQueriesChecksPartialUpdateBodyAiModelMax = 128+export const dataQualityChecksPartialUpdateBodyAiModelMax = 128-export const warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMin = 0-export const warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMax = 1+export const dataQualityChecksPartialUpdateBodyConfidenceMin = 0+export const dataQualityChecksPartialUpdateBodyConfidenceMax = 1-export const WarehouseSavedQueriesChecksPartialUpdateBody = () => zod+export const DataQualityChecksPartialUpdateBody = () => zod.object({name: zod.union([zod.string()- .max(warehouseSavedQueriesChecksPartialUpdateBodyNameOneMax)- .regex(warehouseSavedQueriesChecksPartialUpdateBodyNameOneRegExp),- zod.string().max(warehouseSavedQueriesChecksPartialUpdateBodyNameTwoMax),+ .max(dataQualityChecksPartialUpdateBodyNameOneMax)+ .regex(dataQualityChecksPartialUpdateBodyNameOneRegExp),+ zod.string().max(dataQualityChecksPartialUpdateBodyNameTwoMax),]).optional().describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),description: zod.string().optional().describe('Why this check exists and what a failure means.'),column_name: zod.string()- .max(warehouseSavedQueriesChecksPartialUpdateBodyColumnNameMax)+ .max(dataQualityChecksPartialUpdateBodyColumnNameMax).optional().describe('Column the check applies to. Omit for table-scoped types like row_count.'),check_type: zod@@ -167,277 +169,116 @@ export const WarehouseSavedQueriesChecksPartialUpdateBody = () => zod),ai_model: zod.string()- .max(warehouseSavedQueriesChecksPartialUpdateBodyAiModelMax)+ .max(dataQualityChecksPartialUpdateBodyAiModelMax).optional().describe('Model that generated the check, if AI-authored.'),confidence: zod.number()- .min(warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMin)- .max(warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMax)+ .min(dataQualityChecksPartialUpdateBodyConfidenceMin)+ .max(dataQualityChecksPartialUpdateBodyConfidenceMax).nullish().describe("AI author's confidence in the check, 0-1."),reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),})- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')+ .describe(+ 'A check as it reads back, and everything an edit may change about it.\n\nThe subject is not one of those: it is writable only on ``DataQualityCheckCreate``.'+ )/**- * CRUD for one subject's checks, plus the actions that run them and report on them.+ * Every check in the project: authoring, running, results, health, and schedules.*/-export const WarehouseSavedQueriesChecksDestroyParams = () => zod.object({+export const DataQualityChecksDestroyParams = () => zod.object({id: zod.string().describe('A UUID string identifying this data quality check.'),project_id: zod.string().describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- saved_query_id: zod.string(),})/*** Run this check now. Returns the suite run to poll for the report.*/-export const WarehouseSavedQueriesChecksRunCreateParams = () => zod.object({+export const DataQualityChecksRunCreateParams = () => zod.object({id: zod.string().describe('A UUID string identifying this data quality check.'),project_id: zod.string().describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- saved_query_id: zod.string(),})/*** Recent run history for this check, newest first.*/-export const WarehouseSavedQueriesChecksRunsListParams = () => zod.object({+export const DataQualityChecksRunsListParams = () => zod.object({id: zod.string().describe('A UUID string identifying this data quality check.'),project_id: zod.string().describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- saved_query_id: zod.string(),})/**- * The check types this project can author, with the JSON schema of each type's config.+ * The check types this project can author, with the JSON schema of each type's config. Pass subject_type to narrow it to the types that kind of subject supports.*/-export const WarehouseSavedQueriesChecksCheckTypesListParams = () => zod.object({+export const DataQualityChecksCheckTypesListParams = () => zod.object({project_id: zod.string().describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- saved_query_id: zod.string(),})-/**- * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.- */-export const WarehouseTablesChecksCreateParams = () => zod.object({- project_id: zod- .string()- .describe(- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."- ),- table_id: zod.string(),+export const DataQualityChecksCheckTypesListQueryParams = () => zod.object({+ subject_type: zod+ .enum(['metric', 'table', 'view'])+ .optional()+ .describe("Kind of catalog object: 'table', 'view', or 'metric'."),})-export const warehouseTablesChecksCreateBodyNameOneMax = 128--export const warehouseTablesChecksCreateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseTablesChecksCreateBodyNameTwoMax = 0--export const warehouseTablesChecksCreateBodyColumnNameMax = 400--export const warehouseTablesChecksCreateBodyAiModelMax = 128--export const warehouseTablesChecksCreateBodyConfidenceMin = 0-export const warehouseTablesChecksCreateBodyConfidenceMax = 1--export const WarehouseTablesChecksCreateBody = () => zod- .object({- name: zod- .union([- zod- .string()- .max(warehouseTablesChecksCreateBodyNameOneMax)- .regex(warehouseTablesChecksCreateBodyNameOneRegExp),- zod.string().max(warehouseTablesChecksCreateBodyNameTwoMax),- ])- .optional()- .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),- description: zod.string().optional().describe('Why this check exists and what a failure means.'),- column_name: zod- .string()- .max(warehouseTablesChecksCreateBodyColumnNameMax)- .optional()- .describe('Column the check applies to. Omit for table-scoped types like row_count.'),- check_type: zod- .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])- .describe(- '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- )- .describe(- 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- ),- config: zod- .record(zod.string(), zod.unknown())- .optional()- .describe("Type-specific configuration, validated against the check type's JSON schema."),- severity: zod- .enum(['error', 'warn'])- .describe('\* `error` - error\n\* `warn` - warn')- .optional()- .describe(- "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"- ),- enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),- tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),- created_source: zod- .enum(['user', 'ai_generated'])- .describe('\* `user` - user\n\* `ai_generated` - ai_generated')- .optional()- .describe(- "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"- ),- ai_model: zod- .string()- .max(warehouseTablesChecksCreateBodyAiModelMax)- .optional()- .describe('Model that generated the check, if AI-authored.'),- confidence: zod- .number()- .min(warehouseTablesChecksCreateBodyConfidenceMin)- .max(warehouseTablesChecksCreateBodyConfidenceMax)- .nullish()- .describe("AI author's confidence in the check, 0-1."),- reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),- })- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')-/**- * Edit this check in place, including what it asserts (check_type, column_name, config). The table or view it audits is fixed, and the check keeps its id, run history, latest status, and latest run time. A definition or name already held by another active check comes back as a field error, with nothing written.+ * Change how often this subject's checks run, or stop running them automatically. Name the subject with subject_type and subject_uuid in the body.*/-export const WarehouseTablesChecksPartialUpdateParams = () => zod.object({- id: zod.string().describe('A UUID string identifying this data quality check.'),+export const DataQualityChecksSchedulePartialUpdateParams = () => zod.object({project_id: zod.string().describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- table_id: zod.string(),})-export const warehouseTablesChecksPartialUpdateBodyNameOneMax = 128--export const warehouseTablesChecksPartialUpdateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')-export const warehouseTablesChecksPartialUpdateBodyNameTwoMax = 0--export const warehouseTablesChecksPartialUpdateBodyColumnNameMax = 400--export const warehouseTablesChecksPartialUpdateBodyAiModelMax = 128--export const warehouseTablesChecksPartialUpdateBodyConfidenceMin = 0-export const warehouseTablesChecksPartialUpdateBodyConfidenceMax = 1--export const WarehouseTablesChecksPartialUpdateBody = () => zod+export const DataQualityChecksSchedulePartialUpdateBody = () => zod.object({- name: zod- .union([- zod- .string()- .max(warehouseTablesChecksPartialUpdateBodyNameOneMax)- .regex(warehouseTablesChecksPartialUpdateBodyNameOneRegExp),- zod.string().max(warehouseTablesChecksPartialUpdateBodyNameTwoMax),- ])- .optional()- .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),- description: zod.string().optional().describe('Why this check exists and what a failure means.'),- column_name: zod- .string()- .max(warehouseTablesChecksPartialUpdateBodyColumnNameMax)+ subject_type: zod+ .enum(['table', 'view', 'metric'])+ .describe('\* `table` - table\n\* `view` - view\n\* `metric` - metric').optional()- .describe('Column the check applies to. Omit for table-scoped types like row_count.'),- check_type: zod- .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql']).describe(- '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'- )- .optional()- .describe(- 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'+ "Kind of catalog object: 'table', 'view', or 'metric'.\n\n\* `table` - table\n\* `view` - view\n\* `metric` - metric"),- config: zod- .record(zod.string(), zod.unknown())- .optional()- .describe("Type-specific configuration, validated against the check type's JSON schema."),- severity: zod- .enum(['error', 'warn'])- .describe('\* `error` - error\n\* `warn` - warn')- .optional()+ subject_uuid: zod.string().optional().describe('Id of the table, view, or metric.'),+ interval: zod+ .enum(['1hour', '6hour', '12hour', '24hour', '7day']).describe(- "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"- ),- enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),- tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),- created_source: zod- .enum(['user', 'ai_generated'])- .describe('\* `user` - user\n\* `ai_generated` - ai_generated')+ '\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day'+ ).optional().describe(- "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"+ 'How often all enabled checks on the subject run.\n\n\* `1hour` - 1hour\n\* `6hour` - 6hour\n\* `12hour` - 12hour\n\* `24hour` - 24hour\n\* `7day` - 7day'),- ai_model: zod- .string()- .max(warehouseTablesChecksPartialUpdateBodyAiModelMax)- .optional()- .describe('Model that generated the check, if AI-authored.'),- confidence: zod- .number()- .min(warehouseTablesChecksPartialUpdateBodyConfidenceMin)- .max(warehouseTablesChecksPartialUpdateBodyConfidenceMax)- .nullish()- .describe("AI author's confidence in the check, 0-1."),- reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+ enabled: zod.boolean().optional().describe('Whether checks run automatically on this schedule.'),})- .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')+ .describe("Which subject's schedule to change, and what to change about it.")/**- * CRUD for one subject's checks, plus the actions that run them and report on them.+ * Everything in this project you can author a check on, with each subject's columns.*/-export const WarehouseTablesChecksDestroyParams = () => zod.object({- id: zod.string().describe('A UUID string identifying this data quality check.'),- project_id: zod- .string()- .describe(- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."- ),- table_id: zod.string(),-})--/**- * Run this check now. Returns the suite run to poll for the report.- */-export const WarehouseTablesChecksRunCreateParams = () => zod.object({- id: zod.string().describe('A UUID string identifying this data quality check.'),- project_id: zod- .string()- .describe(- "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."- ),- table_id: zod.string(),-})--/**- * Recent run history for this check, newest first.- */-export const WarehouseTablesChecksRunsListParams = () => zod.object({- id: zod.string().describe('A UUID string identifying this data quality check.'),+export const DataQualityChecksSubjectsListParams = () => zod.object({project_id: zod.string().describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."),- table_id: zod.string(),})diff --git a/services/mcp/src/tools/generated/data_quality.ts b/services/mcp/src/tools/generated/data_quality.tsindex 9a37116653fa..06320414db0f 100644--- a/services/mcp/src/tools/generated/data_quality.ts+++ b/services/mcp/src/tools/generated/data_quality.ts@@ -5,19 +5,18 @@ import type { Schemas } from '@/api/generated'import * as orvalSchemas from '@/generated/data_quality/api'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'-const DataQualityCheckCreateOnTableSchema = () => {- const WarehouseTablesChecksCreateBody = orvalSchemas.WarehouseTablesChecksCreateBody()- const WarehouseTablesChecksCreateParams = orvalSchemas.WarehouseTablesChecksCreateParams()- return WarehouseTablesChecksCreateParams.omit({ project_id: true }).extend(WarehouseTablesChecksCreateBody.shape)+const DataQualityCheckCreateSchema = () => {+ const DataQualityChecksCreateBody = orvalSchemas.DataQualityChecksCreateBody()+ return DataQualityChecksCreateBody}-const dataQualityCheckCreateOnTable = (): ToolBase<- ReturnType<typeof DataQualityCheckCreateOnTableSchema>,- Schemas.DataQualityCheck+const dataQualityCheckCreate = (): ToolBase<+ ReturnType<typeof DataQualityCheckCreateSchema>,+ Schemas.DataQualityCheckCreate> => ({- name: 'data-quality-check-create-on-table',- schema: DataQualityCheckCreateOnTableSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckCreateOnTableSchema>>) => {+ name: 'data-quality-check-create',+ schema: DataQualityCheckCreateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckCreateSchema>>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}if (params.name !== undefined) {@@ -26,68 +25,11 @@ const dataQualityCheckCreateOnTable = (): ToolBase<if (params.description !== undefined) {body['description'] = params.description}- if (params.column_name !== undefined) {- body['column_name'] = params.column_name- }- if (params.check_type !== undefined) {- body['check_type'] = params.check_type- }- if (params.config !== undefined) {- body['config'] = params.config- }- if (params.severity !== undefined) {- body['severity'] = params.severity- }- if (params.enabled !== undefined) {- body['enabled'] = params.enabled- }- if (params.tags !== undefined) {- body['tags'] = params.tags- }- if (params.created_source !== undefined) {- body['created_source'] = params.created_source- }- if (params.ai_model !== undefined) {- body['ai_model'] = params.ai_model- }- if (params.confidence !== undefined) {- body['confidence'] = params.confidence- }- if (params.reasoning !== undefined) {- body['reasoning'] = params.reasoning- }- body['created_source'] = 'ai_generated'- const result = await context.api.request<Schemas.DataQualityCheck>({- method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/`,- body,- })- return result- },-})--const DataQualityCheckCreateOnViewSchema = () => {- const WarehouseSavedQueriesChecksCreateBody = orvalSchemas.WarehouseSavedQueriesChecksCreateBody()- const WarehouseSavedQueriesChecksCreateParams = orvalSchemas.WarehouseSavedQueriesChecksCreateParams()- return WarehouseSavedQueriesChecksCreateParams.omit({ project_id: true }).extend(- WarehouseSavedQueriesChecksCreateBody.shape- )-}--const dataQualityCheckCreateOnView = (): ToolBase<- ReturnType<typeof DataQualityCheckCreateOnViewSchema>,- Schemas.DataQualityCheck-> => ({- name: 'data-quality-check-create-on-view',- schema: DataQualityCheckCreateOnViewSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckCreateOnViewSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.name !== undefined) {- body['name'] = params.name+ if (params.subject_type !== undefined) {+ body['subject_type'] = params.subject_type}- if (params.description !== undefined) {- body['description'] = params.description+ if (params.subject_uuid !== undefined) {+ body['subject_uuid'] = params.subject_uuid}if (params.column_name !== undefined) {body['column_name'] = params.column_name@@ -120,142 +62,116 @@ const dataQualityCheckCreateOnView = (): ToolBase<body['reasoning'] = params.reasoning}body['created_source'] = 'ai_generated'- const result = await context.api.request<Schemas.DataQualityCheck>({+ const result = await context.api.request<Schemas.DataQualityCheckCreate>({method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_quality_checks/`,body,})return result},})-const DataQualityCheckDeleteOnTableSchema = () => {- const WarehouseTablesChecksDestroyParams = orvalSchemas.WarehouseTablesChecksDestroyParams()- return WarehouseTablesChecksDestroyParams.omit({ project_id: true })-}--const dataQualityCheckDeleteOnTable = (): ToolBase<- ReturnType<typeof DataQualityCheckDeleteOnTableSchema>,- unknown-> => ({- name: 'data-quality-check-delete-on-table',- schema: DataQualityCheckDeleteOnTableSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckDeleteOnTableSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<unknown>({- method: 'DELETE',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/${encodeURIComponent(String(params.id))}/`,- })- return result- },-})--const DataQualityCheckDeleteOnViewSchema = () => {- const WarehouseSavedQueriesChecksDestroyParams = orvalSchemas.WarehouseSavedQueriesChecksDestroyParams()- return WarehouseSavedQueriesChecksDestroyParams.omit({ project_id: true })+const DataQualityCheckDeleteSchema = () => {+ const DataQualityChecksDestroyParams = orvalSchemas.DataQualityChecksDestroyParams()+ return DataQualityChecksDestroyParams.omit({ project_id: true })}-const dataQualityCheckDeleteOnView = (): ToolBase<ReturnType<typeof DataQualityCheckDeleteOnViewSchema>, unknown> => ({- name: 'data-quality-check-delete-on-view',- schema: DataQualityCheckDeleteOnViewSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckDeleteOnViewSchema>>) => {+const dataQualityCheckDelete = (): ToolBase<ReturnType<typeof DataQualityCheckDeleteSchema>, unknown> => ({+ name: 'data-quality-check-delete',+ schema: DataQualityCheckDeleteSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckDeleteSchema>>) => {const projectId = await context.stateManager.getProjectId()const result = await context.api.request<unknown>({method: 'DELETE',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/${encodeURIComponent(String(params.id))}/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_quality_checks/${encodeURIComponent(String(params.id))}/`,})return result},})-const DataQualityCheckResultsOnTableSchema = () => {- const WarehouseTablesChecksRunsListParams = orvalSchemas.WarehouseTablesChecksRunsListParams()- return WarehouseTablesChecksRunsListParams.omit({ project_id: true })+const DataQualityCheckResultsSchema = () => {+ const DataQualityChecksRunsListParams = orvalSchemas.DataQualityChecksRunsListParams()+ return DataQualityChecksRunsListParams.omit({ project_id: true })}-const dataQualityCheckResultsOnTable = (): ToolBase<- ReturnType<typeof DataQualityCheckResultsOnTableSchema>,+const dataQualityCheckResults = (): ToolBase<+ ReturnType<typeof DataQualityCheckResultsSchema>,Schemas.DataQualityCheckRun[]> => ({- name: 'data-quality-check-results-on-table',- schema: DataQualityCheckResultsOnTableSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckResultsOnTableSchema>>) => {+ name: 'data-quality-check-results',+ schema: DataQualityCheckResultsSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckResultsSchema>>) => {const projectId = await context.stateManager.getProjectId()const result = await context.api.request<Schemas.DataQualityCheckRun[]>({method: 'GET',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/${encodeURIComponent(String(params.id))}/runs/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_quality_checks/${encodeURIComponent(String(params.id))}/runs/`,})return result},})-const DataQualityCheckResultsOnViewSchema = () => {- const WarehouseSavedQueriesChecksRunsListParams = orvalSchemas.WarehouseSavedQueriesChecksRunsListParams()- return WarehouseSavedQueriesChecksRunsListParams.omit({ project_id: true })+const DataQualityCheckRunSchema = () => {+ const DataQualityChecksRunCreateParams = orvalSchemas.DataQualityChecksRunCreateParams()+ return DataQualityChecksRunCreateParams.omit({ project_id: true })}-const dataQualityCheckResultsOnView = (): ToolBase<- ReturnType<typeof DataQualityCheckResultsOnViewSchema>,- Schemas.DataQualityCheckRun[]-> => ({- name: 'data-quality-check-results-on-view',- schema: DataQualityCheckResultsOnViewSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckResultsOnViewSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.DataQualityCheckRun[]>({- method: 'GET',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/${encodeURIComponent(String(params.id))}/runs/`,- })- return result- },-})--const DataQualityCheckRunOnTableSchema = () => {- const WarehouseTablesChecksRunCreateParams = orvalSchemas.WarehouseTablesChecksRunCreateParams()- return WarehouseTablesChecksRunCreateParams.omit({ project_id: true })-}--const dataQualityCheckRunOnTable = (): ToolBase<- ReturnType<typeof DataQualityCheckRunOnTableSchema>,+const dataQualityCheckRun = (): ToolBase<+ ReturnType<typeof DataQualityCheckRunSchema>,Schemas.DataQualitySuiteRun> => ({- name: 'data-quality-check-run-on-table',- schema: DataQualityCheckRunOnTableSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckRunOnTableSchema>>) => {+ name: 'data-quality-check-run',+ schema: DataQualityCheckRunSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckRunSchema>>) => {const projectId = await context.stateManager.getProjectId()const result = await context.api.request<Schemas.DataQualitySuiteRun>({method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/${encodeURIComponent(String(params.id))}/run/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_quality_checks/${encodeURIComponent(String(params.id))}/run/`,})return result},})-const DataQualityCheckRunOnViewSchema = () => {- const WarehouseSavedQueriesChecksRunCreateParams = orvalSchemas.WarehouseSavedQueriesChecksRunCreateParams()- return WarehouseSavedQueriesChecksRunCreateParams.omit({ project_id: true })+const DataQualityCheckScheduleSchema = () => {+ const DataQualityChecksSchedulePartialUpdateBody = orvalSchemas.DataQualityChecksSchedulePartialUpdateBody()+ return DataQualityChecksSchedulePartialUpdateBody.extend({+ subject_type: DataQualityChecksSchedulePartialUpdateBody.shape['subject_type'].unwrap(),+ subject_uuid: DataQualityChecksSchedulePartialUpdateBody.shape['subject_uuid'].unwrap(),+ })}-const dataQualityCheckRunOnView = (): ToolBase<- ReturnType<typeof DataQualityCheckRunOnViewSchema>,- Schemas.DataQualitySuiteRun+const dataQualityCheckSchedule = (): ToolBase<+ ReturnType<typeof DataQualityCheckScheduleSchema>,+ Schemas.DataQualityCheckSchedule> => ({- name: 'data-quality-check-run-on-view',- schema: DataQualityCheckRunOnViewSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckRunOnViewSchema>>) => {+ name: 'data-quality-check-schedule',+ schema: DataQualityCheckScheduleSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckScheduleSchema>>) => {const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.DataQualitySuiteRun>({- method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/${encodeURIComponent(String(params.id))}/run/`,+ const body: Record<string, unknown> = {}+ if (params.subject_type !== undefined) {+ body['subject_type'] = params.subject_type+ }+ if (params.subject_uuid !== undefined) {+ body['subject_uuid'] = params.subject_uuid+ }+ if (params.interval !== undefined) {+ body['interval'] = params.interval+ }+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }+ const result = await context.api.request<Schemas.DataQualityCheckSchedule>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_quality_checks/schedule/`,+ body,})return result},})const DataQualityCheckTypesSchema = () => {- const WarehouseSavedQueriesChecksCheckTypesListParams =- orvalSchemas.WarehouseSavedQueriesChecksCheckTypesListParams()- return WarehouseSavedQueriesChecksCheckTypesListParams.omit({ project_id: true })+ const DataQualityChecksCheckTypesListQueryParams = orvalSchemas.DataQualityChecksCheckTypesListQueryParams()+ return DataQualityChecksCheckTypesListQueryParams}const dataQualityCheckTypes = (): ToolBase<@@ -268,27 +184,30 @@ const dataQualityCheckTypes = (): ToolBase<const projectId = await context.stateManager.getProjectId()const result = await context.api.request<Schemas.DataQualityCheckType[]>({method: 'GET',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/check_types/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_quality_checks/check_types/`,+ query: {+ subject_type: params.subject_type,+ },})return result},})-const DataQualityCheckUpdateOnTableSchema = () => {- const WarehouseTablesChecksPartialUpdateBody = orvalSchemas.WarehouseTablesChecksPartialUpdateBody()- const WarehouseTablesChecksPartialUpdateParams = orvalSchemas.WarehouseTablesChecksPartialUpdateParams()- return WarehouseTablesChecksPartialUpdateParams.omit({ project_id: true }).extend(- WarehouseTablesChecksPartialUpdateBody.shape+const DataQualityCheckUpdateSchema = () => {+ const DataQualityChecksPartialUpdateBody = orvalSchemas.DataQualityChecksPartialUpdateBody()+ const DataQualityChecksPartialUpdateParams = orvalSchemas.DataQualityChecksPartialUpdateParams()+ return DataQualityChecksPartialUpdateParams.omit({ project_id: true }).extend(+ DataQualityChecksPartialUpdateBody.shape)}-const dataQualityCheckUpdateOnTable = (): ToolBase<- ReturnType<typeof DataQualityCheckUpdateOnTableSchema>,+const dataQualityCheckUpdate = (): ToolBase<+ ReturnType<typeof DataQualityCheckUpdateSchema>,Schemas.DataQualityCheck> => ({- name: 'data-quality-check-update-on-table',- schema: DataQualityCheckUpdateOnTableSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckUpdateOnTableSchema>>) => {+ name: 'data-quality-check-update',+ schema: DataQualityCheckUpdateSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckUpdateSchema>>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}if (params.name !== undefined) {@@ -329,85 +248,38 @@ const dataQualityCheckUpdateOnTable = (): ToolBase<}const result = await context.api.request<Schemas.DataQualityCheck>({method: 'PATCH',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_tables/${encodeURIComponent(String(params.table_id))}/checks/${encodeURIComponent(String(params.id))}/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_quality_checks/${encodeURIComponent(String(params.id))}/`,body,})return result},})-const DataQualityCheckUpdateOnViewSchema = () => {- const WarehouseSavedQueriesChecksPartialUpdateBody = orvalSchemas.WarehouseSavedQueriesChecksPartialUpdateBody()- const WarehouseSavedQueriesChecksPartialUpdateParams = orvalSchemas.WarehouseSavedQueriesChecksPartialUpdateParams()- return WarehouseSavedQueriesChecksPartialUpdateParams.omit({ project_id: true }).extend(- WarehouseSavedQueriesChecksPartialUpdateBody.shape- )-}+const DataQualitySubjectsSchema = () => z.object({})-const dataQualityCheckUpdateOnView = (): ToolBase<- ReturnType<typeof DataQualityCheckUpdateOnViewSchema>,- Schemas.DataQualityCheck+const dataQualitySubjects = (): ToolBase<+ ReturnType<typeof DataQualitySubjectsSchema>,+ Schemas.DataQualitySubject[]> => ({- name: 'data-quality-check-update-on-view',- schema: DataQualityCheckUpdateOnViewSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof DataQualityCheckUpdateOnViewSchema>>) => {+ name: 'data-quality-subjects',+ schema: DataQualitySubjectsSchema(),+ handler: async (context: Context, _params: z.infer<ReturnType<typeof DataQualitySubjectsSchema>>) => {const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.name !== undefined) {- body['name'] = params.name- }- if (params.description !== undefined) {- body['description'] = params.description- }- if (params.column_name !== undefined) {- body['column_name'] = params.column_name- }- if (params.check_type !== undefined) {- body['check_type'] = params.check_type- }- if (params.config !== undefined) {- body['config'] = params.config- }- if (params.severity !== undefined) {- body['severity'] = params.severity- }- if (params.enabled !== undefined) {- body['enabled'] = params.enabled- }- if (params.tags !== undefined) {- body['tags'] = params.tags- }- if (params.created_source !== undefined) {- body['created_source'] = params.created_source- }- if (params.ai_model !== undefined) {- body['ai_model'] = params.ai_model- }- if (params.confidence !== undefined) {- body['confidence'] = params.confidence- }- if (params.reasoning !== undefined) {- body['reasoning'] = params.reasoning- }- const result = await context.api.request<Schemas.DataQualityCheck>({- method: 'PATCH',- path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.saved_query_id))}/checks/${encodeURIComponent(String(params.id))}/`,- body,+ const result = await context.api.request<Schemas.DataQualitySubject[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_quality_checks/subjects/`,})return result},})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {- 'data-quality-check-create-on-table': dataQualityCheckCreateOnTable,- 'data-quality-check-create-on-view': dataQualityCheckCreateOnView,- 'data-quality-check-delete-on-table': dataQualityCheckDeleteOnTable,- 'data-quality-check-delete-on-view': dataQualityCheckDeleteOnView,- 'data-quality-check-results-on-table': dataQualityCheckResultsOnTable,- 'data-quality-check-results-on-view': dataQualityCheckResultsOnView,- 'data-quality-check-run-on-table': dataQualityCheckRunOnTable,- 'data-quality-check-run-on-view': dataQualityCheckRunOnView,+ 'data-quality-check-create': dataQualityCheckCreate,+ 'data-quality-check-delete': dataQualityCheckDelete,+ 'data-quality-check-results': dataQualityCheckResults,+ 'data-quality-check-run': dataQualityCheckRun,+ 'data-quality-check-schedule': dataQualityCheckSchedule,'data-quality-check-types': dataQualityCheckTypes,- 'data-quality-check-update-on-table': dataQualityCheckUpdateOnTable,- 'data-quality-check-update-on-view': dataQualityCheckUpdateOnView,+ 'data-quality-check-update': dataQualityCheckUpdate,+ 'data-quality-subjects': dataQualitySubjects,}diff --git a/services/mcp/tests/unit/data-quality-schedule-schema.test.ts b/services/mcp/tests/unit/data-quality-schedule-schema.test.tsnew file mode 100644index 000000000000..187d647670b0--- /dev/null+++ b/services/mcp/tests/unit/data-quality-schedule-schema.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest'++import { getToolByName } from '@/shared/test-utils'+import { GENERATED_TOOLS } from '@/tools/generated/data_quality'++describe('Generated data-quality-check-schedule tool', () => {+ it('requires the subject on the schedule schema (PATCH optionality stripped)', () => {+ const tool = getToolByName(GENERATED_TOOLS, 'data-quality-check-schedule')++ // The endpoint names its subject in the body and rejects a request that omits it, but a+ // PATCH marks every body field optional in OpenAPI — the schema must re-require both so+ // the agent cannot send an interval alone and hit a backend 400.+ expect(() => tool.schema.parse({ interval: '6hour' })).toThrow()+ expect(() => tool.schema.parse({ subject_type: 'metric', interval: '6hour' })).toThrow()+ expect(+ tool.schema.parse({+ subject_type: 'metric',+ subject_uuid: '0199c0de-0000-7000-8000-00000000beef',+ interval: '6hour',+ })+ ).toEqual({+ subject_type: 'metric',+ subject_uuid: '0199c0de-0000-7000-8000-00000000beef',+ interval: '6hour',+ })+ })+})