:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-quality): add manual metric SQL checks (#97570)
Thiago Salvatorec2d9b4324a50
diff --git a/docs/internal/data-quality-checks.md b/docs/internal/data-quality-checks.mdnew file mode 100644index 000000000000..7a069af4ae0d--- /dev/null+++ b/docs/internal/data-quality-checks.md@@ -0,0 +1,49 @@+# Data quality checks++Data quality checks audit warehouse tables, saved views, and catalog metrics. Checks keep their identity and history when their assertion changes.++## 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.++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.++Checks and suites are polymorphic: a catalog-only member can read a teammate's metric checks without warehouse access. Project lists filter by each row's subject. A mixed suite is hidden if any recorded run is unreadable, because aggregate counts would otherwise disclose its outcome.++Restricted callers must have access to both the stored and proposed definitions before PUT or PATCH can save anything, including presentation-only edits. Authorization is repeated if a concurrent edit changes the definition accepted by the transaction. An edit makes three attempts. After three attempts it writes nothing and returns HTTP 400 with the code `concurrent_edit`. An unavailable reference fails closed. An authorized caller can still disable a stale check without revalidating its assertion.++A check that reads more than its own subject executes as a user. A manual run executes as the user who started it, and an automated run executes as the user who last wrote the definition. If neither user is available, the run records an error and executes no SQL.++## Token scopes++All 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` |++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 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.++## Custom SQL++Custom SQL supports direct relations, subqueries, CTEs, and unions. Metric checks bind `{metric}` before enumerating dependencies. Metric checks cannot use CTEs. Query `{metric}` directly or through a subquery. Expandable table expressions whose dependencies cannot be established, including HogQLX sources and table functions, are rejected during authoring and compilation.++Previously saved definitions that cannot be enumerated remain hidden and unrunnable for restricted callers. Execution permissions do not replace the checks that protect definitions, counts, and history.++## History and discovery++A run is authorized using the subject identities recorded when it executed. Editing a check does not authorize its earlier results. Deleted subjects, unreadable recorded references, and missing dependency records on cross-subject checks remain inaccessible. An authorized edit can return the updated check with historical status fields redacted.++The REST endpoints and `information_schema.data_quality_checks`, `information_schema.data_quality_check_runs`, and `information_schema.data_quality_health` share visibility rules. Their query-cache boundary includes catalog, warehouse, and source permissions.++The overview filters readable subject identities in SQL before scanning definition and history visibility. The remaining scan loads only authorization fields in batches of 200 checks, before counting or paginating. Creator and owner records are hydrated for the returned page. Complex-definition evaluation still scales with the candidate checks; pagination is not constant-cost.++Notification recipient checks retain the existing global warehouse-resource policy. A specific object grant alone does not expand notification delivery eligibility. A subject that no longer resolves sends no notification. Background dependency pinning still resolves references individually; batching that cross-product workflow is separate work.++Catalog access is a project permission resource. Notification visibility follows that permission, including after access is revoked.diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.pyindex 5e4c54ffb083..41be89b064d3 100644--- a/posthog/hogql/database/schema/information_schema.py+++ b/posthog/hogql/database/schema/information_schema.py@@ -17,6 +17,7 @@ import jsonimport uuidimport hashlibfrom collections import defaultdict+from collections.abc import Iterablefrom typing import TYPE_CHECKING, Any, NamedTuple, Optionalimport structlog@@ -950,6 +951,21 @@ _RELATIONSHIP_PROPOSALS_DESCRIPTION = ()+class DeniedTableMatcher:+ def __init__(self, denied: Iterable[str]) -> None:+ normalized_names = {name.lower() for name in denied}+ self._denied_names = frozenset(normalized_names | {name.rsplit(".", 1)[-1] for name in normalized_names})++ def matches(self, referenced_table_names: Iterable[str] | None) -> bool:+ if not self._denied_names or referenced_table_names is None:+ return False+ for name in referenced_table_names:+ normalized = name.lower()+ if normalized in self._denied_names or normalized.rsplit(".", 1)[-1] in self._denied_names:+ return True+ return False++def _references_denied_table(referenced_table_names: Optional[list[str]], denied: set[str]) -> bool:"""Whether any of a metric's referenced tables is in the caller's denied set.@@ -961,13 +977,7 @@ def _references_denied_table(referenced_table_names: Optional[list[str]], denied"""if not denied or not referenced_table_names:return False- denied_norm = {name.lower() for name in denied}- denied_norm |= {name.rsplit(".", 1)[-1] for name in denied_norm}- for name in referenced_table_names:- normalized = name.lower()- if normalized in denied_norm or normalized.rsplit(".", 1)[-1] in denied_norm:- return True- return False+ return DeniedTableMatcher(denied).matches(referenced_table_names)def references_denied_table(referenced_table_names: Optional[list[str]], denied: set[str]) -> bool:@@ -1007,7 +1017,7 @@ def _catalog_metrics(context: "HogQLContext", allowed: Optional[frozenset[str]])record_catalog_read("metrics")try:- denied = context.database._denied_tables if context.database is not None else set()+ denied_matcher = DeniedTableMatcher(context.database._denied_tables if context.database is not None else ())queryset = (Metric.objects.for_team(team_id).filter(deleted=False).select_related("owner").order_by("-created_at"))@@ -1017,7 +1027,7 @@ def _catalog_metrics(context: "HogQLContext", allowed: Optional[frozenset[str]])drift = compute_drift(metrics)rows: list[list[Any]] = []for metric in metrics:- if _references_denied_table(metric.referenced_table_names, denied):+ if denied_matcher.matches(metric.referenced_table_names):continuerows.append([@@ -1045,6 +1055,9 @@ def _catalog_metrics(context: "HogQLContext", allowed: Optional[frozenset[str]])return []+_DATA_QUALITY_READ_ATTR = "_data_quality_read_verdict"++def _can_read_data_quality(context: "HogQLContext") -> bool:"""Whether the caller can read warehouse metadata, mirroring the REST viewsets' resource gate.@@ -1052,12 +1065,18 @@ def _can_read_data_quality(context: "HogQLContext") -> bool:reading them is warehouse read access (either resource resolves through warehouse_objects).Fails closed with no access-control context (service tokens, shared links)."""+ from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415+access_control = _access_control(context)if access_control is None:return False- return access_control.check_access_level_for_resource(- "warehouse_view", "viewer"- ) or access_control.check_access_level_for_resource("warehouse_table", "viewer")+ # Resolved once per caller: for a member without resource-level warehouse access this falls+ # through to a scan of every warehouse object, and all three loaders below ask the same question.+ cached = getattr(access_control, _DATA_QUALITY_READ_ATTR, None)+ if cached is None:+ cached = bool(data_quality.authorized_subject_types(access_control, None))+ setattr(access_control, _DATA_QUALITY_READ_ATTR, cached)+ return cacheddef _access_control(context: "HogQLContext") -> Any:@@ -1094,7 +1113,9 @@ def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[stfrom products.data_quality.backend.facade import api as data_quality # noqa: PLC0415denied = context.database._denied_tables if context.database is not None else set()- queryset = DataQualityCheck.objects.for_team(team_id).filter(deleted=False).order_by("-created_at")+ queryset = data_quality.live_subject_checks(+ DataQualityCheck.objects.for_team(team_id).filter(deleted=False)+ ).order_by("-created_at")if allowed is not None:queryset = queryset.filter(name__in=allowed)checks = list(queryset)@@ -1197,7 +1218,9 @@ def _data_quality_health(context: "HogQLContext", allowed: Optional[frozenset[stfrom products.data_quality.backend.facade import api as data_quality # noqa: PLC0415denied = context.database._denied_tables if context.database is not None else set()- checks_qs = DataQualityCheck.objects.for_team(team_id).filter(deleted=False, enabled=True)+ checks_qs = data_quality.live_subject_checks(+ DataQualityCheck.objects.for_team(team_id).filter(deleted=False, enabled=True)+ )if allowed is not None:checks_qs = checks_qs.filter(subject_name__in=allowed)checks = list(checks_qs)@@ -1944,7 +1967,7 @@ class InformationSchemaRelationshipProposalsTable(InformationSchemaTable):class InformationSchemaDataQualityChecksTable(LazyTable):description: str = (- "Data quality checks defined on the project's warehouse tables and views (dbt-test style); one row "+ "Data quality checks defined on the project's warehouse tables, views, and HogQL metrics; one row ""per check. Query this before authoring a check so you extend the existing coverage instead of ""duplicating it. A check passes when its assertion finds zero failing rows; see ""information_schema.data_quality_check_runs for outcomes and data_quality_health for the per-subject "@@ -1953,11 +1976,15 @@ class InformationSchemaDataQualityChecksTable(LazyTable):fields: dict[str, FieldOrTable] = {"id": _string_field("id", description="Stable UUID of the check (pass to the run/update/delete tools)."),"name": _string_field("name", nullable=True, description="Optional handle; NULL when addressed by id."),- "subject_type": _string_field("subject_type", description="'table' (synced source) or 'view' (saved query)."),+ "subject_type": _string_field(+ "subject_type", description="'table' (synced source), 'view' (saved query), or 'metric' (catalog metric)."+ ),"subject_uuid": _string_field(- "subject_uuid", nullable=True, description="UUID of the checked table or view; NULL once hard-deleted."+ "subject_uuid",+ nullable=True,+ description="UUID of the checked table, view, or metric; NULL once hard-deleted.",),- "subject_name": _string_field("subject_name", description="Queryable name of the checked table or view."),+ "subject_name": _string_field("subject_name", description="Name of the checked table, view, or metric."),"subject_status": _string_field("subject_status", description="'active', or 'orphaned' once the subject stops resolving."),@@ -2013,8 +2040,10 @@ class InformationSchemaDataQualityCheckRunsTable(LazyTable):"check_id", nullable=True, description="UUID of the check definition; NULL once it is deleted."),"suite_run_id": _string_field("suite_run_id", description="UUID of the batch this execution belonged to."),- "subject_type": _string_field("subject_type", description="'table' or 'view'."),- "subject_uuid": _string_field("subject_uuid", description="UUID of the checked table or view."),+ "subject_type": _string_field(+ "subject_type", description="'table' (synced source), 'view' (saved query), or 'metric' (catalog metric)."+ ),+ "subject_uuid": _string_field("subject_uuid", description="UUID of the checked table, view, or metric."),"subject_name": _string_field("subject_name", description="Name of the subject at the time of the run."),"check_type": _string_field("check_type", description="Which assertion ran."),"column_name": _string_field("column_name", nullable=True, description="Checked column, when applicable."),@@ -2056,15 +2085,20 @@ class InformationSchemaDataQualityCheckRunsTable(LazyTable):class InformationSchemaDataQualityHealthTable(LazyTable):description: str = (- "One row per warehouse table or view that has data quality checks, rolled up to a single verdict. "- "Check this before trusting a source in an analysis: 'failing' means an error-severity check found bad "- "data, 'erroring' means a check could not run at all, 'warn' means only warn-severity checks failed, "+ "One row per warehouse table, view, or catalog metric that has data quality checks, rolled up to a single "+ "verdict. Check this before trusting a source in an analysis: 'failing' means an error-severity check found "+ "bad data, 'erroring' means a check could not run at all, 'warn' means only warn-severity checks failed, ""'unknown' means nothing has run yet. Subjects with no checks do not appear.")fields: dict[str, FieldOrTable] = {- "subject_type": _string_field("subject_type", description="'table' or 'view'."),- "subject_uuid": _string_field("subject_uuid", description="UUID of the table or view."),- "subject_name": _string_field("subject_name", description="Queryable name of the table or view."),+ "subject_type": _string_field(+ "subject_type", description="'table' (synced source), 'view' (saved query), or 'metric' (catalog metric)."+ ),+ "subject_uuid": _string_field("subject_uuid", description="UUID of the table, view, or metric."),+ "subject_name": _string_field(+ "subject_name",+ description="Name of the table, view, or metric. Only table and view names are queryable in HogQL.",+ ),"health": _string_field("health", description="'failing', 'erroring', 'warn', 'healthy', or 'unknown'. Worst outcome wins."),diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.pyindex 9d4ac0d61804..ac1f8d63eb7a 100644--- a/posthog/hogql/database/schema/test/test_information_schema.py+++ b/posthog/hogql/database/schema/test/test_information_schema.py@@ -12,11 +12,13 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.models import SavedQueryfrom posthog.hogql.database.schema.information_schema import (+ DeniedTableMatcher,_bound_table_names,_certification_key,_classify_table,_pushdown_table_filter,_warehouse_metadata,+ references_denied_table,)from posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_ast@@ -55,6 +57,31 @@ def _in(field: str, values: list[str]) -> ast.CompareOperation:)+class TestDeniedTableMatcher(SimpleTestCase):+ @parameterized.expand(+ [+ ("mixed_case", ["Orders"], ["oRDERS"], True),+ ("qualified_reference", ["Orders"], ["warehouse.ORDERS"], True),+ ("qualified_denial", ["Warehouse.Orders"], ["ORDERS"], True),+ ("shared_leaf", ["warehouse.orders"], ["other.orders"], True),+ ("later_reference", ["orders"], ["customers", "orders"], True),+ ("distinct_leaf", ["warehouse.orders"], ["warehouse.customers"], False),+ ("partial_name", ["orders"], ["archived_orders"], False),+ ("empty_denial", [], ["orders"], False),+ ("empty_references", ["orders"], [], False),+ ("missing_references", ["orders"], None, False),+ ]+ )+ def test_repeated_matches_preserve_existing_denial_rules(+ self, _name: str, denied: list[str], references: list[str] | None, expected: bool+ ) -> None:+ matcher = DeniedTableMatcher(iter(denied))++ assert matcher.matches(references) is expected+ assert matcher.matches(references) is expected+ assert references_denied_table(references, set(denied)) is expected++class TestInformationSchemaPushdown(APIBaseTest):@parameterized.expand([diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.pyindex 1af97749b225..c7386faf92d0 100644--- a/posthog/hogql_queries/access_controlled_resources.py+++ b/posthog/hogql_queries/access_controlled_resources.py@@ -143,6 +143,7 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[str# allowed one's check configs and run counts on a hit. The specific denied object IDs fold# into the key via AnalyticsQueryRunner._get_object_access_restrictions.if table_names & _DATA_QUALITY_INFORMATION_SCHEMA_TABLES:+ scopes.add("data_catalog")scopes.add("warehouse_table")scopes.add("warehouse_view")diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.pyindex 3de1e1ae6726..f5932cfd8eea 100644--- a/posthog/hogql_queries/test/test_access_controlled_resources.py+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py@@ -118,17 +118,17 @@ class TestQueriedAccessControlledResources(BaseTest):("information_schema_data_quality_checks","select config from system.information_schema.data_quality_checks",- {"external_data_source", "warehouse_table", "warehouse_view"},+ {"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},),("information_schema_data_quality_check_runs","select failed_row_count from system.information_schema.data_quality_check_runs",- {"external_data_source", "warehouse_table", "warehouse_view"},+ {"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},),("information_schema_data_quality_health","select health from system.information_schema.data_quality_health",- {"external_data_source", "warehouse_table", "warehouse_view"},+ {"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},),# The plain schema tables expose no catalog-gated data, so they don't partition on it.("information_schema_columns", "select * from system.information_schema.columns", set()),diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 47056480196b..6aa33fbafa3d 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -543,6 +543,7 @@ field_exclusions: dict[AuditableScope, list[str]] = {"subject_name","subject_status",# Subject FKs are immutable after create and not JSON-serializable for the change detail.+ "metric","saved_query","table",],diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.pyindex fdc3fc86fa7b..269accd585ea 100644--- a/products/access_control/backend/facade/user_access_control.py+++ b/products/access_control/backend/facade/user_access_control.py@@ -62,6 +62,7 @@ ACCESS_CONTROL_MAX_OBJECTS_PER_RESOURCE = 1000ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = ("action","customer_analytics",+ "data_catalog","dashboard","early_access_feature","endpoint",@@ -414,14 +415,28 @@ class UserAccessControl:# object in a list response. The events carry no object id, so these repeats are# identical events. Report each distinct divergence once per request.self._reported_resolved_access_divergences: set[tuple] = set()+ # Project-wide object-id resolutions, keyed by (resource, team, level). Each one scans the+ # resource and preloads its access controls, and one request asks for the same set several+ # times over. Narrowed lookups are never stored here, only whole-resource ones.+ self._allowed_object_ids: dict[tuple[str, int, str], frozenset] = {}if not organization_id and team:organization_id = str(team.organization_id)self._organization_id = organization_id+ def allowed_object_ids(+ self, resource: str, team_id: int, required_level: str, resolve: Callable[[], frozenset]+ ) -> frozenset:+ """Memoize one whole-resource object-id resolution for the life of this request."""+ key = (resource, team_id, required_level)+ if key not in self._allowed_object_ids:+ self._allowed_object_ids[key] = resolve()+ return self._allowed_object_ids[key]+def _clear_cache(self):self._cache = {}+ self._allowed_object_ids = {}# Pop from __dict__ rather than hasattr/delattr# hasattr on an un-computed cached_property would re-populate the value we're clearingself.__dict__.pop("_cached_access_controls", None)diff --git a/products/access_control/backend/tests/__snapshots__/test_access_control.ambr b/products/access_control/backend/tests/__snapshots__/test_access_control.ambrindex 7e4aea4b80a8..6afcef36e6c4 100644--- a/products/access_control/backend/tests/__snapshots__/test_access_control.ambr+++ b/products/access_control/backend/tests/__snapshots__/test_access_control.ambr@@ -63,7 +63,6 @@'survey','tagger','ticket',- 'warehouse_objects','warehouse_table','warehouse_view',])diff --git a/products/access_control/backend/tests/test_access_control.py b/products/access_control/backend/tests/test_access_control.pyindex f957fa706dbe..5fd54bf365ea 100644--- a/products/access_control/backend/tests/test_access_control.py+++ b/products/access_control/backend/tests/test_access_control.py@@ -1774,6 +1774,7 @@ class TestAccessControlDefaultsEndpoint(BaseAccessControlTest):assert "dashboard" in data["resource_access_levels"]assert "feature_flag" in data["resource_access_levels"]assert "insight" in data["resource_access_levels"]+ assert "data_catalog" in data["resource_access_levels"]def test_only_returns_current_team_defaults(self):"""Access controls from other teams are not included."""diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.pyindex d860d27d35ea..ce21b294dc8a 100644--- a/products/data_catalog/backend/facade/api.py+++ b/products/data_catalog/backend/facade/api.py@@ -19,7 +19,13 @@ from ..logic.certifications import ()from ..logic.drift import compute_driftfrom ..logic.execution import run_metric-from ..logic.metric_reads import get_metric_summary, live_metric_summaries, metric_names_for_ids, metric_reads_for_ids+from ..logic.metric_reads import (+ get_metric_summary,+ live_metric_ids,+ live_metric_summaries,+ metric_names_for_ids,+ metric_reads_for_ids,+)from ..logic.metrics import (BULK_SKIP_NOT_FOUND,METRIC_BULK_MAX,@@ -66,6 +72,7 @@ __all__ = ["deprecate","get_hogql_metric_definition","get_metric_summary",+ "live_metric_ids","live_metric_summaries","metric_names_for_ids","metrics_for_team",diff --git a/products/data_catalog/backend/logic/metric_reads.py b/products/data_catalog/backend/logic/metric_reads.pyindex 43de584a8610..4ac72f9854a5 100644--- a/products/data_catalog/backend/logic/metric_reads.py+++ b/products/data_catalog/backend/logic/metric_reads.py@@ -53,10 +53,24 @@ def metric_reads_for_ids(team_id: int, metric_ids: Collection[UUID]) -> dict[UUIdef live_metric_summaries(team_id: int) -> list[MetricSummary]:- metrics = Metric.objects.for_team(team_id).filter(deleted=False).order_by("created_at", "id")+ metrics = (+ Metric.objects.for_team(team_id)+ .filter(deleted=False)+ .only("id", "name", "display_name", "definition", "referenced_table_names")+ .order_by("created_at", "id")+ )return [_summary(metric) for metric in metrics]+def live_metric_ids(team_id: int) -> list[UUID]:+ """The ids of this team's metrics that still exist, as one query.++ Reads one column, so a caller that only needs to know which metrics are alive never hydrates a+ definition or the free text beside it.+ """+ return list(Metric.objects.for_team(team_id).filter(deleted=False).values_list("id", flat=True))++def metric_names_for_ids(team_id: int, metric_ids: Collection[UUID]) -> dict[UUID, str]:"""The current name of each of these metrics, as one query. A deleted or missing one is absent.diff --git a/products/data_catalog/backend/routes.py b/products/data_catalog/backend/routes.pyindex 417a7c8fb849..46d4e5231f22 100644--- a/products/data_catalog/backend/routes.py+++ b/products/data_catalog/backend/routes.py@@ -5,10 +5,17 @@ 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:- routers.projects.register(r"data_catalog/metrics", MetricViewSet, "environment_data_catalog_metrics", ["team_id"])+ 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/certifications",CertificationViewSet,diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex d6e2132607ed..150b63790b03 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -30,6 +30,7 @@ _LAZY = {"get_saved_query_ids_for_nodes": "logic.saved_query_reads","get_saved_query_summary": "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","saved_query_materialized_at": "logic.saved_query_freshness","latest_saved_query_materialization_job": "logic.saved_query_freshness",diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.pyindex b52e69e4dbdc..38c81efc83c7 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -1,6 +1,7 @@"""Contract-shaped reads of saved queries for consumers outside this product."""-from collections.abc import Iterable+from collections.abc import Collection, Iterable+from typing import TYPE_CHECKINGfrom uuid import UUIDfrom django.conf import settings@@ -10,6 +11,9 @@ from ..models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom ..models.node import Nodefrom .saved_query_freshness import saved_query_materialized_at+if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl+def _clickhouse_type(entry: object) -> str | None:"""The stored ClickHouse type, reading a current dict entry keyed ``clickhouse`` or a legacy@@ -62,6 +66,49 @@ def all_saved_query_names(team_id: int) -> dict[str, str]:return {str(saved_query_id): name for saved_query_id, name in rows}+def allowed_saved_query_ids(+ team_id: int,+ user_access_control: "UserAccessControl",+ *,+ required_level: "AccessControlLevel" = "viewer",+ ids: Collection[UUID] | None = None,+) -> frozenset[UUID]:+ """The saved queries this caller may reach at ``required_level``.++ ``ids`` narrows the objects loaded before their access controls are read, so a caller asking+ about one view does not pay for the whole project. ``None`` asks about every view; an empty+ collection asks about none.+ """+ if ids is not None and not ids:+ return frozenset()+ if ids is None:+ return user_access_control.allowed_object_ids(+ "warehouse_view",+ team_id,+ required_level,+ lambda: _resolve_allowed_saved_query_ids(team_id, user_access_control, required_level, None),+ )+ return _resolve_allowed_saved_query_ids(team_id, user_access_control, required_level, ids)+++def _resolve_allowed_saved_query_ids(+ team_id: int,+ user_access_control: "UserAccessControl",+ required_level: "AccessControlLevel",+ ids: Collection[UUID] | None,+) -> frozenset[UUID]:+ candidates = DataWarehouseSavedQuery.objects.filter(team_id=team_id).exclude(deleted=True)+ if ids is not None:+ candidates = candidates.filter(id__in=ids)+ saved_queries = list(candidates.only("id", "created_by_id"))+ user_access_control.preload_object_access_controls(list(saved_queries))+ return frozenset(+ saved_query.id+ for saved_query in saved_queries+ if user_access_control.check_access_level_for_object(saved_query, required_level)+ )++def backing_table_ids_by_saved_query(team_id: int) -> dict[UUID, UUID]:"""Private backing table ids mapped to their saved query ids. One query.diff --git a/products/data_modeling/backend/test/test_saved_query_reads.py b/products/data_modeling/backend/test/test_saved_query_reads.pynew file mode 100644index 000000000000..e0c6c52d20e3--- /dev/null+++ b/products/data_modeling/backend/test/test_saved_query_reads.py@@ -0,0 +1,71 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.models import Team+from posthog.models.organization import OrganizationMembership++from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl+from products.access_control.backend.models.access_control import AccessControl+from products.data_modeling.backend.facade import api+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+++class TestSavedQueryReads(BaseTest):+ @parameterized.expand(+ [+ ("legacy_viewer", False, "viewer"),+ ("legacy_editor", False, "editor"),+ ("most_specific_viewer", True, "viewer"),+ ("most_specific_editor", True, "editor"),+ ]+ )+ def test_allowed_saved_query_ids_preserves_object_grants(+ self, _name: str, most_specific: bool, required_level: AccessControlLevel+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.uses_most_specific_access_resolution = most_specific+ self.organization.save(update_fields=["available_product_features", "uses_most_specific_access_resolution"])+ member = self._create_user("[email protected]")+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")+ readable = DataWarehouseSavedQuery.objects.create(team=self.team, name="readable")+ editable = DataWarehouseSavedQuery.objects.create(team=self.team, name="editable")+ ungranted = DataWarehouseSavedQuery.objects.create(team=self.team, name="ungranted")+ owned = DataWarehouseSavedQuery.objects.create(team=self.team, name="owned", created_by=member)+ DataWarehouseSavedQuery.objects.create(team=self.team, name="deleted", deleted=True, created_by=member)+ other_team = Team.objects.create(organization=self.organization, name="other")+ DataWarehouseSavedQuery.objects.create(team=other_team, name="other", created_by=member)+ for saved_query, level in [(readable, "viewer"), (editable, "editor")]:+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_view",+ resource_id=str(saved_query.id),+ organization_member=membership,+ access_level=level,+ )++ access = UserAccessControl(member, team=self.team)+ expected = frozenset({editable.id, owned.id} | ({readable.id} if required_level == "viewer" else set()))+ assert api.allowed_saved_query_ids(self.team.id, access, required_level=required_level) == expected+ with self.assertNumQueries(0):+ assert api.allowed_saved_query_ids(self.team.id, access, required_level=required_level) == expected++ narrowed = api.allowed_saved_query_ids(+ self.team.id, access, required_level=required_level, ids=[owned.id, ungranted.id]+ )+ assert narrowed == frozenset({owned.id})+ with self.assertNumQueries(0):+ assert (+ api.allowed_saved_query_ids(self.team.id, access, required_level=required_level, ids=[]) == frozenset()+ )++ membership.level = OrganizationMembership.Level.ADMIN+ membership.save(update_fields=["level"])+ admin = UserAccessControl(member, team=self.team)+ assert api.allowed_saved_query_ids(self.team.id, admin, required_level=required_level) == frozenset(+ {readable.id, editable.id, ungranted.id, owned.id}+ )diff --git a/products/data_quality/backend/admin.py b/products/data_quality/backend/admin.pyindex 74b5e0faa8f8..ee89058a45ab 100644--- a/products/data_quality/backend/admin.py+++ b/products/data_quality/backend/admin.py@@ -1,19 +1,106 @@+from typing import cast++from django import formsfrom django.contrib import admin+from django.contrib.admin.widgets import ForeignKeyRawIdWidget+from django.core.exceptions import ObjectDoesNotExist, ValidationError+from django.db import models+from django.http import HttpRequest+from django.urls import NoReverseMatch, reverse+from django.utils.text import Truncator++from posthog.models.scoping import team_scope+from posthog.models.scoping.manager import TeamScopedManagerfrom products.data_quality.backend.facade.models import DataQualityCheck, DataQualitySuiteRun+RAW_ID_LABEL_WORD_LIMIT = 14+++class _UnscopedForeignKeyRawIdWidget(ForeignKeyRawIdWidget):+ # nosemgrep: tuple-return-prefer-dataclass -- Django's raw-ID widget requires a (label, URL) tuple.+ def label_and_url_for_value(self, value: object) -> tuple[str, str]:+ manager = cast(TeamScopedManager, self.rel.model._default_manager)+ try:+ related_object = manager.unscoped().using(self.db).get(**{self.rel.get_related_field().name: value})+ except (ValueError, ObjectDoesNotExist, ValidationError):+ return "", ""++ options = related_object._meta+ try:+ url = reverse(+ f"{self.admin_site.name}:{options.app_label}_{options.model_name}_change", args=[related_object.pk]+ )+ except NoReverseMatch:+ url = ""+ return Truncator(related_object).words(RAW_ID_LABEL_WORD_LIMIT), url+++class _DataQualityAdminForm(forms.ModelForm):+ def _post_clean(self) -> None:+ team = self.cleaned_data.get("team")+ if team is None:+ return+ with team_scope(team.id):+ super()._post_clean() # type: ignore[misc]+++# nosemgrep: admin-modeladmin-needs-register-decorator -- Shared base; concrete admins below are registered.+class _DataQualityAdmin(admin.ModelAdmin):+ form = _DataQualityAdminForm++ def save_model(+ self,+ request: HttpRequest,+ obj: DataQualityCheck | DataQualitySuiteRun,+ form: forms.ModelForm,+ change: bool,+ ) -> None:+ with team_scope(obj.team_id):+ super().save_model(request, obj, form, change)++ def get_queryset(self, request: HttpRequest) -> models.QuerySet:+ queryset = cast(TeamScopedManager, self.model._default_manager).unscoped()+ ordering = self.get_ordering(request)+ return queryset.order_by(*ordering) if ordering else queryset++ def formfield_for_foreignkey(+ self, db_field: models.ForeignKey, request: HttpRequest, **kwargs: object+ ) -> forms.ModelChoiceField | None:+ manager = db_field.remote_field.model._default_manager+ if not isinstance(manager, TeamScopedManager):+ return super().formfield_for_foreignkey(db_field, request, **kwargs)++ database = cast(str | None, kwargs.pop("using", None))+ kwargs.setdefault("queryset", manager.unscoped().using(database))+ kwargs.setdefault(+ "widget", _UnscopedForeignKeyRawIdWidget(db_field.remote_field, self.admin_site, using=database)+ )+ return cast(+ forms.ModelChoiceField | None,+ models.Field.formfield(+ db_field,+ form_class=forms.ModelChoiceField,+ choices_form_class=cast(type[forms.ChoiceField] | None, kwargs.pop("choices_form_class", None)),+ to_field_name=db_field.remote_field.field_name,+ limit_choices_to=db_field.remote_field.limit_choices_to,+ blank=db_field.blank,+ **kwargs,+ ),+ )+@admin.register(DataQualityCheck)-class DataQualityCheckAdmin(admin.ModelAdmin):+class DataQualityCheckAdmin(_DataQualityAdmin):list_display = ("id", "check_type", "subject_name", "column_name", "severity", "enabled", "last_status")list_filter = ("check_type", "severity", "enabled", "subject_type", "subject_status")search_fields = ("id", "name", "subject_name", "team__id")- raw_id_fields = ("team", "created_by", "definition_author", "owner", "saved_query", "table")+ raw_id_fields = ("team", "created_by", "definition_author", "owner", "saved_query", "table", "metric")readonly_fields = ("id", "fingerprint", "created_at", "updated_at", "last_run_at", "last_status")@admin.register(DataQualitySuiteRun)-class DataQualitySuiteRunAdmin(admin.ModelAdmin):+class DataQualitySuiteRunAdmin(_DataQualityAdmin):list_display = ("id", "trigger", "status", "checks_passed", "checks_failed", "checks_errored", "created_at")list_filter = ("trigger", "status")search_fields = ("id", "workflow_id", "team__id")diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.pyindex d449b30b46ec..5d76b28d2703 100644--- a/products/data_quality/backend/facade/api.py+++ b/products/data_quality/backend/facade/api.py@@ -12,6 +12,7 @@ from ..logic.checks import (edit_check,empty_check_suite,ensure_name_available,+ live_subject_checks,soft_delete_check,start_check_suite,subject_health,@@ -20,11 +21,12 @@ from ..logic.checks import ()from ..logic.compiler import compile_check, related_subject_reffrom ..logic.config import get_gate_config, set_gate_materialization_on_checks-from ..logic.contracts import CompiledCheck, SubjectRef+from ..logic.contracts import CompiledCheck, SubjectIdentity, SubjectReffrom ..logic.errors import CheckConfigError, CheckEditConflict, SubjectUnresolvableErrorfrom ..logic.health import CheckStatusRow, roll_up_healthfrom ..logic.navigation import SubjectKey, SubjectLocation, subject_locationsfrom ..logic.notifications import notify_materialization_blocked+from ..logic.permissions import authorized_subject_types, restrict_subject_types, writable_subjectsfrom ..logic.registry import UnknownCheckTypeError, list_check_typesfrom ..logic.run_records import record_check_runfrom ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entry@@ -36,13 +38,15 @@ from ..logic.subject_access import (can_be_object_denied,definition_reads_unreadable_subject,denial_context,- denied_subject_names,+ memoized_definition_verdict,+ readable_check_subjects,suites_backing_unreadable_runs_q,unreadable_suites_q,+ visible_check_queryset,visible_checks,without_denied_runs,)-from ..logic.subjects import resolve_subject+from ..logic.subjects import resolve_metric_subjects, resolve_subjectfrom ..logic.triggers import materialization_audit_mode as quality_audit_modefrom .contracts import CheckTypeInfo@@ -56,18 +60,23 @@ __all__ = ["ReadableSubjects","ReferencedSubjects","SubjectKey",+ "SubjectIdentity","SubjectLocation","SubjectRef","SubjectUnresolvableError","UnknownCheckTypeError",+ "authorized_subject_types",+ "restrict_subject_types",+ "live_subject_checks","caller_denial_context","can_be_object_denied","checks_for_subject","compile_check","compute_fingerprint","definition_reads_unreadable_subject",+ "memoized_definition_verdict","denial_context",- "denied_subject_names",+ "readable_check_subjects","edit_check","empty_check_suite","ensure_name_available",@@ -79,6 +88,7 @@ __all__ = ["record_check_run","related_subject_ref","resolve_subject",+ "resolve_metric_subjects","roll_up_health","set_gate_materialization_on_checks","soft_delete_check",@@ -91,5 +101,7 @@ __all__ = ["upsert_check","validate_check","visible_checks",+ "visible_check_queryset","without_denied_runs",+ "writable_subjects",]diff --git a/products/data_quality/backend/facade/contracts.py b/products/data_quality/backend/facade/contracts.pyindex 69eb52244c9f..4023c5f651f7 100644--- a/products/data_quality/backend/facade/contracts.py+++ b/products/data_quality/backend/facade/contracts.py@@ -8,6 +8,7 @@ from dataclasses import dataclass, fieldfrom typing import Any, Literal, TypeGuardCHECK_SUITE_WORKFLOW_NAME = "data-quality-run-suite"+DISPATCH_SCHEDULED_SUITES_WORKFLOW_NAME = "data-quality-dispatch-scheduled-suites"MATERIALIZATION_GATE_ACTIVITY_NAME = "data-quality-materialization-gate"diff --git a/products/data_quality/backend/facade/enums.py b/products/data_quality/backend/facade/enums.pyindex e8d4228ad85e..11ca8060d2c0 100644--- a/products/data_quality/backend/facade/enums.py+++ b/products/data_quality/backend/facade/enums.py@@ -63,25 +63,34 @@ class SuiteRunStatus(StrEnum):class SuiteRunTrigger(StrEnum):"""What started a suite run.- Every automatic trigger is an event on the subject's own data -- a materialization or a source- sync completing. Checks have no independent schedule.+ Automatic runs follow materializations, source syncs, or a subject's schedule."""MANUAL = "manual"MATERIALIZATION = "materialization"SOURCE_SYNC = "source_sync"+ SCHEDULED = "scheduled"class SubjectType(StrEnum):"""Kind of catalog object a check targets.- On the check itself the subject is a foreign key (``saved_query`` for views, ``table`` for- warehouse tables); run history denormalizes it as loose ``(subject_type, subject_uuid, name)``+ On the check itself the subject is a foreign key (``saved_query``, ``table``, or ``metric``);+ run history denormalizes it as loose ``(subject_type, subject_uuid, name)``tuples so it outlives hard deletes."""TABLE = "table"VIEW = "view"+ METRIC = "metric"+++def subject_type_choices() -> dict[str, str]:+ return {kind.value: kind.value for kind in SubjectType}+++def suite_run_trigger_choices() -> dict[str, str]:+ return {trigger.value: trigger.value for trigger in SuiteRunTrigger}class SubjectStatus(StrEnum):diff --git a/products/data_quality/backend/facade/models.py b/products/data_quality/backend/facade/models.pyindex c818f81852f1..ace75035f672 100644--- a/products/data_quality/backend/facade/models.py+++ b/products/data_quality/backend/facade/models.py@@ -7,4 +7,9 @@ isolation boundary.from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun, TeamDataQualityConfig-__all__ = ["DataQualityCheck", "DataQualityCheckRun", "DataQualitySuiteRun", "TeamDataQualityConfig"]+__all__ = [+ "DataQualityCheck",+ "DataQualityCheckRun",+ "DataQualitySuiteRun",+ "TeamDataQualityConfig",+]diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.pyindex 619e20fbd08a..06e4f3c3148f 100644--- a/products/data_quality/backend/logic/checks.py+++ b/products/data_quality/backend/logic/checks.py@@ -1,20 +1,21 @@"""Authoring and triggering data quality checks.Creation is an upsert on the fingerprint (KTD: agents re-propose the same check constantly, and a-duplicate row is worse than a no-op). Everything that runs a check goes through Temporal -- nothing-here waits on a warehouse query.+duplicate row is worse than a no-op). Check runs go through Temporal. Metric authoring validates+the composed SQL without executing the query."""import asyncio-from collections.abc import Iterable+from collections.abc import Callable, Iterablefrom dataclasses import asdictfrom datetime import UTC, datetime+from operator import attrgetterfrom typing import Anyfrom uuid import UUID, uuid4from django.conf import settingsfrom django.db import IntegrityError, transaction-from django.db.models import QuerySet+from django.db.models import Q, QuerySetfrom temporalio.common import RetryPolicy@@ -27,7 +28,13 @@ from ..facade.contracts import CHECK_SUITE_WORKFLOW_NAMEfrom ..facade.enums import SubjectHealth, SubjectStatus, SubjectType, SuiteRunStatus, SuiteRunTriggerfrom ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom .compiler import related_subject_ref-from .errors import DuplicateDefinitionError, NameConflictError, SubjectUnresolvableError+from .errors import (+ CheckConfigError,+ ConcurrentEditError,+ DuplicateDefinitionError,+ NameConflictError,+ SubjectUnresolvableError,+)from .exceptions import CheckNameConflictfrom .health import CheckStatusRow, roll_up_healthfrom .registry import get_spec@@ -53,12 +60,25 @@ _ASSERTION_FIELDS = ("check_type", "column_name", "config")_EDITABLE_FIELDS = (*_UPSERTABLE_FIELDS, *_ASSERTION_FIELDS)+_MAX_EDIT_ATTEMPTS = 3+_definition_identity = attrgetter("subject_type", "subject_uuid", "fingerprint")+++def _edits_the_assertion(fields: Iterable[str]) -> bool:+ """Whether a write proposes a new assertion, rather than only presentation fields."""+ requested = set(fields)+ return any(field in requested for field in _ASSERTION_FIELDS)+def _subject_fk(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}- return {"saved_query_id": subject_uuid}+ if subject_type == SubjectType.VIEW:+ return {"saved_query_id": subject_uuid}+ if subject_type == SubjectType.METRIC:+ return {"metric_id": subject_uuid}+ raise ValueError(f"Unknown check subject type: {subject_type}")def validate_check(@@ -75,11 +95,16 @@ def validate_check(normalized form rather than whatever representation the request happened to use."""spec = get_spec(check_type)+ if SubjectType(subject_type) not in spec.subject_types:+ raise CheckConfigError(f"A {check_type} check cannot target a {subject_type}. Choose a supported check type.")parsed = spec.validate(config, column_name)- if not resolve_subject(team.id, subject_type, subject_uuid).exists:+ subject = resolve_subject(team.id, subject_type, subject_uuid)+ if not subject.exists:raise SubjectUnresolvableError(f"No {subject_type} with id {subject_uuid} in this project.")-+ if subject.subject_type == SubjectType.METRIC and column_name:+ raise CheckConfigError("A check on a metric takes no column. Remove the column and save again.")+ spec.referenced_table_names(parsed, subject)# After the subject resolves, so the column type is only looked up for a check that could run.parsed = spec.coerce_to_column(parsed, subject_column_type(team.id, subject_type, subject_uuid, column_name))@@ -190,7 +215,14 @@ class _CandidateDefinition:fingerprint: str-def edit_check(*, team: Team, check: DataQualityCheck, editor: User | None, **fields: Any) -> DataQualityCheck:+def edit_check(+ *,+ team: Team,+ check: DataQualityCheck,+ editor: User | None,+ authorize: Callable[[DataQualityCheck], None] | None = None,+ **fields: Any,+) -> DataQualityCheck:"""Save a complete definition change, or none of it. The owning subject never moves.Two edits to the same check serialize on the row lock, so the loser recomputes against what the@@ -199,26 +231,36 @@ def edit_check(*, team: Team, check: DataQualityCheck, editor: User | None, **fisame conflict the precheck raises."""requested = {key: value for key, value in fields.items() if key in _EDITABLE_FIELDS}- try:- with transaction.atomic():- locked = DataQualityCheck.objects.for_team(team.id).select_for_update().get(id=check.id)- return _commit_edit(team, locked, editor, requested)- except IntegrityError:- # Which constraint lost decides which field the error is addressed to. Asking about the- # definition alone would answer "duplicate" for every one of them, since an edit that leaves- # the assertion alone still finds its own fingerprint.- candidate = _candidate_definition(team, check, requested)- if _definition_taken(check, candidate.fingerprint):- raise DuplicateDefinitionError()- if _name_taken(team.id, requested.get("name") or "", exclude_id=check.id):- raise NameConflictError()- raise+ for _ in range(_MAX_EDIT_ATTEMPTS):+ current = DataQualityCheck.objects.for_team(team.id).get(id=check.id)+ candidate = _candidate_definition(team, current, requested)+ if authorize is not None:+ authorize(current)+ try:+ with transaction.atomic():+ locked = DataQualityCheck.objects.for_team(team.id).select_for_update().get(id=check.id)+ if _definition_identity(locked) != _definition_identity(current):+ continue+ return _commit_edit(team, locked, editor, requested, candidate)+ except IntegrityError:+ # Which constraint lost decides which field the error is addressed to. Asking about the+ # definition alone would answer "duplicate" for every one of them, since an edit that leaves+ # the assertion alone still finds its own fingerprint.+ if _definition_taken(current, candidate.fingerprint):+ raise DuplicateDefinitionError()+ if _name_taken(team.id, requested.get("name") or "", exclude_id=check.id):+ raise NameConflictError()+ raise+ raise ConcurrentEditError()def _commit_edit(- team: Team, check: DataQualityCheck, editor: User | None, requested: dict[str, Any]+ team: Team,+ check: DataQualityCheck,+ editor: User | None,+ requested: dict[str, Any],+ candidate: _CandidateDefinition,) -> DataQualityCheck:- candidate = _candidate_definition(team, check, requested)_ensure_definition_available(check, candidate.fingerprint)if _name_taken(team.id, requested.get("name") or "", exclude_id=check.id):raise NameConflictError()@@ -243,6 +285,17 @@ def _commit_edit(def _candidate_definition(team: Team, check: DataQualityCheck, requested: dict[str, Any]) -> _CandidateDefinition:+ if not _edits_the_assertion(requested):+ # A presentation-only edit asserts nothing new, so the stored definition is kept as it is+ # rather than revalidated. A subject can stop supporting its check after the check exists (a+ # metric moves off a HogQL definition), and revalidating here would block the very edit that+ # settles it: turning the check off.+ return _CandidateDefinition(+ check_type=check.check_type,+ column_name=check.column_name,+ config=check.config,+ fingerprint=check.fingerprint,+ )check_type = requested.get("check_type", check.check_type)column_name = requested.get("column_name", check.column_name)parsed = validate_check(@@ -291,13 +344,26 @@ def soft_delete_check(check: DataQualityCheck) -> None:check.save(update_fields=["deleted", "deleted_at", "enabled", "updated_at"])+def live_subject_checks(checks: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:+ return (+ checks.filter(+ Q(subject_type=SubjectType.METRIC, metric_id__isnull=False)+ | Q(subject_type=SubjectType.VIEW, saved_query_id__isnull=False)+ | Q(subject_type=SubjectType.TABLE, table_id__isnull=False)+ )+ .exclude(metric__deleted=True)+ .exclude(saved_query__deleted=True)+ .exclude(table__deleted=True)+ )++def 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))# 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 queryset.filter(deleted=False)+ return queryset if include_deleted else live_subject_checks(queryset.filter(deleted=False))def latest_run_ids(team_id: int, check_ids: Iterable[UUID]) -> list[UUID]:@@ -363,6 +429,7 @@ def start_check_suite(trigger=trigger,saved_query_ids=subject_uuids if subject_type == SubjectType.VIEW else [],table_ids=subject_uuids if subject_type == SubjectType.TABLE else [],+ metric_ids=subject_uuids if subject_type == SubjectType.METRIC else [],check_ids=check_ids or [],suite_run_id=str(suite_run.id),created_by_id=user.id if user else None,diff --git a/products/data_quality/backend/logic/contracts.py b/products/data_quality/backend/logic/contracts.pyindex 8d6c92682116..0bc9ed0ddc2a 100644--- a/products/data_quality/backend/logic/contracts.py+++ b/products/data_quality/backend/logic/contracts.py@@ -9,6 +9,8 @@ from ..facade.enums import SubjectTypeif TYPE_CHECKING:from posthog.hogql import ast+ from products.data_catalog.backend.facade.contracts import HogQLMetricDefinition+class Evaluation(StrEnum):"""How the runner turns a compiled query's result row into a status."""@@ -43,6 +45,8 @@ class SubjectRef:name: strqueryable_name: strexists: bool+ definition_kind: str | None = None+ metric_definition: "HogQLMetricDefinition | None" = None@dataclass(frozen=True)diff --git a/products/data_quality/backend/logic/errors.py b/products/data_quality/backend/logic/errors.pyindex 71fc0904ba8d..7a9ab538c6f7 100644--- a/products/data_quality/backend/logic/errors.py+++ b/products/data_quality/backend/logic/errors.py@@ -42,3 +42,12 @@ class NameConflictError(CheckEditConflict):def __init__(self, message: str = "A check with this name already exists.") -> None:super().__init__(message)+++class ConcurrentEditError(CheckEditConflict):+ """The check kept changing while the edit was being prepared, so nothing was written."""++ code = "concurrent_edit"++ def __init__(self, message: str = "This check changed while you were editing it. Reload it and try again.") -> None:+ super().__init__(message)diff --git a/products/data_quality/backend/logic/metric_query.py b/products/data_quality/backend/logic/metric_query.pynew file mode 100644index 000000000000..0b470bb6f24d--- /dev/null+++ b/products/data_quality/backend/logic/metric_query.py@@ -0,0 +1,83 @@+"""Bind a metric definition into a custom-SQL failure query without constructing SQL text."""++from collections.abc import Sequence+from typing import cast++from posthog.hogql import ast+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.parser import parse_select+from posthog.hogql.placeholders import find_placeholders, replace_placeholders+from posthog.hogql.visitor import TraversingVisitor++from posthog.exceptions_capture import capture_exception++from products.data_catalog.backend.facade.contracts import HogQLMetricDefinition++from .errors import CheckConfigError+++class _RelationPlaceholders(TraversingVisitor):+ def __init__(self) -> None:+ self.placeholders: list[ast.Placeholder] = []++ def visit_join_expr(self, node: ast.JoinExpr) -> None:+ if isinstance(node.table, ast.Placeholder):+ self.placeholders.append(node.table)+ super().visit_join_expr(node)+++class _MetricCheckCteValidator(TraversingVisitor):+ def visit_cte(self, node: ast.CTE) -> None:+ raise CheckConfigError(+ "Metric custom_sql checks cannot use CTEs. Query {metric} directly or through a subquery."+ )+++def bind_metric_query(+ check_query: str, metric_definition: HogQLMetricDefinition+) -> ast.SelectQuery | ast.SelectSetQuery:+ """Return the check query with exactly one metric relation replaced by its saved query AST."""+ metric_placeholders: dict[str, ast.Expr] = {+ name: ast.Constant(value=value) for name, value in metric_definition.values.items()+ }+ metric_query = _parse(metric_definition.query, "Could not parse the metric query.", metric_placeholders)+ check_ast = _parse(check_query, "Could not parse the metric custom_sql query.")+ _validate_metric_placeholder(check_ast)+ _MetricCheckCteValidator().visit(check_ast)+ return cast("ast.SelectQuery | ast.SelectSetQuery", replace_placeholders(check_ast, {"metric": metric_query}))+++def _parse(+ query: str, unparseable: str, placeholders: dict[str, ast.Expr] | None = None+) -> ast.SelectQuery | ast.SelectSetQuery:+ try:+ return parse_select(query.rstrip(";").strip(), placeholders=placeholders)+ except ExposedHogQLError:+ raise CheckConfigError(unparseable)+ except Exception as error:+ capture_exception(error)+ raise CheckConfigError(unparseable)+++def _validate_metric_placeholder(check_ast: ast.SelectQuery | ast.SelectSetQuery) -> None:+ found = find_placeholders(check_ast)+ if found.has_filters:+ raise CheckConfigError("Metric custom_sql checks cannot use {filters}.")+ if found.placeholder_expressions:+ raise CheckConfigError("Metric custom_sql checks cannot use expression placeholders.")+ if not _has_exactly_one_metric_relation(found.placeholder_fields, check_ast):+ raise CheckConfigError("Metric custom_sql checks must use exactly one {metric} relation placeholder.")+++def _has_exactly_one_metric_relation(+ placeholder_fields: Sequence[list[str | int]], check_ast: ast.SelectQuery | ast.SelectSetQuery+) -> bool:+ if placeholder_fields != [["metric"]]:+ return False+ relations = _RelationPlaceholders()+ relations.visit(check_ast)+ return len(relations.placeholders) == 1 and _is_metric_placeholder(relations.placeholders[0])+++def _is_metric_placeholder(placeholder: ast.Placeholder) -> bool:+ return isinstance(placeholder.expr, ast.Field) and placeholder.expr.chain == ["metric"]diff --git a/products/data_quality/backend/logic/navigation.py b/products/data_quality/backend/logic/navigation.pyindex 7a72da76a68c..d91e9a28f079 100644--- a/products/data_quality/backend/logic/navigation.py+++ b/products/data_quality/backend/logic/navigation.py@@ -1,15 +1,16 @@"""Where a check's subject can be opened.A check row carries the subject's id, which is enough to run it but not enough to link to it: a-view is administered on its DAG node and a synced table on its source's schema page. Both are-resolved in bulk for a whole page of checks, never per row -- the overview lists every check in the-project, so a query per row is a query per table in the warehouse.+view is administered on its DAG node, a synced table on its source's schema page, and a metric on+its own catalog page. Each kind is resolved in bulk for a whole page of checks, never per row -- the+overview lists every check in the project, so a query per row is a query per table in the warehouse."""from collections.abc import Iterablefrom posthog.dataclasses import frozen+from products.data_catalog.backend.facade import api as data_catalog_facadefrom products.data_modeling.backend.facade import api as data_modeling_facadefrom products.warehouse_sources.backend.facade import api as warehouse_facade@@ -32,12 +33,15 @@ class SubjectLocation:node_id: str | None = Nonesource_id: str | None = Noneschema_id: str | None = None+ metric_name: str | None = Nonedef subject_locations(team_id: int, checks: Iterable[DataQualityCheck]) -> dict[SubjectKey, SubjectLocation]:- """Two queries for any number of checks."""+ """A read per subject kind on the page, whatever the number of checks."""+ checks = list(checks)view_ids = {str(check.saved_query_id) for check in checks if check.saved_query_id}table_ids = {check.table_id for check in checks if check.table_id}+ metric_ids = {check.metric_id for check in checks if check.metric_id}locations: dict[SubjectKey, SubjectLocation] = {SubjectKey(subject_type=SubjectType.VIEW, subject_uuid=saved_query_id): SubjectLocation(node_id=node_id)@@ -47,4 +51,8 @@ def subject_locations(team_id: int, checks: Iterable[DataQualityCheck]) -> dict[locations[SubjectKey(subject_type=SubjectType.TABLE, subject_uuid=str(table_id))] = SubjectLocation(source_id=str(location.source_id), schema_id=str(location.schema_id))+ for metric_id, metric_name in data_catalog_facade.metric_names_for_ids(team_id, metric_ids).items():+ locations[SubjectKey(subject_type=SubjectType.METRIC, subject_uuid=str(metric_id))] = SubjectLocation(+ metric_name=metric_name+ )return locationsdiff --git a/products/data_quality/backend/logic/notifications.py b/products/data_quality/backend/logic/notifications.pyindex ea3ceaf4ea97..543376e4e78f 100644--- a/products/data_quality/backend/logic/notifications.py+++ b/products/data_quality/backend/logic/notifications.py@@ -4,17 +4,16 @@ Only the pass-to-fail edge notifies, and only for error-severity checks. A checkrun after run is already known about; re-notifying every run is how an inbox gets ignored."""-from typing import cast+from collections.abc import Sequence+from urllib.parse import quote+from uuid import UUIDimport structlogfrom posthog.models import Team, User-from posthog.scopes import APIScopeObject-from products.access_control.backend.facade.user_access_control import (- UserAccessControl,- access_level_satisfied_for_resource,-)+from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.data_modeling.backend.facade import api as data_modeling_facadefrom products.notifications.backend.facade.api import (NotificationData,NotificationType,@@ -23,21 +22,26 @@ from products.notifications.backend.facade.api import (TargetType,create_notification,)+from products.warehouse_sources.backend.facade import api as warehouse_facadefrom ..facade.enums import CheckRunStatus, SubjectTypefrom ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom .checks import checks_for_subjectfrom .flags import is_data_quality_checks_enabled_for_team_id-from .subject_access import denied_subject_names, is_subject_denied, referenced_subject_names, referencing_check_types+from .subject_access import (+ DenialContext,+ SubjectMetadata,+ caller_denial_context,+ can_be_object_denied,+ referenced_subject_names,+ referencing_check_types,+ subject_metadata,+)+from .subjects import resolve_subjectLOGGER = structlog.get_logger(__name__)-# Object-level access controls for a warehouse table or view are keyed on the child resource; both-# inherit from the `warehouse_objects` umbrella the built-in resource-level filter checks.-_SUBJECT_RESOURCE: dict[SubjectType, APIScopeObject] = {- SubjectType.TABLE: cast(APIScopeObject, "warehouse_table"),- SubjectType.VIEW: cast(APIScopeObject, "warehouse_view"),-}+_OBJECT_GATED_SUBJECT_TYPES = frozenset({SubjectType.TABLE, SubjectType.VIEW})class _WarehouseSubjectResolver(RecipientsResolver):@@ -63,15 +67,20 @@ class _WarehouseSubjectResolver(RecipientsResolver):subject_type: str,subject_uuid: str,referenced_names: list[str] | None = None,+ executed_references: Sequence[dict[str, str]] = (),+ references_unknown: bool = False,) -> None:self._team = teamself._subject_type = subject_typeself._subject_uuid = subject_uuidself._referenced_names = referenced_names or []+ self._executed_references = executed_references+ self._references_unknown = references_unknown# One access-control object per member, reused across both gates below (and the warehouse# database build the referenced-subject gate runs) so a single failing check doesn't rebuild# it -- and its membership, role, and access-control lookups -- once per pass.self._access: dict[int, UserAccessControl] = {}+ self._subject_metadata: SubjectMetadata | None = Nonedef _access_of(self, user: User) -> UserAccessControl:access = self._access.get(user.id)@@ -89,70 +98,97 @@ class _WarehouseSubjectResolver(RecipientsResolver):def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]:user_ids = super().resolve(target_type, target_id, team_id)user_ids = self.filter_by_access_control(user_ids, "query", self._team)- user_ids = self._filter_by_object_access(user_ids)- return self._filter_by_referenced_subject_access(user_ids)-- def _filter_by_object_access(self, user_ids: list[int]) -> list[int]:- resource = _SUBJECT_RESOURCE.get(SubjectType(self._subject_type))- if resource is None:+ if self._subject_type == SubjectType.METRIC:+ user_ids = self.filter_by_access_control(user_ids, "data_catalog", self._team)+ return self._filter_by_subject_access(user_ids)++ def _filter_by_subject_access(self, user_ids: list[int]) -> list[int]:+ # Both gates below are per-member, so they share one member query, one access-control object+ # and one denial snapshot each rather than a pass apiece.+ if not self._object_gate_applies() and not self._reference_gate_applies():return user_ids- object_id = self._subject_uuid+ # No warehouse access control means no denials, so skip the per-member work entirely.if not self._access_controls_supported(user_ids):return user_ids- allowed: list[int] = []- for user in User.objects.filter(id__in=user_ids):- level = self._access_of(user).bulk_object_access_levels(resource, [(object_id, None)]).get(object_id)- if level is not None and access_level_satisfied_for_resource(resource, level, "viewer"):- allowed.append(user.id)- return allowed+ return [user.id for user in User.objects.filter(id__in=user_ids) if self._may_receive(user)]- def _filter_by_referenced_subject_access(self, user_ids: list[int]) -> list[int]:- # The declared subject isn't the only one the count depends on: a relationships check reads- # its target and a custom_sql check reads arbitrary tables. Drop members denied any of those,- # matching the run-history endpoint -- resolved by name the same way the loaders resolve them.- if not self._referenced_names:- return user_ids+ def _object_gate_applies(self) -> bool:+ return SubjectType(self._subject_type) in _OBJECT_GATED_SUBJECT_TYPES- # No warehouse access control means no denials, so skip the per-member database build the- # denial check would otherwise run -- the same early exit the object-access gate makes.- if not self._access_controls_supported(user_ids):- return user_ids+ def _reference_gate_applies(self) -> bool:+ # The declared subject isn't the only one the count depends on: a relationships check reads+ # its target and a custom_sql check reads arbitrary tables.+ return bool(self._referenced_names) or bool(self._executed_references) or self._references_unknown++ def _may_receive(self, user: User) -> bool:+ access = self._access_of(user)+ if self._object_gate_applies() and not self._has_object_access(access):+ return False+ if not self._reference_gate_applies():+ return True+ if self._references_unknown and can_be_object_denied(access):+ return False+ context = self._denial_context_of(user)+ if self._executed_references and not all(+ context.readable.contains(ref["subject_type"], ref["subject_uuid"]) for ref in self._executed_references+ ):+ return False+ return not context.matcher.matches(self._referenced_names)++ def _has_object_access(self, access: UserAccessControl) -> bool:+ object_id = UUID(self._subject_uuid)+ allowed_ids = (+ warehouse_facade.allowed_table_ids(self._team.id, access, ids=[object_id])+ if self._subject_type == SubjectType.TABLE+ else data_modeling_facade.allowed_saved_query_ids(self._team.id, access, ids=[object_id])+ )+ return object_id in allowed_ids- allowed: list[int] = []- for user in User.objects.filter(id__in=user_ids):- denied = denied_subject_names(self._team, user, self._access_of(user))- if not any(is_subject_denied(name, denied) for name in self._referenced_names):- allowed.append(user.id)- return allowed+ def _denial_context_of(self, user: User) -> DenialContext:+ if self._subject_metadata is None:+ self._subject_metadata = subject_metadata(self._team.id)+ return caller_denial_context(self._team, user, self._access_of(user), metadata=self._subject_metadata)-def notify_check_started_failing(check: DataQualityCheck, failed_row_count: int | None) -> None:+def notify_check_started_failing(+ check: DataQualityCheck, failed_row_count: int | None, *, executed_references: Sequence[dict[str, str]] | None = ()+) -> None:"""Best-effort: a notification failure must never take down the run that produced it."""try:if not is_data_quality_checks_enabled_for_team_id(check.team_id) or check.subject_uuid is None:returnteam = Team.objects.get(id=check.team_id)+ subject = resolve_subject(team.id, check.subject_type, check.subject_uuid)+ if not subject.exists:+ return+ is_metric = check.subject_type == SubjectType.METRIC+ subject_name = subject.name if is_metric else check.subject_namecreate_notification(NotificationData(team_id=check.team_id,notification_type=NotificationType.DATA_QUALITY_CHECK_FAILURE,priority=Priority.NORMAL,- title=f"Data quality check failed on {check.subject_name}",+ title=f"Data quality check failed on {subject_name}",body=_body(check, failed_row_count),target_type=TargetType.TEAM,target_id=str(check.team_id),# The body names a warehouse table or view and one of its columns, so it points at# the subject object (not the check) and the resolver filters recipients down to# members with object-level access to it, plus query access for the count.- resource_type="warehouse_objects",+ resource_type="data_catalog" if is_metric else "warehouse_objects",resource_id=str(check.subject_uuid),+ source_url=f"/project/{team.id}/data-catalog/metrics/{quote(subject_name, safe='')}?tab=tests"+ if is_metric+ else "",resolver=_WarehouseSubjectResolver(team,check.subject_type,str(check.subject_uuid),- referenced_names=referenced_subject_names(team.id, check.check_type, check.config),+ referenced_names=referenced_subject_names(team.id, check.check_type, check.config, subject=subject),+ executed_references=executed_references or (),+ references_unknown=executed_references is None,),))diff --git a/products/data_quality/backend/logic/permissions.py b/products/data_quality/backend/logic/permissions.pynew file mode 100644index 000000000000..480c72d4564b--- /dev/null+++ b/products/data_quality/backend/logic/permissions.py@@ -0,0 +1,96 @@+from collections.abc import Collection+from dataclasses import replace+from typing import TYPE_CHECKING, Literal++from products.data_modeling.backend.facade import api as data_modeling_facade+from products.warehouse_sources.backend.facade import api as warehouse_facade++from ..facade.enums import SubjectType+from .subject_access import DenialContext, ReadableSubjects++if TYPE_CHECKING:+ from posthog.scopes import APIScopeObject, APIScopeObjectOrNotSupported++ from products.access_control.backend.facade.user_access_control import UserAccessControl++_SUBJECT_RESOURCES: dict[SubjectType, "APIScopeObject"] = {+ SubjectType.TABLE: "warehouse_table",+ SubjectType.VIEW: "warehouse_view",+ SubjectType.METRIC: "data_catalog",+}+++def authorized_subject_types(+ access: "UserAccessControl",+ 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(+ kind+ for 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)+ )+++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 True+ if access.team is None or kind == SubjectType.METRIC:+ return False+ if kind == SubjectType.TABLE:+ return bool(warehouse_facade.allowed_table_ids(access.team.id, access, required_level=level))+ return bool(data_modeling_facade.allowed_saved_query_ids(access.team.id, access, required_level=level))+++def writable_subjects(+ context: DenialContext, access: "UserAccessControl", *, allowed: Collection[SubjectType]+) -> ReadableSubjects:+ """The subjects this caller may change, narrowed to the kinds ``allowed`` permits.++ Takes the restriction rather than a pre-restricted context: the two have to be applied in that+ order, and a caller that passed an unrestricted context would get a wider answer than its scopes+ allow.+ """+ context = restrict_subject_types(context, allowed)+ if access.team is None:+ return ReadableSubjects(table_ids=frozenset(), view_ids=frozenset())+ return ReadableSubjects(+ table_ids=context.readable.table_ids+ & warehouse_facade.allowed_table_ids(access.team.id, access, required_level="editor"),+ view_ids=context.readable.view_ids+ & data_modeling_facade.allowed_saved_query_ids(access.team.id, access, required_level="editor"),+ metric_ids=context.readable.metric_ids+ if access.check_access_level_for_resource("data_catalog", "editor")+ else frozenset(),+ )+++def _scope_allows(scopes: Collection[str] | None, resource: str, write: bool) -> bool:+ if scopes is None or "*" in scopes or f"{resource}:write" in scopes:+ return True+ return not write and f"{resource}:read" in scopes+++def restrict_subject_types(context: DenialContext, allowed: Collection[SubjectType]) -> DenialContext:+ denied = set(context.denied)+ if SubjectType.TABLE not in allowed:+ denied.update(context.metadata.table_names.values())+ if SubjectType.VIEW not in allowed:+ denied.update(context.metadata.view_names.values())+ return replace(+ context,+ denied=denied,+ readable=ReadableSubjects(+ table_ids=context.readable.table_ids if SubjectType.TABLE in allowed else frozenset(),+ view_ids=context.readable.view_ids if SubjectType.VIEW in allowed else frozenset(),+ metric_ids=context.readable.metric_ids if SubjectType.METRIC in allowed else frozenset(),+ ),+ )diff --git a/products/data_quality/backend/logic/query_scope.py b/products/data_quality/backend/logic/query_scope.pynew file mode 100644index 000000000000..6aadd1ff6b3c--- /dev/null+++ b/products/data_quality/backend/logic/query_scope.py@@ -0,0 +1,65 @@+from dataclasses import replace++from posthog.hogql import ast+from posthog.hogql.visitor import TraversingVisitor++from .errors import CheckConfigError+++class ScopedQueryVisitor(TraversingVisitor):+ def __init__(self) -> None:+ self.cte_names: set[str] = set()++ def visit_select_query(self, node: ast.SelectQuery) -> None:+ parent_ctes = self.cte_names+ self.cte_names = set(parent_ctes)+ try:+ for cte in (node.ctes or {}).values():+ self.visit(cte)+ super().visit_select_query(replace(node, ctes=None))+ finally:+ self.cte_names = parent_ctes++ def visit_cte(self, node: ast.CTE) -> None:+ if node.recursive and isinstance(node.expr, ast.SelectSetQuery):+ self.visit(node.expr.initial_select_query)+ self.cte_names.add(node.name)+ self.visit(node.expr)+ self.cte_names.add(node.name)++ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:+ parent_ctes = self.cte_names+ self.cte_names = set(parent_ctes)+ try:+ self.visit(node.initial_select_query)+ if isinstance(node.initial_select_query, ast.SelectQuery):+ self.cte_names.update(node.initial_select_query.ctes or {})+ for branch in node.subsequent_select_queries:+ self.visit(branch.select_query)+ self.visit(node.limit)+ self.visit(node.offset)+ finally:+ self.cte_names = parent_ctes+++class _TableReferences(ScopedQueryVisitor):+ def __init__(self) -> None:+ super().__init__()+ self.table_names: set[str] = set()++ def visit_join_expr(self, node: ast.JoinExpr) -> None:+ if node.table_args is not None or not isinstance(node.table, ast.Field | ast.SelectQuery | ast.SelectSetQuery):+ raise CheckConfigError(+ "Custom SQL checks cannot use this table expression. Use a table name or a SELECT subquery."+ )+ if isinstance(node.table, ast.Field):+ name = ".".join(str(part) for part in node.table.chain)+ if name not in self.cte_names:+ self.table_names.add(name)+ super().visit_join_expr(node)+++def referenced_table_names(query: ast.SelectQuery | ast.SelectSetQuery) -> list[str]:+ references = _TableReferences()+ references.visit(query)+ return sorted(references.table_names)diff --git a/products/data_quality/backend/logic/registry.py b/products/data_quality/backend/logic/registry.pyindex 47b4227f7fdf..1705d22ee8f1 100644--- a/products/data_quality/backend/logic/registry.py+++ b/products/data_quality/backend/logic/registry.py@@ -5,7 +5,7 @@ one import and one entry."""from ..facade.contracts import CheckTypeInfo-from ..facade.enums import CheckType+from ..facade.enums import CheckType, SubjectTypefrom .spec import CheckTypeSpecfrom .types import accepted_values, custom_sql, freshness, not_null, relationships, row_count, unique@@ -34,7 +34,7 @@ def all_specs() -> list[CheckTypeSpec]:return [_SPECS[check_type] for check_type in CheckType]-def list_check_types() -> list[CheckTypeInfo]:+def list_check_types(subject_type: str | None = None) -> list[CheckTypeInfo]:"""The catalog, as plain values. What callers outside the compiler get instead of the specs."""return [CheckTypeInfo(@@ -44,6 +44,7 @@ def list_check_types() -> list[CheckTypeInfo]:config_schema=spec.json_schema,)for spec in all_specs()+ if subject_type is None or SubjectType(subject_type) in spec.subject_types]diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.pyindex 366fe3728473..6960ea825f96 100644--- a/products/data_quality/backend/logic/runner.py+++ b/products/data_quality/backend/logic/runner.py@@ -10,6 +10,7 @@ check must not take down the rest of its suite.import timefrom dataclasses import dataclass, replacefrom datetime import UTC, datetime+from enum import Enum, autofrom typing import TYPE_CHECKING, Anyfrom django.db import transaction@@ -25,15 +26,16 @@ from posthog.models.scoping import team_scopefrom posthog.models.team import Teamfrom posthog.models.user import User-from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectStatus, SuiteRunTrigger+from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectStatus, SubjectType, SuiteRunTriggerfrom ..models import DataQualityCheck, DataQualitySuiteRunfrom .compiler import compile_check, related_subject_ref-from .contracts import CompiledCheck, Evaluation+from .contracts import CompiledCheck, Evaluation, SubjectReffrom .notifications import notify_check_started_failingfrom .run_records import record_check_runfrom .staged_audit import StagedSubjectOverride, build_staged_databasefrom .subject_access import check_type_reads_beyond_subject, pin_referenced_subjectsfrom .subjects import resolve_subject+from .types.common import within_boundsQUERY_TYPE = "data_quality_check"@@ -42,6 +44,10 @@ FAILING_STATUSES = (CheckRunStatus.FAILED, CheckRunStatus.ERRORED)STAGED_FILES_UNREADABLE = "The staged files could not be read, so this data was not audited."+class _ReferenceState(Enum):+ NOT_SUPPLIED = auto()++@dataclass(frozen=True)class CheckOutcome:"""What one check execution produced, before it is written down."""@@ -52,6 +58,7 @@ class CheckOutcome:compiled_query: str = ""error: str = ""became_failing: bool = False+ referenced_subjects: list[dict[str, str]] | None | _ReferenceState = _ReferenceState.NOT_SUPPLIEDdef run_check(@@ -87,7 +94,13 @@ def run_check(_update_check(check, outcome)if became_failing:- notify_check_started_failing(check, outcome.failed_row_count)+ notify_check_started_failing(+ check,+ outcome.failed_row_count,+ executed_references=None+ if outcome.referenced_subjects is _ReferenceState.NOT_SUPPLIED+ else outcome.referenced_subjects,+ )return replace(outcome, became_failing=became_failing)@@ -147,6 +160,8 @@ def _authorize(check: DataQualityCheck, suite_run: DataQualitySuiteRun) -> _Authauthorize against, returning ``None`` errors the run rather than bypassing the ACL."""if suite_run.trigger == SuiteRunTrigger.MANUAL:+ if suite_run.created_by is None and check_type_reads_beyond_subject(check.check_type):+ return Nonereturn _Authorization(run_as=suite_run.created_by, bypass=suite_run.created_by is None)if not check_type_reads_beyond_subject(check.check_type):return _Authorization(run_as=None, bypass=True)@@ -215,7 +230,7 @@ def _execute(if authorization is None:return CheckOutcome(status=CheckRunStatus.ERRORED,- error="An automated check that reads another subject needs an author to authorize its warehouse access.",+ error="A check that reads another subject needs an initiator or author to authorize its warehouse access.",)related = related_subject_ref(check.check_type, check.config)@@ -226,6 +241,29 @@ def _execute(config=check.config,related_subject=resolve_subject(team.id, *related) if related else None,)+ if staged is not None and subject.subject_type == SubjectType.METRIC:+ return CheckOutcome(status=CheckRunStatus.ERRORED, error="Metric checks cannot audit staged data.")+ referenced_subjects = pin_referenced_subjects(team.id, check.check_type, check.config, subject=subject)+ try:+ outcome = _execute_compiled(check, subject, compiled, team, authorization, staged, staged_database_cache)+ except Exception as err:+ outcome = CheckOutcome(+ status=CheckRunStatus.ERRORED,+ error=str(err),+ compiled_query=compiled.printed_failing_rows_query,+ )+ return replace(outcome, referenced_subjects=referenced_subjects)+++def _execute_compiled(+ check: DataQualityCheck,+ subject: SubjectRef,+ compiled: CompiledCheck,+ team: Team,+ authorization: _Authorization,+ staged: StagedSubjectOverride | None,+ staged_database_cache: "dict[Any, Database | None] | None",+) -> CheckOutcome:database = _staged_database(team, staged, authorization, staged_database_cache) if staged is not None else Noneif staged is not None and database is None:# Falling back to the unmodified database would read the live view and rule on data the@@ -284,7 +322,11 @@ def _interpret(observed = _as_float(row.get("observed_value"))if compiled.evaluation is Evaluation.BOUNDS:- status = CheckRunStatus.PASSED if _within_bounds(observed, config) else CheckRunStatus.FAILED+ status = (+ CheckRunStatus.PASSED+ if within_bounds(observed, config.get("min"), config.get("max"))+ else CheckRunStatus.FAILED+ )failed_row_count = Noneelse:failed_row_count = int(row.get("failure_count") or 0)@@ -298,15 +340,6 @@ def _interpret()-def _within_bounds(observed: float | None, config: dict[str, Any]) -> bool:- if observed is None:- return False- minimum, maximum = config.get("min"), config.get("max")- if minimum is not None and observed < minimum:- return False- return not (maximum is not None and observed > maximum)--def _as_float(value: Any) -> float | None:try:return float(value) if value is not None else None@@ -335,7 +368,16 @@ def _record_run(column_name=check.column_name,check_config=check.config,check_severity=check.severity,- referenced_subjects=pin_referenced_subjects(check.team_id, check.check_type, check.config),+ referenced_subjects=(+ outcome.referenced_subjects+ if outcome.referenced_subjects is not _ReferenceState.NOT_SUPPLIED+ else pin_referenced_subjects(+ check.team_id,+ check.check_type,+ check.config,+ subject=resolve_subject(check.team_id, check.subject_type, check.subject_uuid),+ )+ ),status=outcome.status,failed_row_count=outcome.failed_row_count,observed_value=outcome.observed_value,diff --git a/products/data_quality/backend/logic/serialization.py b/products/data_quality/backend/logic/serialization.pyindex 954f54625e2e..f6e1c8593d12 100644--- a/products/data_quality/backend/logic/serialization.py+++ b/products/data_quality/backend/logic/serialization.py@@ -7,7 +7,7 @@ files and read them back: the DB stays the source of truth, files are a projectiThe fingerprint is the identity agents author against -- re-creating a semantically identical checkupserts instead of duplicating -- so it must depend only on what the check *asserts*, never onpresentation (name, description, tags, owner). ``subject_uuid`` here is the id of whichever subject-FK the check carries (saved query or table); the file format keeps the loose pair so it stays+FK the check carries (saved query, table, or metric); the file format keeps the loose pair so it staysportable."""diff --git a/products/data_quality/backend/logic/spec.py b/products/data_quality/backend/logic/spec.pyindex e9785e7ebf45..a71a8935b9ad 100644--- a/products/data_quality/backend/logic/spec.py+++ b/products/data_quality/backend/logic/spec.py@@ -13,7 +13,7 @@ from typing import Any, ClassVarfrom pydantic import BaseModel, ConfigDict, ValidationError-from ..facade.enums import CheckType+from ..facade.enums import CheckType, SubjectTypefrom .contracts import CheckPlan, SubjectReffrom .errors import CheckConfigError@@ -39,6 +39,8 @@ class CheckTypeSpec(ABC):config_model: ClassVar[type[CheckConfig]]requires_column: ClassVar[bool]description: ClassVar[str]+ subject_types: ClassVar[frozenset[SubjectType]] = frozenset({SubjectType.TABLE, SubjectType.VIEW})+ reads_beyond_subject: ClassVar[bool] = False@propertydef json_schema(self) -> dict[str, Any]:@@ -73,13 +75,19 @@ class CheckTypeSpec(ABC):"""The second subject this check needs resolved before it can compile, if any."""return None- def referenced_table_names(self, config: CheckConfig) -> list[str]:+ def referenced_table_names(self, config: CheckConfig, subject: SubjectRef | None = None) -> list[str]:"""Warehouse names this check reads directly, besides its subject and related subject.Only ``custom_sql`` needs this -- its query names arbitrary tables. Every structured typereaches exactly its subject plus, via ``related_subject_ref``, one other, so the default isempty. Used to authorize every subject a check reads, since the worker executes with team- scope only."""+ scope only.++ ``subject`` is the resolved subject when the caller has one. Custom SQL over a metric binds+ the metric query into its AST, so only a resolved subject reveals the tables it reaches;+ every other type ignores it and answers from config alone. Raises ``CheckConfigError`` when+ the references cannot be established.+ """return []@abstractmethoddiff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pyindex 183ece14da07..42a2f2323e82 100644--- a/products/data_quality/backend/logic/subject_access.py+++ b/products/data_quality/backend/logic/subject_access.py@@ -13,27 +13,31 @@ know is absent from that snapshot and therefore out of reach.import jsonfrom collections.abc import Sequence+from dataclasses import field+from itertools import batchedfrom typing import TYPE_CHECKING, Any, Optional, TypeVarfrom uuid import UUIDfrom django.db.models import Exists, OuterRef, Q, QuerySetfrom posthog.hogql.database.database import Database-from posthog.hogql.database.schema.information_schema import references_denied_table+from posthog.hogql.database.schema.information_schema import DeniedTableMatcherfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception+from products.data_catalog.backend.facade import api as data_catalog_facade+from products.data_catalog.backend.facade.contracts import MetricSummaryfrom products.data_modeling.backend.facade import api as data_modeling_facadefrom products.warehouse_sources.backend.facade import api as warehouse_facadefrom ..facade.enums import SubjectTypefrom ..models import DataQualityCheck, DataQualityCheckRunfrom .checks import latest_run_ids-from .contracts import SubjectIdentity+from .contracts import SubjectIdentity, SubjectReffrom .registry import all_specs, get_specfrom .spec import CheckTypeSpec-from .subjects import resolve_subject, resolve_subject_by_name+from .subjects import resolve_metric_subjects, resolve_subject, resolve_subject_by_nameif TYPE_CHECKING:from posthog.models import Team, User@@ -43,22 +47,8 @@ if TYPE_CHECKING:_SUBJECT_TYPE_KEY = "subject_type"_SUBJECT_UUID_KEY = "subject_uuid"_RunQS = TypeVar("_RunQS", bound=QuerySet)---def denied_subject_names(- team: "Team", user: "User", user_access_control: Optional["UserAccessControl"] = None-) -> set[str]:- """The warehouse table/view identifiers this caller cannot query, as the HogQL database sees them.-- This is the exact set the ``information_schema`` loaders consult, so the two paths stay in- lock-step. Fails closed with no principal (the database denies every warehouse table)."""- database = Database.create_for(team=team, user=user, user_access_control=user_access_control)- return set(database._denied_tables)---def is_subject_denied(subject_name: str, denied: set[str]) -> bool:- """Whether a check's subject is in the caller's denied set, matched the same way the loaders match."""- return references_denied_table([subject_name], denied)+_CHECK_VISIBILITY_BATCH_SIZE = 200+_CHECK_VISIBILITY_FIELDS = ("id", "subject_type", "table_id", "saved_query_id", "metric_id", "check_type", "config")def can_be_object_denied(user_access_control: Optional["UserAccessControl"]) -> bool:@@ -88,6 +78,7 @@ class ReadableSubjects:table_ids: frozenset[UUID]view_ids: frozenset[UUID]+ metric_ids: frozenset[UUID] = frozenset()def contains(self, subject_type: str, subject_uuid: str | UUID | None) -> bool:if subject_uuid is None:@@ -100,6 +91,8 @@ class ReadableSubjects:return identifier in self.table_idsif subject_type == SubjectType.VIEW:return identifier in self.view_ids+ if subject_type == SubjectType.METRIC:+ return identifier in self.metric_idsreturn False@@ -115,39 +108,92 @@ class DenialContext:readable: ReadableSubjectsdenied: set[str]database: Database+ metadata: "SubjectMetadata"+ matcher: DeniedTableMatcher = field(init=False, repr=False, compare=False)++ def __post_init__(self) -> None:+ object.__setattr__(self, "matcher", DeniedTableMatcher(self.denied))+++@frozen+class SubjectMetadata:+ table_names: dict[UUID, str]+ view_names: dict[UUID, str]+ metrics: tuple[MetricSummary, ...]+++def subject_metadata(team_id: int) -> SubjectMetadata:+ tables = warehouse_facade.all_queryable_table_names(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))+ return SubjectMetadata(+ table_names={table_id: name for table_id, name in tables.items() if table_id not in excluded_table_ids},+ view_names={+ UUID(view_id): name for view_id, name in data_modeling_facade.all_saved_query_names(team_id).items()+ },+ metrics=tuple(data_catalog_facade.live_metric_summaries(team_id)),+ )-def readable_subjects(team_id: int, denied: set[str]) -> ReadableSubjects:+def readable_subjects(+ team_id: int,+ denied: set[str],+ *,+ can_read_catalog: bool = True,+ metadata: SubjectMetadata | None = None,+) -> ReadableSubjects:"""The team's live warehouse subjects, minus the ones this caller is denied. Four queries.Cost tracks the objects the team has, not the length of retained history, which is what makesit safe to hold a whole page of run history up against."""- tables = warehouse_facade.all_queryable_table_names(team_id)- views = data_modeling_facade.all_saved_query_names(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))+ metadata = metadata if metadata is not None else subject_metadata(team_id)+ matcher = DeniedTableMatcher(denied)return ReadableSubjects(- table_ids=frozenset(- table_id- for table_id, name in tables.items()- if table_id not in excluded_table_ids and not is_subject_denied(name, denied)+ table_ids=frozenset(table_id for table_id, name in metadata.table_names.items() if not matcher.matches([name])),+ view_ids=frozenset(view_id for view_id, name in metadata.view_names.items() if not matcher.matches([name])),+ metric_ids=frozenset(+ metric.id+ for metric in metadata.metrics+ if can_read_catalog and not matcher.matches(metric.referenced_table_names)),- view_ids=frozenset(UUID(view_id) for view_id, name in views.items() if not is_subject_denied(name, denied)),)-def denial_context(team_id: int, database: Database) -> DenialContext:+def denial_context(team_id: int, database: Database, *, metadata: SubjectMetadata | None = None) -> DenialContext:"""The caller's denial state, from a HogQL database that has already been built for them."""+ metadata = metadata if metadata is not None else subject_metadata(team_id)denied = set(database._denied_tables)- return DenialContext(readable=readable_subjects(team_id, denied), denied=denied, database=database)+ access = database.user_access_control+ can_read_catalog = access is not None and access.check_access_level_for_resource("data_catalog", "viewer")+ allowed_tables = warehouse_facade.allowed_table_ids(team_id, access) if access is not None else frozenset()+ allowed_views = data_modeling_facade.allowed_saved_query_ids(team_id, access) if access is not None else frozenset()+ denied.update(name for identifier, name in metadata.table_names.items() if identifier not in allowed_tables)+ denied.update(name for identifier, name in metadata.view_names.items() if identifier not in allowed_views)+ return DenialContext(+ readable=readable_subjects(+ team_id,+ denied,+ can_read_catalog=can_read_catalog,+ metadata=metadata,+ ),+ denied=denied,+ database=database,+ metadata=metadata,+ )def caller_denial_context(- team: "Team", user: "User", user_access_control: Optional["UserAccessControl"] = None+ team: "Team",+ user: "User",+ user_access_control: Optional["UserAccessControl"] = None,+ *,+ metadata: SubjectMetadata | None = None,) -> DenialContext:"""The caller's denial state, building the HogQL database this request will reuse."""- return denial_context(team.id, Database.create_for(team=team, user=user, user_access_control=user_access_control))+ return denial_context(+ team.id, Database.create_for(team=team, user=user, user_access_control=user_access_control), metadata=metadata+ )def unreadable_runs_q(context: DenialContext) -> Q:@@ -215,16 +261,36 @@ def hidden_check_ids(team_id: int, checks: Sequence[DataQualityCheck], context:tenses at once, so each is judged by the rule for its own tense -- the definition by the names itresolves today, the stored run by the identities it recorded."""+ hidden = definition_hidden_ids(team_id, checks, context, {})+ return hidden | _checks_whose_latest_run_is_unreadable(+ team_id, [check.id for check in checks if check.id not in hidden], context+ )+++def definition_hidden_ids(+ team_id: int, checks: Sequence[DataQualityCheck], context: DenialContext, verdicts: dict[str, bool]+) -> set[UUID]:+ """The present-tense half of :func:`hidden_check_ids`: unreadable subject, or unreadable definition.++ ``verdicts`` is carried in by the caller so a scan that runs in batches parses a definition it has+ already seen once, whichever batch it lands in.+ """hidden = {check.id for check in checks if not context.readable.contains(check.subject_type, check.subject_uuid)}- verdicts: dict[str, bool] = {}+ metric_subjects = resolve_metric_subjects(+ team_id,+ {+ UUID(str(check.metric_id))+ for check in checks+ if check.id not in hidden and check.subject_type == SubjectType.METRIC and check.metric_id is not None+ },+ )for check in checks:if check.id in hidden:continue- if _memoized_definition_verdict(team_id, check.check_type, check.config or {}, context, verdicts):+ subject = metric_subjects.get(UUID(str(check.metric_id))) if check.metric_id is not None else None+ if memoized_definition_verdict(team_id, check.check_type, check.config or {}, context, verdicts, subject):hidden.add(check.id)- return hidden | _checks_whose_latest_run_is_unreadable(- team_id, [check.id for check in checks if check.id not in hidden], context- )+ return hiddendef visible_checks(team_id: int, checks: Sequence[DataQualityCheck], context: DenialContext) -> list[DataQualityCheck]:@@ -237,8 +303,39 @@ def visible_checks(team_id: int, checks: Sequence[DataQualityCheck], context: Dereturn [check for check in checks if check.id not in hidden]+def readable_check_subjects(+ queryset: QuerySet[DataQualityCheck], readable: ReadableSubjects+) -> QuerySet[DataQualityCheck]:+ return queryset.filter(+ Q(subject_type=SubjectType.TABLE, table_id__in=readable.table_ids)+ | Q(subject_type=SubjectType.VIEW, saved_query_id__in=readable.view_ids)+ | Q(subject_type=SubjectType.METRIC, metric_id__in=readable.metric_ids)+ )+++def visible_check_queryset(+ team_id: int, queryset: QuerySet[DataQualityCheck], context: DenialContext+) -> QuerySet[DataQualityCheck]:+ queryset = readable_check_subjects(queryset, context.readable)+ candidates = queryset.select_related(None).prefetch_related(None).only(*_CHECK_VISIBILITY_FIELDS)+ hidden: set[UUID] = set()+ survivors: list[UUID] = []+ verdicts: dict[str, bool] = {}+ # The definition scan stays batched, because it holds a parsed config per row. The history scan+ # only needs ids, so it runs once over everything the definition scan let through rather than+ # once per batch.+ for batch in batched(+ candidates.iterator(chunk_size=_CHECK_VISIBILITY_BATCH_SIZE), _CHECK_VISIBILITY_BATCH_SIZE, strict=False+ ):+ batch_hidden = definition_hidden_ids(team_id, batch, context, verdicts)+ hidden |= batch_hidden+ survivors.extend(check.id for check in batch if check.id not in batch_hidden)+ hidden |= _checks_whose_latest_run_is_unreadable(team_id, survivors, context)+ return queryset.exclude(id__in=hidden)++def definition_reads_unreadable_subject(- team_id: int, check_type: str, config: dict[str, Any], context: DenialContext+ team_id: int, check_type: str, config: dict[str, Any], context: DenialContext, *, subject: SubjectRef | None = None) -> bool:"""Whether the definition a check would run next reads a subject beyond a caller's reach.@@ -251,12 +348,16 @@ def definition_reads_unreadable_subject("""if not check_type_reads_beyond_subject(check_type):return False- refs = referenced_subjects(team_id, check_type, config)+ try:+ refs = referenced_subjects(team_id, check_type, config, subject=subject)+ except Exception as err:+ capture_exception(err)+ return Trueif refs.related_subject is not None and not context.readable.contains(refs.related_subject.subject_type, refs.related_subject.subject_uuid):return True- if any(is_subject_denied(name, context.denied) for name in refs.names):+ if context.matcher.matches(refs.names):return Truereturn bool(unconfirmable_subject_names(refs.names, context.database))@@ -277,7 +378,8 @@ def unconfirmable_subject_names(names: tuple[str, ...], database: Database) -> s_REFERENCING_CHECK_TYPES: frozenset[str] = frozenset(str(spec.type_name)for spec in all_specs()- if type(spec).related_subject_ref is not CheckTypeSpec.related_subject_ref+ if spec.reads_beyond_subject+ or type(spec).related_subject_ref is not CheckTypeSpec.related_subject_refor type(spec).referenced_table_names is not CheckTypeSpec.referenced_table_names)@@ -310,7 +412,9 @@ class ReferencedSubjects:related_subject: SubjectIdentity | None-def referenced_subjects(team_id: int, check_type: str, config: dict[str, Any]) -> ReferencedSubjects:+def referenced_subjects(+ team_id: int, check_type: str, config: dict[str, Any], *, subject: SubjectRef | None = None+) -> ReferencedSubjects:"""Every warehouse name a check reads *besides* its declared subject.A ``relationships`` check names a second subject and a ``custom_sql`` query selects from arbitrary@@ -324,12 +428,15 @@ def referenced_subjects(team_id: int, check_type: str, config: dict[str, Any]) -if (related := spec.related_subject_ref(parsed))else None)- return ReferencedSubjects(names=tuple(spec.referenced_table_names(parsed)), related_subject=related_subject)+ names = spec.referenced_table_names(parsed, subject)+ return ReferencedSubjects(names=tuple(names), related_subject=related_subject)-def referenced_subject_names(team_id: int, check_type: str, config: dict[str, Any]) -> list[str]:+def referenced_subject_names(+ team_id: int, check_type: str, config: dict[str, Any], *, subject: SubjectRef | None = None+) -> list[str]:"""The names from :func:`referenced_subjects`, for callers that only report or match on them."""- referenced = referenced_subjects(team_id, check_type, config)+ referenced = referenced_subjects(team_id, check_type, config, subject=subject)names = list(referenced.names)if referenced.related_subject is not None:related = resolve_subject(@@ -340,7 +447,9 @@ def referenced_subject_names(team_id: int, check_type: str, config: dict[str, Anreturn names-def pin_referenced_subjects(team_id: int, check_type: str, config: dict[str, Any]) -> list[dict[str, str]] | None:+def pin_referenced_subjects(+ team_id: int, check_type: str, config: dict[str, Any], *, subject: SubjectRef | None = None+) -> list[dict[str, str]] | None:"""The identities of the subjects this run reads besides its own, to record alongside the run.Names cannot carry this. Deleting a warehouse object frees its name, so a recorded name starts@@ -356,16 +465,15 @@ def pin_referenced_subjects(team_id: int, check_type: str, config: dict[str, Anyrun by its type rather than reading an empty list as "read nothing"."""try:- spec = get_spec(check_type)- parsed = spec.parse_config(config)+ references = referenced_subjects(team_id, check_type, config, subject=subject)+ if not references.names and references.related_subject is None:+ return []backing_tables = data_modeling_facade.backing_table_ids_by_saved_query(team_id)pinned = [- subject- for name in spec.referenced_table_names(parsed)- if (subject := _pin_name(team_id, name, backing_tables)) is not None+ identity for name in references.names if (identity := _pin_name(team_id, name, backing_tables)) is not None]- if related := spec.related_subject_ref(parsed):- pinned.append(SubjectIdentity(subject_type=str(related[0]), subject_uuid=str(related[1])))+ if references.related_subject is not None:+ pinned.append(references.related_subject)except Exception as err:capture_exception(err)return None@@ -373,15 +481,21 @@ def pin_referenced_subjects(team_id: int, check_type: str, config: dict[str, Anydef _readable_subject_q(readable: ReadableSubjects) -> Q:- return Q(subject_type=SubjectType.TABLE, subject_uuid__in=readable.table_ids) | Q(- subject_type=SubjectType.VIEW, subject_uuid__in=readable.view_ids+ return (+ Q(subject_type=SubjectType.TABLE, subject_uuid__in=readable.table_ids)+ | Q(subject_type=SubjectType.VIEW, subject_uuid__in=readable.view_ids)+ | Q(subject_type=SubjectType.METRIC, subject_uuid__in=readable.metric_ids))def _readable_identities(readable: ReadableSubjects) -> list[dict[str, str]]:return [{_SUBJECT_TYPE_KEY: str(subject_type), _SUBJECT_UUID_KEY: str(subject_uuid)}- for subject_type, ids in ((SubjectType.TABLE, readable.table_ids), (SubjectType.VIEW, readable.view_ids))+ for subject_type, ids in (+ (SubjectType.TABLE, readable.table_ids),+ (SubjectType.VIEW, readable.view_ids),+ (SubjectType.METRIC, readable.metric_ids),+ )for subject_uuid in ids]@@ -401,12 +515,20 @@ def _checks_whose_latest_run_is_unreadable(return {check_id for check_id in unreadable if check_id is not None}-def _memoized_definition_verdict(- team_id: int, check_type: str, config: dict[str, Any], context: DenialContext, verdicts: dict[str, bool]+def memoized_definition_verdict(+ team_id: int,+ check_type: str,+ config: dict[str, Any],+ context: DenialContext,+ verdicts: dict[str, bool],+ subject: SubjectRef | None = None,) -> bool:- key = json.dumps([check_type, config], sort_keys=True, default=str)+ # The subject enters the key as its identity: serializing the whole ref would drag a metric's+ # parsed HogQL definition into the hash of every row that shares it.+ identity = [subject.subject_type, subject.subject_uuid] if subject is not None else None+ key = json.dumps([check_type, config, identity], sort_keys=True, default=str)if key not in verdicts:- verdicts[key] = definition_reads_unreadable_subject(team_id, check_type, config, context)+ verdicts[key] = definition_reads_unreadable_subject(team_id, check_type, config, context, subject=subject)return verdicts[key]diff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.pyindex e9300e4a8c64..c41bb17e995c 100644--- a/products/data_quality/backend/logic/subjects.py+++ b/products/data_quality/backend/logic/subjects.py@@ -1,13 +1,15 @@"""Resolve a check's subject id to something queryable.-The check row carries the subject as a foreign key (``saved_query`` or ``table``); resolution still+The check row carries the subject as a foreign key (``saved_query``, ``table`` or ``metric``); resolution stillgoes through the owning product's facade rather than traversing the FK, so model instances nevercross the product boundary. A subject that no longer resolves marks the check orphaned, and thedenormalized name is refreshed on every run so renames self-heal."""+from collections.abc import Collectionfrom uuid import UUID+from products.data_catalog.backend.facade import api as data_catalog_facadefrom 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@@ -26,9 +28,34 @@ def resolve_subject(team_id: int, subject_type: str, subject_uuid: str | UUID) -kind = SubjectType(subject_type)if kind is SubjectType.TABLE:return _resolve_table(team_id, subject_uuid)+ if kind is SubjectType.METRIC:+ return _resolve_metric(team_id, subject_uuid)return _resolve_view(team_id, subject_uuid)+def _resolve_metric(team_id: int, subject_uuid: str | UUID) -> SubjectRef:+ identifier = UUID(str(subject_uuid))+ return resolve_metric_subjects(team_id, [identifier])[identifier]+++def resolve_metric_subjects(team_id: int, metric_ids: Collection[UUID]) -> dict[UUID, SubjectRef]:+ reads = data_catalog_facade.metric_reads_for_ids(team_id, metric_ids)+ return {+ metric_id: SubjectRef(+ subject_type=SubjectType.METRIC,+ subject_uuid=str(metric_id),+ name=reads[metric_id].summary.name,+ queryable_name="",+ exists=True,+ definition_kind=reads[metric_id].summary.definition_kind,+ metric_definition=reads[metric_id].hogql_definition,+ )+ if metric_id in reads+ else _missing(SubjectType.METRIC, metric_id)+ for metric_id in metric_ids+ }++def resolve_subject_by_name(team_id: int, name: str) -> SubjectRef | None:"""The subject a query reaches under this name, or None when the name is no warehouse object.@@ -84,6 +111,8 @@ def subject_column_type(team_id: int, subject_type: str, subject_uuid: str | UUIif not column_name:return Nonekind = SubjectType(subject_type)+ if 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 {}diff --git a/products/data_quality/backend/logic/types/common.py b/products/data_quality/backend/logic/types/common.pyindex ea98dc24ccfe..227de0642a06 100644--- a/products/data_quality/backend/logic/types/common.py+++ b/products/data_quality/backend/logic/types/common.py@@ -5,9 +5,42 @@ the printer's backtick escaping is the only thing standing between a hostile colgenerated SQL."""+from math import isfinite+from typing import Self++from pydantic import Field, field_validator, model_validator+from posthog.hogql import astfrom ..contracts import SubjectRef+from ..spec import CheckConfig+++class BoundsConfig(CheckConfig):+ min: int | float | None = Field(default=None, allow_inf_nan=False, description="Minimum allowed value, inclusive.")+ max: int | float | None = Field(default=None, allow_inf_nan=False, description="Maximum allowed value, inclusive.")++ @field_validator("min", "max")+ @classmethod+ def _normalize_integral_bounds(cls, value: int | float | None) -> int | float | None:+ return int(value) if isinstance(value, float) and value.is_integer() else value++ @model_validator(mode="after")+ def _bounds_are_usable(self) -> Self:+ if self.min is None and self.max is None:+ raise ValueError("needs at least one of min or max")+ if self.min is not None and self.max is not None and self.min > self.max:+ raise ValueError(f"needs min <= max, got min={self.min} and max={self.max}")+ return self+++def within_bounds(observed: float | None, minimum: float | None, maximum: float | None) -> bool:+ # NaN compares False against every bound, so an unguarded comparison reads it as passing.+ if observed is None or not isfinite(observed):+ return False+ if minimum is not None and observed < minimum:+ return False+ return not (maximum is not None and observed > maximum)def subject_source(subject: SubjectRef) -> ast.JoinExpr:diff --git a/products/data_quality/backend/logic/types/custom_sql.py b/products/data_quality/backend/logic/types/custom_sql.pyindex 1cb16d70793e..e8c748208b72 100644--- a/products/data_quality/backend/logic/types/custom_sql.py+++ b/products/data_quality/backend/logic/types/custom_sql.py@@ -1,14 +1,15 @@-from pydantic import Field, field_validator+from pydantic import Fieldfrom posthog.hogql import astfrom posthog.hogql.errors import ExposedHogQLError-from posthog.hogql.metadata import get_table_namesfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.placeholders import find_placeholders-from ...facade.enums import CheckType+from ...facade.enums import CheckType, SubjectTypefrom ..contracts import CheckPlan, SubjectReffrom ..errors import CheckConfigError+from ..metric_query import bind_metric_query+from ..query_scope import referenced_table_names as query_table_namesfrom ..spec import CheckConfig, CheckTypeSpec@@ -18,31 +19,40 @@ def parse_failing_rows_query(query: str) -> ast.SelectQuery | ast.SelectSetQueryA UNION of selects is as good as one: the compiler aggregates over whatever this returns, so thefailure set can be assembled from several branches."""+ parsed = parse_custom_sql_query(query)++ found = find_placeholders(parsed)+ if found.has_filters or found.placeholder_fields or found.placeholder_expressions:+ raise CheckConfigError("A custom_sql check cannot use {placeholders} -- nothing supplies them.")+ return parsed+++def parse_custom_sql_query(query: str) -> ast.SelectQuery | ast.SelectSetQuery:try:- parsed = parse_select(query.rstrip(";").strip())+ return parse_select(query.rstrip(";").strip())except ExposedHogQLError as err:raise CheckConfigError(f"Could not parse the custom query: {err}")except Exception:raise CheckConfigError("Could not parse the custom query.")- found = find_placeholders(parsed)- if found.has_filters or found.placeholder_fields or found.placeholder_expressions:- raise CheckConfigError("A custom_sql check cannot use {placeholders} -- nothing supplies them.")- return parsed++def build_failing_rows(subject: SubjectRef | None, config: "CustomSqlConfig") -> ast.SelectQuery | ast.SelectSetQuery:+ if subject is None or subject.subject_type != SubjectType.METRIC:+ return parse_failing_rows_query(config.query)+ if subject.metric_definition is None:+ raise CheckConfigError("Metric checks require a live HogQL definition.")+ return bind_metric_query(config.query, subject.metric_definition)class CustomSqlConfig(CheckConfig):query: str = Field(min_length=1,- description="HogQL SELECT returning one row per failure. Passing means it returns nothing.",+ description=(+ "HogQL SELECT returning one row per failure. Passing means it returns nothing. "+ "Metric checks must use {metric} once as a relation."+ ),)- @field_validator("query")- @classmethod- def _is_a_select(cls, value: str) -> str:- parse_failing_rows_query(value)- return value-class CustomSqlSpec(CheckTypeSpec):"""A user-written HogQL SELECT whose returned rows are the failures.@@ -58,17 +68,21 @@ class CustomSqlSpec(CheckTypeSpec):type_name = CheckType.CUSTOM_SQLconfig_model = CustomSqlConfigrequires_column = False- description = "Fails on every row the custom HogQL SELECT returns."+ subject_types = frozenset({SubjectType.TABLE, SubjectType.VIEW, SubjectType.METRIC})+ reads_beyond_subject = True+ description = "Fails on every row the custom HogQL SELECT returns. Metric checks query the {metric} relation."- def referenced_table_names(self, config: CheckConfig) -> list[str]:+ def referenced_table_names(self, config: CheckConfig, subject: SubjectRef | None = None) -> list[str]:assert isinstance(config, CustomSqlConfig)- return get_table_names(parse_failing_rows_query(config.query))+ return query_table_names(build_failing_rows(subject, config))def build(self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None) -> CheckPlan:assert isinstance(config, CustomSqlConfig)- return CheckPlan(failing_rows=parse_failing_rows_query(config.query))+ failing_rows = build_failing_rows(subject, config)+ query_table_names(failing_rows)+ return CheckPlan(failing_rows=failing_rows)SPEC = CustomSqlSpec()diff --git a/products/data_quality/backend/logic/types/relationships.py b/products/data_quality/backend/logic/types/relationships.pyindex 13db238272f6..91c4ed1ca738 100644--- a/products/data_quality/backend/logic/types/relationships.py+++ b/products/data_quality/backend/logic/types/relationships.py@@ -1,3 +1,4 @@+from typing import Literalfrom uuid import UUIDfrom pydantic import Field@@ -12,7 +13,9 @@ from .common import column, diagnostic_of, one, subject_sourceclass RelationshipsConfig(CheckConfig):- to_subject_type: SubjectType = Field(description="Kind of catalog object holding the referenced values.")+ to_subject_type: Literal[SubjectType.TABLE, SubjectType.VIEW] = Field(+ description="Kind of catalog object holding the referenced values."+ )to_subject_uuid: UUID = Field(description="Id of the table or view holding the referenced values.")to_column: str = Field(min_length=1, description="Column holding the referenced values.")diff --git a/products/data_quality/backend/logic/types/row_count.py b/products/data_quality/backend/logic/types/row_count.pyindex 572492c5be12..c994fd292367 100644--- a/products/data_quality/backend/logic/types/row_count.py+++ b/products/data_quality/backend/logic/types/row_count.py@@ -1,29 +1,23 @@-from typing import Self--from pydantic import Field, model_validator+from pydantic import Fieldfrom posthog.hogql import astfrom ...facade.enums import CheckTypefrom ..contracts import CheckPlan, Evaluation, SubjectReffrom ..spec import CheckConfig, CheckTypeSpec-from .common import one, subject_source+from .common import BoundsConfig, one, subject_sourceROW_COUNT_ALIAS = "row_count"-class RowCountConfig(CheckConfig):+class RowCountConfig(BoundsConfig):+ # A row count is a whole number and never negative, so its bounds are too, and the published+ # config schema has to say so for an API or agent caller that has no other contract to read.+ # Narrowed here rather than on BoundsConfig, so a bounds check over a measured value can still+ # take a fractional one. The inherited normalizer still folds an integral float to an int.min: int | None = Field(default=None, ge=0, description="Fail if the table has fewer rows than this.")max: int | None = Field(default=None, ge=0, description="Fail if the table has more rows than this.")- @model_validator(mode="after")- def _bounds_are_usable(self) -> Self:- if self.min is None and self.max is None:- raise ValueError("needs at least one of min or max")- if self.min is not None and self.max is not None and self.min > self.max:- raise ValueError(f"needs min <= max, got min={self.min} and max={self.max}")- return self-class RowCountSpec(CheckTypeSpec):"""The one type that does not use zero-failing-rows semantics: it compares a count to bounds."""diff --git a/products/data_quality/backend/migrations/0009_metric_subject_and_check_schedules.py b/products/data_quality/backend/migrations/0009_metric_subject_and_check_schedules.pynew file mode 100644index 000000000000..08a9f95b2bf9--- /dev/null+++ b/products/data_quality/backend/migrations/0009_metric_subject_and_check_schedules.py@@ -0,0 +1,103 @@+# Generated by Django 5.2.17 on 2026-09-04 20:07+++from django.conf import settings+from django.db import migrations, models++from posthog.migration_helpers import AddConstraintNotValid++import products.data_quality.backend.facade.enums+import products.data_quality.backend.models.check+++class Migration(migrations.Migration):+ dependencies = [+ ("data_catalog", "0006_metric_name_partial_unique"),+ ("data_modeling", "0031_datamodelingjob_run_mode"),+ ("data_quality", "0008_alter_dataqualitycheck_team_and_more"),+ ("posthog", "1341_organization_uses_most_specific_access_resolution"),+ ("warehouse_sources", "0159_externaldatajob_destination_ids_and_more"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.RemoveConstraint(+ model_name="dataqualitycheck",+ name="quality_check_subject_binding",+ ),+ migrations.AddField(+ model_name="dataqualitycheck",+ name="metric",+ field=models.ForeignKey(+ blank=True,+ db_constraint=False,+ help_text="The data catalog metric this check evaluates. Exclusive with table and saved_query.",+ db_index=False,+ null=True,+ on_delete=products.data_quality.backend.models.check.orphan_check_on_subject_delete,+ related_name="+",+ to="data_catalog.metric",+ ),+ ),+ migrations.AlterField(+ model_name="dataqualitycheck",+ name="subject_type",+ field=models.CharField(+ choices=products.data_quality.backend.facade.enums.subject_type_choices,+ help_text="Kind of catalog object being checked: table, view, or metric. Kept so orphaned checks stay readable.",+ max_length=32,+ ),+ ),+ migrations.AlterField(+ model_name="dataqualitycheckrun",+ name="subject_type",+ field=models.CharField(+ choices=products.data_quality.backend.facade.enums.subject_type_choices, max_length=32+ ),+ ),+ migrations.AlterField(+ model_name="dataqualitysuiterun",+ name="subject_type",+ field=models.CharField(+ blank=True,+ choices=products.data_quality.backend.facade.enums.subject_type_choices,+ help_text="Set when the run targets exactly one subject.",+ max_length=32,+ ),+ ),+ migrations.AlterField(+ model_name="dataqualitysuiterun",+ name="trigger",+ field=models.CharField(+ choices=products.data_quality.backend.facade.enums.suite_run_trigger_choices,+ help_text="What started this run: manual, materialization, source_sync, or scheduled.",+ max_length=32,+ ),+ ),+ AddConstraintNotValid(+ model_name="dataqualitycheck",+ constraint=models.CheckConstraint(+ condition=models.Q(+ models.Q(("saved_query__isnull", False), ("table__isnull", False), _negated=True),+ models.Q(("metric__isnull", False), ("saved_query__isnull", False), _negated=True),+ models.Q(("metric__isnull", False), ("table__isnull", False), _negated=True),+ models.Q(+ ("saved_query__isnull", True),+ ("subject_type", products.data_quality.backend.facade.enums.SubjectType["VIEW"]),+ _connector="OR",+ ),+ models.Q(+ ("table__isnull", True),+ ("subject_type", products.data_quality.backend.facade.enums.SubjectType["TABLE"]),+ _connector="OR",+ ),+ models.Q(+ ("metric__isnull", True),+ ("subject_type", products.data_quality.backend.facade.enums.SubjectType["METRIC"]),+ _connector="OR",+ ),+ ),+ name="quality_check_subject_binding",+ ),+ ),+ ]diff --git a/products/data_quality/backend/migrations/0010_validate_metric_subject_binding.py b/products/data_quality/backend/migrations/0010_validate_metric_subject_binding.pynew file mode 100644index 000000000000..18362f8d4308--- /dev/null+++ b/products/data_quality/backend/migrations/0010_validate_metric_subject_binding.py@@ -0,0 +1,9 @@+from django.db import migrations++from posthog.migration_helpers import ValidateConstraint+++class Migration(migrations.Migration):+ dependencies = [("data_quality", "0009_metric_subject_and_check_schedules")]++ operations = [ValidateConstraint(model_name="dataqualitycheck", name="quality_check_subject_binding")]diff --git a/products/data_quality/backend/migrations/0011_metric_subject_index.py b/products/data_quality/backend/migrations/0011_metric_subject_index.pynew file mode 100644index 000000000000..5d14a768895c--- /dev/null+++ b/products/data_quality/backend/migrations/0011_metric_subject_index.py@@ -0,0 +1,40 @@+from django.db import migrations, models++from posthog.migration_helpers import CreateIndexConcurrently, SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [("data_quality", "0010_validate_metric_subject_binding")]++ operations = [+ migrations.SeparateDatabaseAndState(+ database_operations=[+ CreateIndexConcurrently(+ index_name="unique_quality_check_fp_metric",+ table_name="data_quality_dataqualitycheck",+ columns="(team_id, metric_id, fingerprint)",+ unique=True,+ where="WHERE metric_id IS NOT NULL AND (NOT deleted OR deleted IS NULL)",+ ),+ ],+ state_operations=[+ migrations.AddConstraint(+ model_name="dataqualitycheck",+ constraint=models.UniqueConstraint(+ condition=models.Q(metric__isnull=False)+ & (models.Q(deleted=False) | models.Q(deleted__isnull=True)),+ fields=("team", "metric", "fingerprint"),+ name="unique_quality_check_fp_metric",+ ),+ ),+ ],+ ),+ SafeAddIndexConcurrently(+ model_name="dataqualitycheck",+ index=models.Index(+ fields=["team", "metric"], condition=models.Q(metric__isnull=False), name="quality_check_metric_idx"+ ),+ ),+ ]diff --git a/products/data_quality/backend/migrations/max_migration.txt b/products/data_quality/backend/migrations/max_migration.txtindex 5c1882d8844f..9cd67febbe12 100644--- a/products/data_quality/backend/migrations/max_migration.txt+++ b/products/data_quality/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_alter_dataqualitycheck_team_and_more+0011_metric_subject_indexdiff --git a/products/data_quality/backend/models/check.py b/products/data_quality/backend/models/check.pyindex ce9c6d7fe421..0cce5af7dabe 100644--- a/products/data_quality/backend/models/check.py+++ b/products/data_quality/backend/models/check.py@@ -9,7 +9,14 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDModel-from ..facade.enums import CheckRunStatus, CheckSeverity, CreatedSource, SubjectStatus, SubjectType+from ..facade.enums import (+ CheckRunStatus,+ CheckSeverity,+ CreatedSource,+ SubjectStatus,+ SubjectType,+ subject_type_choices,+)# A check name is an addressable handle in `information_schema.data_quality_checks` and in agent# prose, so it follows the same bare-identifier discipline as a metric name.@@ -51,7 +58,7 @@ orphan_check_on_subject_delete.lazy_sub_objs = True # type: ignore[attr-definedclass DataQualityCheck(ModelActivityMixin, TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, DeletedMetaFields, UUIDModel):- """An assertion about a warehouse table or view, in the ``dbt test`` sense.+ """An assertion about a warehouse table, view, or data catalog metric.A check passes when its compiled query finds zero failing rows. The definition is the source oftruth here; ``fingerprint`` makes agent authoring idempotent (re-creating a semantically@@ -59,8 +66,8 @@ class DataQualityCheck(git-synced config file would round-trip against. Editing the assertion recomputes it in place:the check keeps its id, history, and latest status.- The subject is one of two foreign keys -- ``saved_query`` (views and matviews) or ``table``- (warehouse source tables) -- and never both. The data modeling Node for a subject is resolved at+ The subject is one of three foreign keys: ``saved_query`` (views and matviews), ``table``+ (warehouse source tables), or ``metric``. The data modeling Node for a subject is resolved attrigger time rather than referenced here: node rows are per-DAG structural records that DAG syncdeletes and recreates, so they cannot anchor a check's identity, and a table in no DAG has nonode at all. A hard-deleted subject nulls its FK (the check turns ``orphaned`` and is skipped);@@ -70,8 +77,7 @@ class DataQualityCheck(``last_status`` / ``last_run_at`` are denormalized from the newest ``DataQualityCheckRun`` soper-subject health is a single indexed read rather than a correlated subquery over run history.- Checks carry no cadence: they run when their subject's data changes (a sync completes, a- materialization runs) or on demand, never on a timer of their own.+ Checks run when their subject's data changes, on demand, or on a shared per-metric schedule."""# db_constraint=False on FKs to hot tables (posthog_team, posthog_user): a real FK constraint@@ -111,8 +117,8 @@ class DataQualityCheck(subject_type = models.CharField(max_length=32,- choices=[(t.value, t.value) for t in SubjectType],- help_text="Kind of catalog object being checked: table or view. Kept so orphaned checks stay readable.",+ choices=subject_type_choices,+ help_text="Kind of catalog object being checked: table, view, or metric. Kept so orphaned checks stay readable.",)saved_query = models.ForeignKey("data_modeling.DataWarehouseSavedQuery",@@ -132,6 +138,16 @@ class DataQualityCheck(related_name="+",help_text="The warehouse source table this check audits. Exclusive with saved_query.",)+ metric = models.ForeignKey(+ "data_catalog.Metric",+ on_delete=orphan_check_on_subject_delete,+ null=True,+ blank=True,+ db_constraint=False,+ db_index=False,+ related_name="+",+ help_text="The data catalog metric this check evaluates. Exclusive with table and saved_query.",+ )subject_name = models.CharField(max_length=400,help_text="Queryable name of the subject, refreshed on every run so renames self-heal.",@@ -211,8 +227,11 @@ class DataQualityCheck(name="quality_check_subject_binding",condition=(~models.Q(saved_query__isnull=False, table__isnull=False)- & ~models.Q(saved_query__isnull=False, subject_type=SubjectType.TABLE)- & ~models.Q(table__isnull=False, subject_type=SubjectType.VIEW)+ & ~models.Q(saved_query__isnull=False, metric__isnull=False)+ & ~models.Q(table__isnull=False, metric__isnull=False)+ & (models.Q(saved_query__isnull=True) | models.Q(subject_type=SubjectType.VIEW))+ & (models.Q(table__isnull=True) | models.Q(subject_type=SubjectType.TABLE))+ & (models.Q(metric__isnull=True) | models.Q(subject_type=SubjectType.METRIC))),),# Partial per FK: orphaned checks (both FKs null) are exempt on purpose, and so are@@ -228,6 +247,11 @@ class DataQualityCheck(condition=models.Q(table__isnull=False) & ACTIVE,name="unique_quality_check_fp_table",),+ models.UniqueConstraint(+ fields=["team", "metric", "fingerprint"],+ condition=models.Q(metric__isnull=False) & ACTIVE,+ name="unique_quality_check_fp_metric",+ ),# Partial on both counts: a blank name is the "address me by id" case, which many checks# share, and a deleted check keeps its name only as history -- holding the name against a# new check would make a delete irreversible for anyone who wants that name back.@@ -238,6 +262,11 @@ class DataQualityCheck(),]indexes = [+ models.Index(+ fields=["team", "metric"],+ condition=models.Q(metric__isnull=False),+ name="quality_check_metric_idx",+ ),models.Index(fields=["team", "saved_query"],condition=models.Q(saved_query__isnull=False),@@ -253,7 +282,7 @@ class DataQualityCheck(@propertydef subject_uuid(self) -> "uuid.UUID | None":"""Id of whichever subject FK is set; None once orphaned."""- return self.saved_query_id or self.table_id+ return self.saved_query_id or self.table_id or self.metric_iddef __str__(self) -> str:return self.name or f"{self.check_type} on {self.subject_name}"diff --git a/products/data_quality/backend/models/check_run.py b/products/data_quality/backend/models/check_run.pyindex c5dbd1268daf..585d929c21dc 100644--- a/products/data_quality/backend/models/check_run.py+++ b/products/data_quality/backend/models/check_run.py@@ -3,7 +3,13 @@ from django.db import modelsfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel-from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectType, SuiteRunStatus, SuiteRunTrigger+from ..facade.enums import (+ CheckRunStatus,+ CheckSeverity,+ SuiteRunStatus,+ subject_type_choices,+ suite_run_trigger_choices,+)class DataQualitySuiteRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):@@ -21,8 +27,8 @@ class DataQualitySuiteRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFietrigger = models.CharField(max_length=32,- choices=[(t.value, t.value) for t in SuiteRunTrigger],- help_text="What started this run: manual, materialization, or source_sync.",+ choices=suite_run_trigger_choices,+ help_text="What started this run: manual, materialization, source_sync, or scheduled.",)status = models.CharField(max_length=16,@@ -33,7 +39,7 @@ class DataQualitySuiteRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFiesubject_type = models.CharField(max_length=32,- choices=[(t.value, t.value) for t in SubjectType],+ choices=subject_type_choices,blank=True,help_text="Set when the run targets exactly one subject.",)@@ -97,7 +103,7 @@ class DataQualityCheckRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFie)# Denormalized from the check so history stays readable after the definition changes or goes away.- subject_type = models.CharField(max_length=32, choices=[(t.value, t.value) for t in SubjectType])+ subject_type = models.CharField(max_length=32, choices=subject_type_choices)subject_uuid = models.UUIDField()subject_name = models.CharField(max_length=400)# No choices, for the same reason as on the check itself: the registry owns the set of types.diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.pyindex 766f48a22a09..85f69ee775fe 100644--- a/products/data_quality/backend/presentation/serializers.py+++ b/products/data_quality/backend/presentation/serializers.py@@ -9,6 +9,7 @@ from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schema_field, extend_schema_serializerfrom rest_framework import serializersfrom rest_framework.exceptions import ErrorDetail+from rest_framework.settings import api_settingsfrom posthog.api.shared import UserBasicSerializer@@ -29,10 +30,10 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):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' (a synced warehouse table) or 'view' (a saved query).",+ help_text="Kind of catalog object being checked: 'table', 'view', or 'metric'.",)subject_uuid = serializers.SerializerMethodField(- help_text="Id of the table or view being checked -- the parent resource in the URL."+ help_text="Id of the table, view, or metric being checked, from the parent resource in the URL.")check_type = serializers.ChoiceField(choices=[(t.value, t.value) for t in CheckType],@@ -157,20 +158,18 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):return str(obj.subject_uuid) if obj.subject_uuid else Nonedef validate(self, attrs: dict) -> dict:- def resolved(field: str) -> str:- return attrs.get(field) or getattr(self.instance, field, None) or ""+ if self.instance is not None:+ return attrs# The subject comes from the URL: the viewset resolves the parent and passes it in context.- subject_type = self.context.get("subject_type") or getattr(self.instance, "subject_type", "")- subject_uuid = self.context.get("subject_uuid") or (self.instance.subject_uuid if self.instance else None)try:api.validate_check(self.context["get_team"](),- str(subject_type),- str(subject_uuid),- resolved("check_type"),- resolved("column_name"),- attrs.get("config", getattr(self.instance, "config", None) or {}),+ str(self.context.get("subject_type") or ""),+ str(self.context.get("subject_uuid") or ""),+ attrs.get("check_type") or "",+ attrs.get("column_name") or "",+ attrs.get("config") or {},)except (api.CheckConfigError, api.SubjectUnresolvableError, api.UnknownCheckTypeError) as err:raise serializers.ValidationError({"config": str(err)})@@ -183,13 +182,17 @@ class DataQualityCheckSerializer(serializers.ModelSerializer):team=self.context["get_team"](),check=instance,editor=getattr(request, "user", None) if request else None,+ authorize=self.context.get("authorize_check_edit"),**validated_data,)+ except (api.CheckConfigError, api.SubjectUnresolvableError, api.UnknownCheckTypeError) as err:+ raise serializers.ValidationError({"config": str(err)})except api.CheckEditConflict as conflict:# Rendered beside the offending fields rather than as a status code, so the editor can# keep the draft open and point at what to change.+ fields = conflict.fields or (api_settings.NON_FIELD_ERRORS_KEY,)raise serializers.ValidationError(- {field: ErrorDetail(str(conflict), code=conflict.code) for field in conflict.fields}+ {field: ErrorDetail(str(conflict), code=conflict.code) for field in fields})@@ -212,6 +215,9 @@ class DataQualityOverviewCheckSerializer(DataQualityCheckSerializer):subject_schema_id = serializers.SerializerMethodField(help_text="Warehouse source schema of the table this check audits, or null when the subject is a view.")+ subject_metric_name = serializers.SerializerMethodField(+ help_text="Current metric name for opening its Tests tab, or null for other subjects."+ )class Meta(DataQualityCheckSerializer.Meta):fields = [@@ -219,6 +225,7 @@ class DataQualityOverviewCheckSerializer(DataQualityCheckSerializer):"subject_node_id","subject_source_id","subject_schema_id",+ "subject_metric_name",]def _location(self, obj: DataQualityCheck) -> api.SubjectLocation:@@ -238,6 +245,10 @@ class DataQualityOverviewCheckSerializer(DataQualityCheckSerializer):def get_subject_schema_id(self, obj: DataQualityCheck) -> str | None:return self._location(obj).schema_id+ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_subject_metric_name(self, obj: DataQualityCheck) -> str | None:+ return self._location(obj).metric_name+@extend_schema_serializer(component_name="DataQualityCheckRun")class DataQualityCheckRunSerializer(serializers.ModelSerializer):@@ -314,9 +325,9 @@ class DataQualitySuiteRunSerializer(serializers.ModelSerializer):status = serializers.CharField(read_only=True, help_text="running, completed, failed, or empty (nothing matched the trigger).")- trigger = serializers.CharField(read_only=True, help_text="manual, materialization, or source_sync.")+ trigger = serializers.CharField(read_only=True, help_text="manual, materialization, source_sync, or scheduled.")subject_type = serializers.SerializerMethodField(- help_text="'table' or 'view' when the run targets exactly one subject, including a run of a "+ help_text="'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.")@@ -351,8 +362,8 @@ class DataQualitySuiteRunSerializer(serializers.ModelSerializer):class SubjectHealthSerializer(serializers.Serializer):"""Per-subject rollup, the same rule the information_schema.data_quality_health table uses."""- subject_type = serializers.CharField(help_text="'table' or 'view'.")- subject_uuid = serializers.CharField(help_text="Id of the table or view.")+ subject_type = serializers.CharField(help_text="'table', 'view', or 'metric'.")+ subject_uuid = serializers.CharField(help_text="Id of the table, view, or metric.")health = serializers.CharField(help_text="failing (an error-severity check failed), erroring (a check could not run), ""warn (only warn-severity failures), healthy, or unknown (nothing has run yet)."diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pyindex 1cb6601e8291..ab2ad1442623 100644--- a/products/data_quality/backend/presentation/views.py+++ b/products/data_quality/backend/presentation/views.py@@ -7,10 +7,10 @@ serialize the result. Nothing here runs a check -- every trigger hands off to Tea suite-run handle to poll."""-import jsonfrom collections import defaultdictfrom collections.abc import Callable, Sequence-from typing import ClassVar, cast+from functools import cached_property+from typing import TYPE_CHECKING, ClassVar, castfrom uuid import UUIDfrom django.db.models import QuerySet@@ -19,8 +19,8 @@ from django.shortcuts import get_object_or_404from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_viewfrom rest_framework import mixins, status, viewsets-from rest_framework.exceptions import PermissionDenied-from rest_framework.permissions import SAFE_METHODS+from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.permissions import SAFE_METHODS, BasePermission, IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer@@ -30,6 +30,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, User+from posthog.permissions import APIScopePermission, TeamMemberAccessPermission, get_authenticator_scopesfrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixin@@ -51,6 +52,29 @@ from .serializers import (_RECENT_RUNS_LIMIT = 50_LAST_RUN_FIELDS = ("last_status", "last_run_at", "last_succeeded_at", "failing_since")+if TYPE_CHECKING:+ from rest_framework.permissions import _SupportsHasPermission+++class _DataQualitySubjectPermission(BasePermission):+ def has_permission(self, request: Request, view: APIView) -> bool:+ if not isinstance(view, _QualityGatedViewSet):+ return False+ if 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:+ return (+ isinstance(view, _QualityGatedViewSet)+ and isinstance(obj, DataQualityCheck | DataQualitySuiteRun)+ and obj.team_id == view.team_id+ and self.has_permission(request, view)+ )+class _QualityGatedViewSet(TeamAndOrgViewSetMixin):"""The gating every data quality surface shares, whether or not it is nested under a subject.@@ -66,6 +90,30 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):team: TeamQUERY_GATED_ACTIONS: ClassVar[frozenset[str]] = frozenset()+ def dangerously_get_permissions(self) -> list["_SupportsHasPermission"]:+ if self.action not in self.QUERY_GATED_ACTIONS:+ raise NotImplementedError()+ return [+ IsAuthenticated(),+ APIScopePermission(),+ TeamMemberAccessPermission(),+ _DataQualitySubjectPermission(),+ *(permission() for permission in self.permission_classes),+ ]++ def _filter_queryset_by_access_level(self, queryset: QuerySet) -> QuerySet:+ # Checks and suite runs answer to the subject gate rather than the generic object filter, so+ # both bypass it. A check is filtered by visible_check_queryset, which every listing path+ # routes through and which applies the subject predicate itself; a suite run is filtered here.+ if self.action != "list" or queryset.model not in (DataQualityCheck, DataQualitySuiteRun):+ return super()._filter_queryset_by_access_level(queryset)+ if queryset.model is DataQualityCheck or not self._can_be_object_denied():+ return queryset+ context = self._denial_context()+ return queryset.exclude(api.unreadable_suites_q(context)).exclude(+ api.suites_backing_unreadable_runs_q(self.team_id, context)+ )+def initial(self, request: Request, *args, **kwargs) -> None:super().initial(request, *args, **kwargs)self._require_flag()@@ -91,10 +139,40 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):if not self.user_access_control.check_access_level_for_resource("query", "viewer"):raise PermissionDenied("You need query access to work with data quality checks.")+ @cached_property+ def _authorized_types(self) -> dict[bool, frozenset[SubjectType]]:+ return {}++ @cached_property+ def _definition_verdicts(self) -> dict[str, bool]:+ return {}++ @cached_property+ def _metric_subjects(self) -> dict[UUID, api.SubjectRef]:+ return {}++ def _authorized_subject_types(self, *, write: bool = False) -> frozenset[SubjectType]:+ if write not in self._authorized_types:+ self._authorized_types[write] = api.authorized_subject_types(+ self.user_access_control,+ get_authenticator_scopes(self.request.successful_authenticator),+ write=write,+ route_scope=self.scope_object,+ )+ return self._authorized_types[write]++ @cached_property+ def _writable_subjects(self) -> api.ReadableSubjects:+ return api.writable_subjects(+ self._denial_context(), self.user_access_control, allowed=self._authorized_subject_types(write=True)+ )+def _can_be_object_denied(self) -> bool:# Shared with the information_schema loaders, so the two surfaces agree on which callers a# gate applies to as well as on what it decides.- return api.can_be_object_denied(self.user_access_control)+ return api.can_be_object_denied(self.user_access_control) or self._authorized_subject_types() != frozenset(+ SubjectType+ )def _denial_context(self) -> api.DenialContext:"""The subjects this caller may read, and the names they are denied. Once per request.@@ -105,10 +183,13 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):cached = getattr(self, "_denial_context_cache", None)if cached is None:try:- cached = api.caller_denial_context(- self.team,- cast(User, self.request.user),- user_access_control=self.user_access_control,+ cached = api.restrict_subject_types(+ api.caller_denial_context(+ self.team,+ cast(User, self.request.user),+ user_access_control=self.user_access_control,+ ),+ self._authorized_subject_types(),)except Exception as err:# Building the snapshot walks every saved query; one malformed definition must not@@ -140,7 +221,9 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):return runsreturn api.without_denied_runs(runs, self._denial_context())- def _require_referenced_subject_access(self, check_type: str, config: dict) -> None:+ def _require_referenced_subject_access(+ self, check_type: str, config: dict, *, subject: api.SubjectIdentity | None = None+ ) -> None:"""403 a definition that reads a subject the caller cannot be shown to be allowed.The parent is not the only subject a check reads: a relationships check names a second@@ -153,19 +236,29 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):"""if not self._can_be_object_denied():return- cache: dict[str, bool] = getattr(self, "_definition_verdicts", {})- self._definition_verdicts = cache- key = json.dumps([check_type, config], sort_keys=True, default=str)- if key not in cache:- cache[key] = api.definition_reads_unreadable_subject(- self.team_id, check_type, config, self._denial_context()- )- if cache[key]:+ resolved = self._definition_subject(subject) if subject is not None else None+ if api.memoized_definition_verdict(+ self.team_id, check_type, config, self._denial_context(), self._definition_verdicts, resolved+ ):raise PermissionDenied("You don't have access to a table or view this check reads.")+ def _definition_subject(self, identity: api.SubjectIdentity) -> api.SubjectRef | None:+ if identity.subject_type != SubjectType.METRIC:+ return None+ identifier = UUID(identity.subject_uuid)+ if identifier not in self._metric_subjects:+ self._metric_subjects.update(api.resolve_metric_subjects(self.team_id, [identifier]))+ return self._metric_subjects[identifier]++ @staticmethod+ def _check_identity(check: DataQualityCheck) -> api.SubjectIdentity | None:+ if check.subject_uuid is None:+ return None+ return api.SubjectIdentity(subject_type=check.subject_type, subject_uuid=str(check.subject_uuid))+class _SubjectScopedViewSet(_QualityGatedViewSet):- """Adds the parent-subject gate for viewsets nested under a warehouse saved query or table."""+ """Adds the parent-subject gate for viewsets nested under a catalog subject."""subject_type: ClassVar[SubjectType]subject_field: ClassVar[str]@@ -177,6 +270,28 @@ class _SubjectScopedViewSet(_QualityGatedViewSet):def initial(self, request: Request, *args, **kwargs) -> None:super().initial(request, *args, **kwargs)self._require_parent_subject_access()+ self._require_subject_id()++ def _require_subject_id(self) -> None:+ """404 a parent segment that is not a uuid, before it reaches a UUIDField filter.++ 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.++ 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)def _require_parent_subject_access(self) -> None:"""403 a parent this caller may not read -- for every action, including list.@@ -190,6 +305,10 @@ class _SubjectScopedViewSet(_QualityGatedViewSet):returnif 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.")_EDIT_DESCRIPTION = (@@ -204,7 +323,7 @@ _EDIT_DESCRIPTION = (update=extend_schema(description=_EDIT_DESCRIPTION),partial_update=extend_schema(description=_EDIT_DESCRIPTION),)-class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsets.ModelViewSet):+class _BaseCheckViewSet(_SubjectScopedViewSet, viewsets.ModelViewSet):"""CRUD for one subject's checks, plus the actions that run them and report on them."""DETAIL_VISIBILITY_ACTIONS = frozenset({"retrieve", "destroy"})@@ -216,7 +335,9 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsedef safely_get_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:# The parent lookup filters by the subject FK; deleted checks stay hidden.- queryset = queryset.filter(team_id=self.team_id, deleted=False)+ queryset = api.live_subject_checks(queryset.filter(team_id=self.team_id, deleted=False)).select_related(+ "created_by", "owner"+ )if check_type := self.request.query_params.get("check_type"):queryset = queryset.filter(check_type=check_type)return queryset.order_by("-created_at")@@ -231,7 +352,7 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsereturn querysetif not self._can_be_object_denied():return queryset- return queryset.exclude(id__in=self._hidden_check_ids(list(queryset)))+ return api.visible_check_queryset(self.team_id, queryset, self._denial_context())def safely_get_object(self, queryset: QuerySet[DataQualityCheck]) -> DataQualityCheck:lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field@@ -259,7 +380,11 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewseserializer = 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 {})+ self._require_referenced_subject_access(+ data["check_type"],+ data.get("config") or {},+ subject=self._parent_identity,+ )optional = {key: data[key]@@ -305,18 +430,24 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsesetattr(check, field, None)def perform_update(self, serializer: BaseSerializer) -> None:+ serializer.context["authorize_check_edit"] = lambda current: self._authorize_check_edit(+ current, serializer.validated_data+ )+ updated_check = cast(DataQualityCheck, serializer.save())+ if self._last_run_is_hidden(updated_check):+ self._redact_last_run(updated_check)++ def _authorize_check_edit(self, check: DataQualityCheck, changes: dict) -> None:+ subject = self._check_identity(check)+ self._require_referenced_subject_access(check.check_type, check.config or {}, subject=subject)# The candidate definition, not the stored one: an edit that points the check at a new# relationships target or rewrites its custom SQL has to clear that subject too, before it# is saved and the worker starts running it.- check = cast(DataQualityCheck, serializer.instance)- redact_last_run = self._last_run_is_hidden(check)- data = serializer.validated_dataself._require_referenced_subject_access(- data.get("check_type", check.check_type), data.get("config", check.config) or {}+ changes.get("check_type", check.check_type),+ changes.get("config", check.config) or {},+ subject=subject,)- updated_check = cast(DataQualityCheck, serializer.save())- if redact_last_run:- self._redact_last_run(updated_check)def perform_destroy(self, instance: DataQualityCheck) -> None:api.soft_delete_check(instance)@@ -331,7 +462,11 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse# The parent 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)+ 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.suite_run = api.start_check_suite(@@ -352,11 +487,7 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsedef 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.- if self._can_be_object_denied():- 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)+ self._require_enabled_check_access()suite_run = api.start_check_suite(team=self.team,user=cast(User, request.user),@@ -365,6 +496,13 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse)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)},@@ -374,7 +512,11 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsecheck = 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)+ self._require_referenced_subject_access(+ check.check_type,+ check.config,+ subject=self._parent_identity,+ )runs = self._readable_runs(DataQualityCheckRun.objects.for_team(self.team_id).filter(quality_check=check)).select_related("quality_check")@@ -415,24 +557,29 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse)@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(), many=True).data)+ return Response(CheckTypeSerializer(api.list_check_types(self.subject_type), many=True).data)-class SavedQueryCheckViewSet(_BaseCheckViewSet):+class SavedQueryCheckViewSet(_BaseCheckViewSet, AccessControlViewSetMixin):scope_object = "warehouse_view"subject_type = SubjectType.VIEWsubject_field = "saved_query"-class TableCheckViewSet(_BaseCheckViewSet):+class TableCheckViewSet(_BaseCheckViewSet, AccessControlViewSetMixin):scope_object = "warehouse_table"subject_type = SubjectType.TABLEsubject_field = "table"+class MetricCheckViewSet(_BaseCheckViewSet):+ scope_object = "data_catalog"+ subject_type = SubjectType.METRIC+ subject_field = "metric"++class _BaseSuiteRunViewSet(_SubjectScopedViewSet,- AccessControlViewSetMixin,mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet,@@ -495,7 +642,7 @@ def _parent_id_parameter(name: str, description: str) -> Callable[[type], type]:@_parent_id_parameter("saved_query_id", "Id of the saved query whose suite runs these are.")-class SavedQuerySuiteRunViewSet(_BaseSuiteRunViewSet):+class SavedQuerySuiteRunViewSet(_BaseSuiteRunViewSet, AccessControlViewSetMixin):scope_object = "warehouse_view"subject_type = SubjectType.VIEWsubject_field = "saved_query"@@ -503,16 +650,35 @@ class SavedQuerySuiteRunViewSet(_BaseSuiteRunViewSet):@_parent_id_parameter("table_id", "Id of the warehouse table whose suite runs these are.")-class TableSuiteRunViewSet(_BaseSuiteRunViewSet):+class TableSuiteRunViewSet(_BaseSuiteRunViewSet, AccessControlViewSetMixin):scope_object = "warehouse_table"subject_type = SubjectType.TABLEsubject_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(- _QualityGatedViewSet,- AccessControlViewSetMixin,+ _ProjectQualityViewSet,mixins.ListModelMixin,viewsets.GenericViewSet,):@@ -524,22 +690,20 @@ class DataQualityCheckOverviewViewSet("""QUERY_GATED_ACTIONS = frozenset({"list", "health"})- scope_object = "warehouse_objects"serializer_class = DataQualityOverviewCheckSerializerqueryset = DataQualityCheck.objects.unscoped()- _subject_locations: dict[api.SubjectKey, api.SubjectLocation] = {}def safely_get_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:# Orphans are excluded: their subject is gone, so there is no page to link to, nothing to# run, and no rollup to sit under. The run history they left behind stays queryable.- return (- queryset.filter(team_id=self.team_id, deleted=False)+ # 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"))-- def get_serializer_context(self) -> dict:- return {**super().get_serializer_context(), "subject_locations": self._subject_locations}+ return queryset.select_related("created_by", "owner") if self.action == "list" else querysetdef list(self, request: Request, *args, **kwargs) -> Response:queryset = self.filter_queryset(self.get_queryset())@@ -547,8 +711,8 @@ class DataQualityCheckOverviewViewSet(checks = list(queryset) if page is None else page# Resolved once for the page, so linking to a subject costs two queries rather than one per# check. Anything the batch cannot resolve stays absent and renders as plain text.- self._subject_locations = api.subject_locations(self.team_id, checks)- serializer = self.get_serializer(checks, many=True)+ 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]:@@ -559,7 +723,7 @@ class DataQualityCheckOverviewViewSet(queryset = super().filter_queryset(queryset)if not self._can_be_object_denied():return queryset- return queryset.exclude(id__in=self._hidden_check_ids(list(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.",@@ -592,8 +756,7 @@ class DataQualityCheckOverviewViewSet(class DataQualityRunViewSet(- _QualityGatedViewSet,- AccessControlViewSetMixin,+ _ProjectQualityViewSet,mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet,@@ -606,7 +769,6 @@ class DataQualityRunViewSet("""QUERY_GATED_ACTIONS = frozenset({"list", "retrieve", "create"})- scope_object = "warehouse_objects"serializer_class = DataQualitySuiteRunSerializerqueryset = DataQualitySuiteRun.objects.unscoped()@@ -644,9 +806,13 @@ class DataQualityRunViewSet(serializer.is_valid(raise_exception=True)requested = [str(check_id) for check_id in serializer.validated_data.get("check_ids") or []]- runnable = DataQualityCheck.objects.for_team(self.team_id).filter(deleted=False, enabled=True)+ runnable = api.live_subject_checks(+ DataQualityCheck.objects.for_team(self.team_id).filter(deleted=False, enabled=True)+ )if requested:runnable = runnable.filter(id__in=requested)+ elif self._can_be_object_denied():+ runnable = api.readable_check_subjects(runnable, self._writable_subjects)checks = self._authorized_checks(list(runnable), named=bool(requested))if not checks:# An empty selection cannot be handed to the worker: it reads as no selector at all and@@ -672,16 +838,39 @@ class DataQualityRunViewSet(check would let a table renamed since its last run be run against, and its pass/fail androw counts read back."""+ allowed_types = self._authorized_subject_types(write=True)+ if named and any(check.subject_type not in allowed_types for check in checks):+ raise PermissionDenied("You don't have permission to run a check on this subject.")+ checks = [check for check in checks if check.subject_type in allowed_types]if not self._can_be_object_denied():return checks- readable = self._denial_context().readable+ readable = self._writable_subjects+ self._metric_subjects.update(+ api.resolve_metric_subjects(+ self.team_id,+ {+ check.metric_id+ for check in checks+ if check.metric_id is not None and readable.contains(check.subject_type, check.subject_uuid)+ },+ )+ )allowed = []for check in checks:if not readable.contains(check.subject_type, check.subject_uuid):if named:raise PermissionDenied("You don't have access to a table or view this check reads.")continue- self._require_referenced_subject_access(check.check_type, check.config)+ try:+ self._require_referenced_subject_access(+ check.check_type,+ check.config,+ subject=self._check_identity(check),+ )+ except PermissionDenied:+ if named:+ raise+ continueallowed.append(check)return alloweddiff --git a/products/data_quality/backend/temporal/activities/cleanup.py b/products/data_quality/backend/temporal/activities/cleanup.pyindex eaf45f37de5a..eb8b48f3ad58 100644--- a/products/data_quality/backend/temporal/activities/cleanup.py+++ b/products/data_quality/backend/temporal/activities/cleanup.py@@ -14,6 +14,7 @@ from temporalio import activityfrom posthog.dataclasses import frozenfrom posthog.temporal.common.logger import get_logger+from products.data_catalog.backend.facade import api as data_catalog_facadefrom products.data_modeling.backend.facade import api as data_modeling_facadefrom products.warehouse_sources.backend.facade import api as warehouse_facade@@ -128,13 +129,18 @@ class _LiveSubjects:table_ids: frozenset[UUID]view_ids: frozenset[UUID]+ metric_ids: frozenset[UUID] = frozenset()- def alive_q(self, table_field: str = "subject_uuid", view_field: str = "subject_uuid") -> Q:+ def alive_q(+ self, table_field: str = "subject_uuid", view_field: str = "subject_uuid", metric_field: str = "subject_uuid"+ ) -> Q:# An explicit predicate per known kind, so a row of a kind this sweep does not know reads as# dead rather than as alive by default. Runs and suites denormalize the subject into one# column; a check carries it as whichever of its two foreign keys is set.- return Q(**{"subject_type": SubjectType.TABLE, f"{table_field}__in": self.table_ids}) | Q(- **{"subject_type": SubjectType.VIEW, f"{view_field}__in": self.view_ids}+ return (+ Q(**{"subject_type": SubjectType.TABLE, f"{table_field}__in": self.table_ids})+ | Q(**{"subject_type": SubjectType.VIEW, f"{view_field}__in": self.view_ids})+ | Q(**{"subject_type": SubjectType.METRIC, f"{metric_field}__in": self.metric_ids}))@@ -171,11 +177,12 @@ def _live_subjects(team_id: int) -> _LiveSubjects:return _LiveSubjects(table_ids=frozenset(warehouse_facade.all_queryable_table_names(team_id)),view_ids=frozenset(UUID(view_id) for view_id in data_modeling_facade.all_saved_query_names(team_id)),+ metric_ids=frozenset(data_catalog_facade.live_metric_ids(team_id)),)def _delete_dead_checks(team_id: int, live: _LiveSubjects, grace: datetime) -> int:- alive = live.alive_q(table_field="table_id", view_field="saved_query_id")+ alive = live.alive_q(table_field="table_id", view_field="saved_query_id", metric_field="metric_id")dead = DataQualityCheck.objects.for_team(team_id).filter(created_at__lt=grace).exclude(alive)return _delete_in_batches(dead).get(DataQualityCheck._meta.label, 0)diff --git a/products/data_quality/backend/temporal/activities/prepare_check_suite.py b/products/data_quality/backend/temporal/activities/prepare_check_suite.pyindex 88cad5904549..4406832c83c8 100644--- a/products/data_quality/backend/temporal/activities/prepare_check_suite.py+++ b/products/data_quality/backend/temporal/activities/prepare_check_suite.py@@ -10,6 +10,7 @@ from posthog.temporal.common.logger import get_loggerfrom products.data_modeling.backend.facade import api as data_modeling_facadefrom ...facade.enums import SubjectType+from ...logic.checks import live_subject_checksfrom ...logic.flags import is_data_quality_checks_enabled_for_team_idfrom ...models import DataQualityCheck, DataQualitySuiteRunfrom ..contracts import PreparedSuite, RunCheckSuiteInputs@@ -72,15 +73,24 @@ def _single_subject_fields(inputs: RunCheckSuiteInputs) -> dict[str, str]:Leaving them out lets the model's own column defaults stand, which is what "this run has no onesubject" looks like on the row."""- if len(inputs.saved_query_ids) == 1 and not inputs.table_ids:- return {"subject_type": SubjectType.VIEW, "subject_uuid": inputs.saved_query_ids[0]}- if len(inputs.table_ids) == 1 and not inputs.saved_query_ids:- return {"subject_type": SubjectType.TABLE, "subject_uuid": inputs.table_ids[0]}+ subjects = [+ (subject_type, subject_uuid)+ for subject_type, identifiers in (+ (SubjectType.VIEW, inputs.saved_query_ids),+ (SubjectType.TABLE, inputs.table_ids),+ (SubjectType.METRIC, inputs.metric_ids),+ )+ for subject_uuid in identifiers+ ]+ if len(subjects) == 1 and not inputs.node_ids and not inputs.check_ids:+ return {"subject_type": subjects[0][0], "subject_uuid": subjects[0][1]}return {}def _select_checks(inputs: RunCheckSuiteInputs) -> list[str]:- runnable = DataQualityCheck.objects.for_team(inputs.team_id).filter(enabled=True, deleted=False)+ runnable = live_subject_checks(+ DataQualityCheck.objects.for_team(inputs.team_id).filter(enabled=True, deleted=False)+ )if inputs.check_ids:runnable = runnable.filter(id__in=inputs.check_ids)@@ -88,11 +98,13 @@ def _select_checks(inputs: RunCheckSuiteInputs) -> list[str]:saved_query_ids = list(inputs.saved_query_ids)if inputs.node_ids:saved_query_ids += data_modeling_facade.get_saved_query_ids_for_nodes(inputs.team_id, inputs.node_ids)- if not saved_query_ids and not inputs.table_ids:+ if not saved_query_ids and not inputs.table_ids and not inputs.metric_ids:return []subject_filter = models.Q(saved_query_id__in=saved_query_ids)if inputs.table_ids:subject_filter |= models.Q(table_id__in=inputs.table_ids)+ if inputs.metric_ids:+ subject_filter |= models.Q(metric_id__in=inputs.metric_ids)runnable = runnable.filter(subject_filter)return [str(check_id) for check_id in runnable.values_list("id", flat=True)]diff --git a/products/data_quality/backend/temporal/contracts.py b/products/data_quality/backend/temporal/contracts.pyindex 12b09f9bc0b9..e0ef1c1236d0 100644--- a/products/data_quality/backend/temporal/contracts.py+++ b/products/data_quality/backend/temporal/contracts.py@@ -24,6 +24,7 @@ class RunCheckSuiteInputs:trigger: SuiteRunTriggersaved_query_ids: list[str] = dataclasses.field(default_factory=list)table_ids: list[str] = dataclasses.field(default_factory=list)+ metric_ids: list[str] = dataclasses.field(default_factory=list)check_ids: list[str] = dataclasses.field(default_factory=list)node_ids: list[str] = dataclasses.field(default_factory=list)suite_run_id: str | None = Nonediff --git a/products/data_quality/backend/tests/test_admin.py b/products/data_quality/backend/tests/test_admin.pynew file mode 100644index 000000000000..bdbf35229e91--- /dev/null+++ b/products/data_quality/backend/tests/test_admin.py@@ -0,0 +1,85 @@+from posthog.test.base import BaseTest++from django.urls import reverse++from parameterized import parameterized++from posthog.admin import register_all_admin++from products.data_catalog.backend.facade.api import upsert_metric+from products.data_quality.backend.facade.enums import CheckType, SubjectType, SuiteRunTrigger+from products.data_quality.backend.facade.models import DataQualityCheck, DataQualitySuiteRun++register_all_admin()+++class TestDataQualityAdmin(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.user.is_staff = True+ self.user.save()+ self.client.force_login(self.user)+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="orders",+ description="Order count",+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS orders"},+ )+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MANUAL+ )+ check = DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.METRIC,+ metric_id=metric.id,+ subject_name="orders",+ check_type=CheckType.CUSTOM_SQL,+ fingerprint="a" * 64,+ )+ self.objects = {+ "dataqualitycheck": check,+ "dataqualitysuiterun": suite_run,+ }++ @parameterized.expand([("dataqualitycheck", "metric"), ("dataqualitysuiterun", None)])+ def test_staff_can_render_lists_and_forms_without_a_team_scope(+ self, model_name: str, scoped_field: str | None+ ) -> None:+ for action in ("changelist", "add", "change"):+ with self.subTest(action=action):+ url = reverse(+ f"admin:data_quality_{model_name}_{action}",+ args=[self.objects[model_name].pk] if action == "change" else None,+ )+ response = self.client.get(url)+ self.assertEqual(response.status_code, 200)++ if action == "change" and scoped_field:+ related_id = getattr(self.objects[model_name], f"{scoped_field}_id")+ field = response.context["adminform"].form.fields[scoped_field]+ self.assertEqual(field.clean(related_id).pk, related_id)++ @parameterized.expand([("dataqualitycheck",)])+ def test_staff_can_save_changes_without_a_team_scope(self, model_name: str) -> None:+ instance = self.objects[model_name]+ payload = {"team": self.team.id, "subject_type": SubjectType.METRIC, "enabled": "on"}+ if isinstance(instance, DataQualityCheck):+ payload.update(+ metric=str(instance.metric_id),+ subject_name=instance.subject_name,+ subject_status=instance.subject_status,+ check_type=instance.check_type,+ severity=instance.severity,+ created_source=instance.created_source,+ description="Check the order count",+ config="{}",+ tags="[]",+ )++ response = self.client.post(reverse(f"admin:data_quality_{model_name}_change", args=[instance.pk]), payload)++ self.assertEqual(response.status_code, 302)+ instance.refresh_from_db()+ if isinstance(instance, DataQualityCheck):+ self.assertEqual(instance.description, "Check the order count")diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pyindex e512357753cd..94fa5562d9af 100644--- a/products/data_quality/backend/tests/test_api.py+++ b/products/data_quality/backend/tests/test_api.py@@ -1,3 +1,5 @@+from types import SimpleNamespace+from typing import TYPE_CHECKINGfrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -14,20 +16,290 @@ from rest_framework.test import APIRequestFactoryfrom posthog.constants import AvailableFeaturefrom products.access_control.backend.models.access_control import AccessControl+from products.data_catalog.backend.facade.models import Metricfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade import apifrom products.data_quality.backend.facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectTypefrom products.data_quality.backend.logic import checks as checks_logic+from 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 DataQualitySuiteRunSerializerfrom products.data_quality.backend.presentation.views import SavedQueryCheckViewSetfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.table import DataWarehouseTable+if TYPE_CHECKING:+ from posthog.models.team import Team+START_SUITE = "products.data_quality.backend.logic.checks.sync_connect"FLAG = "products.data_quality.backend.presentation.views.is_data_quality_checks_enabled"+class TestMetricCheckAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.metric = Metric.objects.for_team(self.team.id).create(+ team=self.team,+ name="signups",+ definition={"kind": "HogQLQuery", "query": "SELECT 10 AS signups"},+ referenced_table_names=[],+ )+ 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"+ flag = patch(FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def _create(self) -> dict:+ response = self.client.post(+ f"{self.url}/",+ {"check_type": "custom_sql", "config": {"query": "SELECT * FROM {metric} WHERE signups < 100"}},+ )+ assert response.status_code == 201, response.content+ return response.json()++ @parameterized.expand(+ [+ ("checks_list", "get", "checks/"),+ ("checks_health", "get", "checks/health/"),+ ("checks_run_all", "post", "checks/run_all/"),+ ("suite_runs_list", "get", "check_suite_runs/"),+ ]+ )+ 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)++ assert response.status_code == status.HTTP_404_NOT_FOUND, response.content++ def test_metric_children_do_not_expose_access_control_actions(self) -> None:+ check = self._create()+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team,+ trigger="manual",+ subject_type=SubjectType.METRIC,+ subject_uuid=self.metric.id,+ )+ for parent, identifier in ((self.url, check["id"]), (self.suites_url, suite.id)):+ for action in (+ "access_controls",+ "resource_access_controls",+ "global_access_controls",+ "users_with_access",+ ):+ response = self.client.get(f"{parent}/{identifier}/{action}/")+ assert response.status_code == 404, response.content++ def test_metric_check_authoring_and_overview(self) -> None:+ check = 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"]+ edited = self.client.patch(+ f"{self.url}/{check['id']}/", {"config": {"query": "SELECT * FROM {metric} WHERE signups < 50"}}+ )+ assert edited.status_code == 200+ assert edited.json()["fingerprint"] != check["fingerprint"]+ self.metric.name = "registrations"+ self.metric.save(update_fields=["name"])+ row = self.client.get(f"/api/projects/{self.team.id}/data_quality_checks/").json()["results"][0]+ assert row["subject_metric_name"] == "registrations"+ assert "definition" not in row and "values" not in row+ assert self.client.delete(f"{self.url}/{check['id']}/").status_code == 204++ def test_a_metric_that_leaves_hogql_still_takes_presentation_edits(self) -> None:+ check = self._create()+ self.metric.definition = {"kind": "MarkdownDefinition", "content": "Signups per day"}+ self.metric.save(update_fields=["definition"])++ paused = self.client.patch(f"{self.url}/{check['id']}/", {"enabled": False, "description": "paused"})++ assert paused.status_code == status.HTTP_200_OK, paused.content+ assert paused.json()["enabled"] is False+ assert paused.json()["description"] == "paused"+ # The assertion itself still cannot be rewritten against a definition that is no longer there.+ rewritten = self.client.patch(+ f"{self.url}/{check['id']}/", {"config": {"query": "SELECT * FROM {metric} WHERE signups < 10"}}+ )+ assert rewritten.status_code == status.HTTP_400_BAD_REQUEST, rewritten.content+ assert rewritten.json()["detail"] == "Metric checks require a live HogQL definition."++ def test_metric_manual_run_and_nested_history(self) -> None:+ check = self._create()+ with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):+ response = self.client.post(f"{self.url}/{check['id']}/run/")+ assert response.status_code == 200, response.content+ suite = response.json()+ assert suite["subject_uuid"] == str(self.metric.id)+ assert self.client.get(f"{self.suites_url}/{suite['id']}/").status_code == 200+ assert self.client.get(f"{self.suites_url}/{suite['id']}/check_runs/").json() == []+ assert self.client.get(f"{self.url}/{check['id']}/runs/").json() == []++ def test_catalog_denial_hides_metric_checks_across_surfaces(self) -> None:+ self._create()+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource="data_catalog",+ organization_member=self.organization_membership,+ access_level="none",+ )+ cache.clear()+ assert self.client.get(f"{self.url}/").status_code == 403+ assert self.client.get(f"{self.suites_url}/").status_code == 403+ assert self.client.get(f"/api/projects/{self.team.id}/data_quality_checks/").json()["results"] == []++ @parameterized.expand([("check_assertion", False), ("metric_definition", True)])+ def test_saved_expandable_sources_are_hidden_and_cannot_be_edited_or_run(+ self, _name: str, in_metric_definition: bool+ ) -> None:+ created = self._create()+ source = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS total"}+ )+ expandable_source = "<HogQLQuery query='SELECT * FROM orders' />"+ if in_metric_definition:+ self.metric.definition = {"kind": "HogQLQuery", "query": f"SELECT * FROM {expandable_source}"}+ self.metric.save(update_fields=["definition"])+ else:+ DataQualityCheck.objects.for_team(self.team.id).filter(id=created["id"]).update(+ config={"query": f"SELECT * FROM {{metric}} JOIN {expandable_source} ON 1 = 1"}+ )+ check = DataQualityCheck.objects.for_team(self.team.id).get(id=created["id"])+ original_config = check.config+ original_fingerprint = check.fingerprint+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_view",+ resource_id=str(source.id),+ organization_member=self.organization_membership,+ access_level="none",+ )+ cache.clear()++ for url in (f"{self.url}/", f"/api/projects/{self.team.id}/data_quality_checks/"):+ listed = self.client.get(url)+ assert listed.status_code == status.HTTP_200_OK, listed.content+ assert listed.json()["results"] == []+ assert listed.json()["count"] == 0++ assert self.client.get(f"{self.url}/{check.id}/").status_code == status.HTTP_403_FORBIDDEN+ edited = self.client.patch(f"{self.url}/{check.id}/", {"enabled": False})+ assert edited.status_code == status.HTTP_403_FORBIDDEN, edited.content+ with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):+ nested_run = self.client.post(f"{self.url}/{check.id}/run/")+ project_run = self.client.post(+ f"/api/projects/{self.team.id}/data_quality_runs/", {"check_ids": [str(check.id)]}+ )+ assert nested_run.status_code == status.HTTP_403_FORBIDDEN, nested_run.content+ assert project_run.status_code == status.HTTP_403_FORBIDDEN, project_run.content+ assert not DataQualitySuiteRun.objects.for_team(self.team.id).exists()+ check.refresh_from_db()+ assert check.config == original_config+ assert check.fingerprint == original_fingerprint+ assert check.enabled++ def test_nested_cte_cannot_expose_history_after_metric_source_changes(self) -> None:+ source = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS total"}+ )+ self.metric.definition = {+ "kind": "HogQLQuery",+ "query": "SELECT * FROM orders UNION ALL "+ "SELECT * FROM (WITH orders AS (SELECT 123 AS total) SELECT * FROM orders)",+ }+ self.metric.referenced_table_names = ["orders"]+ self.metric.save(update_fields=["definition", "referenced_table_names"])+ response = self.client.post(+ f"{self.url}/",+ {+ "check_type": "custom_sql",+ "config": {"query": "SELECT * FROM {metric}"},+ },+ )+ assert response.status_code == 201, response.content+ check = DataQualityCheck.objects.for_team(self.team.id).get(id=response.json()["id"])+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team,+ trigger="manual",+ created_by=self.user,+ subject_type=SubjectType.METRIC,+ subject_uuid=self.metric.id,+ )+ with patch(+ "products.data_quality.backend.logic.runner.execute_hogql_query",+ return_value=SimpleNamespace(columns=["failure_count", "observed_value"], results=[[2, 2]]),+ ):+ assert run_check(check, suite, self.team).status == CheckRunStatus.FAILED+ self.metric.definition = {"kind": "HogQLQuery", "query": "SELECT 1 AS total"}+ self.metric.referenced_table_names = []+ self.metric.save(update_fields=["definition", "referenced_table_names"])+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_view",+ resource_id=str(source.id),+ organization_member=self.organization_membership,+ access_level="none",+ )+ cache.clear()++ with patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda name, *args, **kwargs: name == "hogql-warehouse-access-control",+ ):+ for url in (f"{self.url}/{check.id}/runs/", f"{self.suites_url}/{suite.id}/check_runs/"):+ history = self.client.get(url)+ assert history.status_code == 200, history.content+ assert history.json() == []++ @parameterized.expand(+ [+ ("run", "POST", False),+ ("runs", "GET", False),+ ("run_all", "POST", False),+ ("run", "POST", True),+ ("runs", "GET", True),+ ("run_all", "POST", True),+ ]+ )+ def test_restricted_member_can_run_and_read_metric_checks(self, action: str, method: str, denied: bool) -> None:+ check = self._create()+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ if denied:+ source = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="restricted_source", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check["id"]).update(+ config={"query": "SELECT * FROM {metric} JOIN restricted_source ON 1 = 1"}+ )+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_view",+ resource_id=str(source.id),+ organization_member=self.organization_membership,+ access_level="none",+ )+ warehouse_ac = patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda name, *a, **k: name == "hogql-warehouse-access-control",+ )+ warehouse_ac.start()+ self.addCleanup(warehouse_ac.stop)+ cache.clear()+ 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}/")+ assert response.status_code == (403 if denied else 200), response.content++class TestCheckViewSetScopes(SimpleTestCase):@parameterized.expand([@@ -269,6 +541,52 @@ class TestDataQualityCheckAPI(APIBaseTest):check.refresh_from_db()assert check.name == ""+ @parameterized.expand([("transient_contention", 1, True), ("sustained_contention", 5, False)])+ def test_an_edit_retries_a_definition_that_keeps_moving_only_so_often(+ self, _name: str, moves: int, saved: bool+ ) -> None:+ check = self._create_check(column_name="total")+ build_candidate = checks_logic._candidate_definition+ remaining = moves++ def move_the_definition(+ team: "Team", current: DataQualityCheck, requested: dict[str, object]+ ) -> checks_logic._CandidateDefinition:+ nonlocal remaining+ if remaining:+ remaining -= 1+ DataQualityCheck.objects.for_team(team.id).filter(id=current.id).update(fingerprint=uuid4().hex)+ return build_candidate(team, current, requested)++ with patch.object(checks_logic, "_candidate_definition", side_effect=move_the_definition) as candidate:+ response = self.client.patch(f"{self.url}/{check.id}/", {"description": "why this matters"})++ check.refresh_from_db()+ if saved:+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert check.description == "why this matters"+ return+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["code"] == "concurrent_edit"+ assert response.json()["attr"] is None+ assert response.json()["detail"]+ assert candidate.call_count == checks_logic._MAX_EDIT_ATTEMPTS+ assert check.description == ""++ def test_an_edit_the_compiler_could_never_run_is_a_config_field_error(self) -> None:+ check = self._create_check()++ response = self.client.patch(+ f"{self.url}/{check.id}/",+ {"check_type": CheckType.CUSTOM_SQL, "column_name": "", "config": {"query": "SELECT ("}},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "config"+ check.refresh_from_db()+ assert check.check_type == CheckType.NOT_NULL+ assert check.column_name == "customer_id"+def test_a_definition_freed_by_deletion_becomes_a_new_check(self) -> None:# The old check keeps its own id and history; reusing the definition must not resurrect it.first = self._create_check()@@ -394,7 +712,15 @@ class TestDataQualityCheckAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKby_type = {row["check_type"]: row for row in response.json()}- assert set(by_type) == {t.value for t in CheckType}+ assert set(by_type) == {+ "not_null",+ "unique",+ "accepted_values",+ "relationships",+ "row_count",+ "freshness",+ "custom_sql",+ }assert by_type["accepted_values"]["config_schema"]["required"] == ["values"]assert by_type["row_count"]["requires_column"] is False@@ -625,9 +951,11 @@ class TestDataQualityCheckAPI(APIBaseTest):last_succeeded_at=ran_at,failing_since=ran_at,)+ url = f"{self._checks_url(allowed.id)}/{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()- url = f"{self._checks_url(allowed.id)}/{check.id}"edited = self.client.patch(url + "/", {"check_type": CheckType.NOT_NULL, "column_name": "id", "config": {}})history = self.client.get(f"{url}/runs/")@@ -796,14 +1124,15 @@ class TestDataQualityCheckAPI(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDENassert DataQualityCheck.objects.for_team(self.team.id).count() == 0- def test_editing_a_check_to_read_a_denied_subject_writes_nothing(self) -> None:+ @parameterized.expand([("patch",), ("put",)])+ def test_editing_a_check_to_read_a_denied_subject_writes_nothing(self, method: str) -> None:# The stored definition cleared the denial; the candidate one has to clear it too, or an edit# is the way to point a visible check at a table the member cannot read.allowed = self._make_view("customers")check = self._create_check(url=self._checks_url(allowed.id), column_name="id")self._deny_the_view()- response = self.client.patch(+ response = getattr(self.client, method)(f"{self._checks_url(allowed.id)}/{check.id}/",{"check_type": CheckType.CUSTOM_SQL, "column_name": "", "config": {"query": "SELECT 1 FROM orders"}},)@@ -812,6 +1141,77 @@ class TestDataQualityCheckAPI(APIBaseTest):check.refresh_from_db()assert check.check_type == CheckType.NOT_NULL+ @parameterized.expand([("patch",), ("put",), ("presentation",)])+ 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),+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT 1 FROM orders"},+ )+ original_fingerprint = check.fingerprint+ self._deny_the_view()+ changes = (+ {"enabled": False}+ if method == "presentation"+ else {"check_type": CheckType.CUSTOM_SQL, "column_name": "", "config": {"query": "SELECT 1"}}+ )++ response = getattr(self.client, "patch" if method == "presentation" else method)(+ f"{self._checks_url(allowed.id)}/{check.id}/", changes+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ check.refresh_from_db()+ assert check.config == {"query": "SELECT 1 FROM orders"}+ assert check.fingerprint == original_fingerprint+ assert check.enabled++ 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),+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT 1 FROM customers"},+ )+ concurrent_config = {"query": "SELECT 1 FROM orders"}+ concurrent_fingerprint = api.compute_fingerprint(+ subject_type=check.subject_type,+ subject_uuid=str(check.subject_uuid),+ check_type=check.check_type,+ column_name=check.column_name,+ config=concurrent_config,+ )+ self._deny_the_view()+ build_candidate = checks_logic._candidate_definition+ definition_changed = False++ def replace_definition_before_lock(+ team: "Team", current: DataQualityCheck, requested: dict[str, object]+ ) -> checks_logic._CandidateDefinition:+ nonlocal definition_changed+ if not definition_changed:+ DataQualityCheck.objects.for_team(team.id).filter(id=current.id).update(+ config=concurrent_config, fingerprint=concurrent_fingerprint+ )+ definition_changed = True+ return build_candidate(team, current, requested)++ 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}/",+ {"config": {"query": "SELECT 1"}, "description": "proposed change"},+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ check.refresh_from_db()+ assert check.config == concurrent_config+ assert check.fingerprint == concurrent_fingerprint+ assert check.description == ""+ assert check.definition_author is None+def _suite_with_two_runs(self, allowed: DataWarehouseSavedQuery) -> DataQualitySuiteRun:suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=allowed.iddiff --git a/products/data_quality/backend/tests/test_cleanup.py b/products/data_quality/backend/tests/test_cleanup.pyindex e171ea20d569..a62011317f0a 100644--- a/products/data_quality/backend/tests/test_cleanup.py+++ b/products/data_quality/backend/tests/test_cleanup.py@@ -12,6 +12,7 @@ from django.test.utils import CaptureQueriesContextfrom parameterized import parameterized+from products.data_catalog.backend.facade.api import upsert_metricfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.enums import (CheckRunStatus,@@ -220,10 +221,48 @@ class TestRetentionSweep(BaseTest):assert DataQualityCheck.objects.unscoped().filter(id=check.id).exists()assert DataQualityCheckRun.objects.unscoped().filter(id=run.id).exists()+ @parameterized.expand([("live", False, 1, True), ("deleted", True, 1, False), ("recent", True, 0, True)])+ def test_metric_lifecycle_cleans_history_after_grace(+ self, _name: str, deleted: bool, age_days: int, survives: bool+ ) -> None:+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="signups",+ description="Signups",+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS signups"},+ )+ check = DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.METRIC,+ metric_id=metric.id,+ subject_name=metric.name,+ check_type=CheckType.CUSTOM_SQL,+ fingerprint=uuid4().hex,+ )+ self._age(DataQualityCheck, check, age_days)+ suite = self._suite(age_days=age_days, subject_type=SubjectType.METRIC, subject_uuid=metric.id)+ run = self._run(+ age_days=age_days,+ quality_check=check,+ suite_run=suite,+ subject_type=SubjectType.METRIC,+ subject_uuid=metric.id,+ )+ if deleted:+ metric.deleted = True+ metric.save(update_fields=["deleted"])+ _cleanup()+ assert DataQualityCheck.objects.for_team(self.team.id).filter(pk=check.pk).exists() == survives+ assert DataQualityCheckRun.objects.for_team(self.team.id).filter(pk=run.pk).exists() == survives+ assert DataQualitySuiteRun.objects.for_team(self.team.id).filter(pk=suite.pk).exists() == survives+def test_rows_with_an_unknown_subject_type_are_treated_as_dead(self) -> None:suite = self._suite(age_days=1, subject_type=SubjectType.VIEW, subject_uuid=self.view.id)run = self._run(age_days=1, suite_run=suite)- DataQualityCheck.objects.unscoped().filter(id=self.check.id).update(subject_type="future_subject")+ DataQualityCheck.objects.unscoped().filter(id=self.check.id).update(+ subject_type="future_subject", saved_query_id=None+ )DataQualityCheckRun.objects.unscoped().filter(id=run.id).update(subject_type="future_subject")DataQualitySuiteRun.objects.unscoped().filter(id=suite.id).update(subject_type="future_subject")diff --git a/products/data_quality/backend/tests/test_compiler.py b/products/data_quality/backend/tests/test_compiler.pyindex a103ccafaff0..6d0ad8f1d72b 100644--- a/products/data_quality/backend/tests/test_compiler.py+++ b/products/data_quality/backend/tests/test_compiler.py@@ -2,13 +2,15 @@ import pytestfrom parameterized import parameterized+from products.data_catalog.backend.facade.contracts import HogQLMetricDefinitionfrom products.data_quality.backend.facade.enums import CheckType, SubjectTypefrom products.data_quality.backend.logic.compiler import compile_checkfrom products.data_quality.backend.logic.contracts import Evaluation, SubjectReffrom products.data_quality.backend.logic.errors import CheckConfigError, SubjectUnresolvableError-from products.data_quality.backend.logic.registry import UnknownCheckTypeError, all_specs, get_spec+from products.data_quality.backend.logic.registry import UnknownCheckTypeError, all_specs, get_spec, list_check_typesfrom products.data_quality.backend.logic.serialization import compute_fingerprint, from_config_entry, to_config_entryfrom products.data_quality.backend.logic.spec import CheckTypeSpec, NoConfig+from products.data_quality.backend.logic.types.custom_sql import CustomSqlConfig, CustomSqlSpecORDERS = SubjectRef(SubjectType.VIEW, "1cd4a1ef-0000-0000-0000-000000000001", "orders", "orders", exists=True)CUSTOMERS = SubjectRef(SubjectType.TABLE, "1cd4a1ef-0000-0000-0000-000000000002", "customers", "customers", True)@@ -46,6 +48,202 @@ def _compile(check_type, column_name, config, related=None):class TestCheckCompiler:+ @pytest.mark.parametrize("subject_type", [SubjectType.METRIC, SubjectType.TABLE, SubjectType.VIEW])+ @pytest.mark.parametrize(+ ("query", "references", "has_cte"),+ [+ (+ "SELECT * FROM {metric} UNION ALL "+ "SELECT * FROM (WITH orders AS (SELECT 123 AS total) SELECT * FROM orders)",+ ["orders"],+ True,+ ),+ (+ "WITH metric_output AS (SELECT * FROM {metric}) "+ "SELECT * FROM metric_output UNION ALL SELECT * FROM metric_output",+ ["orders"],+ True,+ ),+ (+ "WITH metric_output AS (SELECT * FROM {metric}), orders AS (SELECT 123 AS total) "+ "SELECT * FROM metric_output JOIN orders ON 1 = 1",+ ["orders"],+ True,+ ),+ (+ "WITH orders AS (SELECT * FROM {metric}) SELECT * FROM orders",+ ["orders"],+ True,+ ),+ (+ "SELECT * FROM {metric} JOIN (SELECT 1 AS total) AS other ON total IN (SELECT total FROM customers)",+ ["customers", "orders"],+ False,+ ),+ (+ "SELECT * FROM {metric} UNION ALL SELECT * FROM customers",+ ["customers", "orders"],+ False,+ ),+ ],+ )+ def test_custom_sql_references_respect_cte_scope(+ self, subject_type: SubjectType, query: str, references: list[str], has_cte: bool+ ) -> None:+ subject = SubjectRef(+ subject_type,+ "1cd4a1ef-0000-0000-0000-000000000003",+ "orders",+ "orders",+ exists=True,+ metric_definition=HogQLMetricDefinition(query="SELECT * FROM orders", values={}),+ )+ config = CustomSqlConfig(+ query=query if subject_type == SubjectType.METRIC else query.replace("{metric}", "(SELECT * FROM orders)")+ )++ if subject_type == SubjectType.METRIC and has_cte:+ with pytest.raises(CheckConfigError, match="cannot use CTEs"):+ CustomSqlSpec().referenced_table_names(config, subject)+ return+ assert sorted(CustomSqlSpec().referenced_table_names(config, subject)) == references++ @parameterized.expand(+ [+ (+ "hogqlx_relation",+ SubjectType.TABLE,+ "SELECT * FROM <HogQLQuery query='SELECT * FROM customers' />",+ "SELECT * FROM orders",+ ),+ (+ "hogqlx_join",+ SubjectType.VIEW,+ "SELECT * FROM orders JOIN <HogQLQuery query='SELECT * FROM customers' /> ON 1 = 1",+ "SELECT * FROM orders",+ ),+ (+ "hogqlx_cte",+ SubjectType.VIEW,+ "WITH failures AS (SELECT * FROM <HogQLQuery query='SELECT * FROM customers' />) "+ "SELECT * FROM failures",+ "SELECT * FROM orders",+ ),+ (+ "hogqlx_metric_definition",+ SubjectType.METRIC,+ "SELECT * FROM {metric}",+ "SELECT * FROM <HogQLQuery query='SELECT * FROM customers' />",+ ),+ (+ "hogqlx_metric_check",+ SubjectType.METRIC,+ "SELECT * FROM {metric} JOIN <HogQLQuery query='SELECT * FROM customers' /> ON 1 = 1",+ "SELECT * FROM orders",+ ),+ (+ "table_function",+ SubjectType.TABLE,+ "SELECT * FROM numbers(10)",+ "SELECT * FROM orders",+ ),+ ]+ )+ def test_custom_sql_rejects_unenumerable_table_expressions(+ self, _name: str, subject_type: SubjectType, query: str, metric_query: str+ ) -> None:+ subject = SubjectRef(+ subject_type,+ "1cd4a1ef-0000-0000-0000-000000000003",+ "orders",+ "orders",+ exists=True,+ metric_definition=HogQLMetricDefinition(query=metric_query, values={}),+ )+ spec = CustomSqlSpec()+ config = CustomSqlConfig(query=query)++ with pytest.raises(CheckConfigError, match="table expression"):+ spec.referenced_table_names(config, subject)+ with pytest.raises(CheckConfigError, match="table expression"):+ compile_check(check_type=CheckType.CUSTOM_SQL, subject=subject, column_name="", config={"query": query})++ def test_custom_sql_is_the_only_metric_check_type(self) -> None:+ """Catches registry filtering custom SQL out of the metric check catalog."""+ assert {entry.check_type for entry in list_check_types("metric")} == {CheckType.CUSTOM_SQL}+ for kind in (SubjectType.TABLE, SubjectType.VIEW):+ assert len(list_check_types(kind)) == 7+ assert {entry.check_type for entry in list_check_types(kind)} == set(CheckType)+ with pytest.raises(UnknownCheckTypeError, match="metric_value"):+ _compile("metric_value", "", {"min": 1})++ def test_compiles_metric_custom_sql_through_the_row_query_path(self) -> None:+ """Catches the compiler rejecting metrics before custom SQL can bind their definition."""+ metric = SubjectRef(+ SubjectType.METRIC,+ "1cd4a1ef-0000-0000-0000-000000000003",+ "signups",+ "",+ exists=True,+ metric_definition=HogQLMetricDefinition(+ query="SELECT count() AS signups FROM events WHERE event = {event_name}",+ values={"event_name": "signup"},+ ),+ )++ compiled = compile_check(+ check_type=CheckType.CUSTOM_SQL,+ subject=metric,+ column_name="",+ config={"query": "SELECT * FROM {metric} WHERE signups < 100"},+ )++ assert compiled.printed_query == (+ "SELECT count() AS failure_count, count() AS observed_value "+ "FROM (SELECT * FROM (SELECT count() AS signups FROM events WHERE equals(event, 'signup')) "+ "WHERE less(signups, 100))"+ )++ def test_metric_custom_sql_hides_invalid_check_parser_details_during_compilation(self) -> None:+ """Catches Pydantic parsing a metric check before the binder can provide its stable error."""+ metric = SubjectRef(+ SubjectType.METRIC,+ "1cd4a1ef-0000-0000-0000-000000000003",+ "signups",+ "",+ exists=True,+ metric_definition=HogQLMetricDefinition(query="SELECT count() AS signups FROM events", values={}),+ )++ with pytest.raises(CheckConfigError, match="^Could not parse the metric custom_sql query\\.$"):+ compile_check(+ check_type=CheckType.CUSTOM_SQL,+ subject=metric,+ column_name="",+ config={"query": "SELECT * FORM {metric}"},+ )++ def test_metric_custom_sql_hides_invalid_check_parser_details_during_subject_validation(self) -> None:+ """Catches authoring validation leaking parser details before binding a metric check."""+ metric = SubjectRef(+ SubjectType.METRIC,+ "1cd4a1ef-0000-0000-0000-000000000003",+ "signups",+ "",+ exists=True,+ metric_definition=HogQLMetricDefinition(query="SELECT count() AS signups FROM events", values={}),+ )+ spec = get_spec(CheckType.CUSTOM_SQL)+ config = spec.validate({"query": "SELECT * FORM {metric}"}, "")++ with pytest.raises(CheckConfigError, match="^Could not parse the metric custom_sql query\\.$"):+ spec.referenced_table_names(config, metric)++ def test_table_custom_sql_keeps_its_existing_invalid_query_error(self) -> None:+ """Catches deferring metric parsing from changing table and view custom-SQL validation."""+ with pytest.raises(CheckConfigError):+ _compile(CheckType.CUSTOM_SQL, "", {"query": "SELECT * FORM orders"})+@parameterized.expand([(@@ -176,6 +374,15 @@ class TestCheckCompiler:("missing_column", CheckType.NOT_NULL, "", {}),("row_count_without_bounds", CheckType.ROW_COUNT, "", {}),("row_count_inverted_bounds", CheckType.ROW_COUNT, "", {"min": 10, "max": 1}),+ ("row_count_negative_min", CheckType.ROW_COUNT, "", {"min": -5}),+ ("row_count_negative_max", CheckType.ROW_COUNT, "", {"max": -1}),+ ("row_count_fractional_bound", CheckType.ROW_COUNT, "", {"min": 1.5}),+ (+ "relationships_to_metric",+ CheckType.RELATIONSHIPS,+ "customer_id",+ {**RELATIONSHIPS_CONFIG, "to_subject_type": "metric"},+ ),("custom_sql_not_a_select", CheckType.CUSTOM_SQL, "", {"query": "drop table orders"}),("custom_sql_with_placeholder",@@ -212,6 +419,7 @@ class TestCheckCompiler:# is derived from the config model rather than written by hand, so it cannot drift from# what parse_config actually accepts.for spec in all_specs():+ assert isinstance(spec, CheckTypeSpec)schema = spec.json_schemaassert schema["type"] == "object"assert schema["additionalProperties"] is False, f"{spec.type_name} silently ignores unknown keys"@@ -229,6 +437,18 @@ class TestCheckCompiler:class TestCheckSerialization:+ @parameterized.expand(+ [+ ("integer", {"min": 1}, {"min": 1, "max": None}),+ ("integral_float_min", {"min": 1.0}, {"min": 1, "max": None}),+ ("integral_float_max", {"max": 2.0}, {"min": None, "max": 2}),+ ("integral_float_bounds", {"min": 1.0, "max": 2.0}, {"min": 1, "max": 2}),+ ]+ )+ def test_row_count_bounds_preserve_existing_fingerprint(self, _name: str, config: dict, expected: dict) -> None:+ normalized = _normalized(CheckType.ROW_COUNT, "", config)+ assert _fingerprint_for(normalized) == _fingerprint_for(expected)+@parameterized.expand([(check_type,) for check_type in CheckType])def test_config_entry_round_trips(self, check_type) -> None:check = {diff --git a/products/data_quality/backend/tests/test_compiler_execution.py b/products/data_quality/backend/tests/test_compiler_execution.pyindex 9b0b176c56b8..221b23b79fa6 100644--- a/products/data_quality/backend/tests/test_compiler_execution.py+++ b/products/data_quality/backend/tests/test_compiler_execution.py@@ -6,10 +6,12 @@ from parameterized import parameterizedfrom posthog.hogql.query import execute_hogql_query+from products.data_catalog.backend.facade.contracts import HogQLMetricDefinitionfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.enums import CheckType, SubjectTypefrom products.data_quality.backend.logic.compiler import compile_checkfrom products.data_quality.backend.logic.contracts import CompiledCheck, SubjectRef+from products.data_quality.backend.logic.errors import CheckConfigError_STRING = {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)"}_INT = {"hogql": "IntegerDatabaseField", "clickhouse": "Int64"}@@ -173,6 +175,38 @@ class TestCompiledCheckExecution(ClickhouseTestMixin, APIBaseTest):assert self._execute(compiled.query).results[0][0] == 4+ def test_metric_rejects_later_ctes_that_capture_sources_in_clickhouse(self) -> None:+ metric = SubjectRef(+ SubjectType.METRIC,+ "1cd4a1ef-0000-0000-0000-000000000003",+ "event_count",+ "",+ exists=True,+ metric_definition=HogQLMetricDefinition(+ query="SELECT count() AS total FROM events WHERE event = '__metric_cte_review_synthetic__'",+ values={},+ ),+ )+ baseline = compile_check(+ check_type=CheckType.CUSTOM_SQL,+ subject=metric,+ column_name="",+ config={"query": "SELECT * FROM {metric}"},+ )+ assert self._execute(baseline.printed_failing_rows_query).results == [(0,)]++ with self.assertRaisesRegex(CheckConfigError, "cannot use CTEs"):+ captured = compile_check(+ check_type=CheckType.CUSTOM_SQL,+ subject=metric,+ column_name="",+ config={+ "query": "WITH metric_output AS (SELECT * FROM {metric}), events AS (SELECT 123 AS total) "+ "SELECT metric_output.total FROM metric_output JOIN events ON 1 = 1"+ },+ )+ self._execute(captured.printed_failing_rows_query)+@parameterized.expand([("not_null", CheckType.NOT_NULL, "customer_id", {}, None, _NULL_CUSTOMER_ROW),diff --git a/products/data_quality/backend/tests/test_information_schema.py b/products/data_quality/backend/tests/test_information_schema.pyindex b02b880173a4..4943fca90b4c 100644--- a/products/data_quality/backend/tests/test_information_schema.py+++ b/products/data_quality/backend/tests/test_information_schema.py@@ -3,17 +3,27 @@ from uuid import uuid4from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import patch+from django.core.cache import cachefrom django.db import DatabaseError, connectionfrom django.test.utils import CaptureQueriesContextfrom parameterized import parameterized+from posthog.schema import CachedHogQLQueryResponse, CacheMissResponse, HogQLQuery+from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.query import execute_hogql_query+from posthog.constants import AvailableFeature+from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Team+from posthog.models.utils import generate_random_token_personal, hash_key_value+from products.access_control.backend.models.access_control import AccessControl+from products.data_catalog.backend.facade.models import Metricfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.api import record_check_runfrom products.data_quality.backend.facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectType@@ -97,6 +107,146 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):assert rows == [("orders_status_accepted", "orders", "accepted_values", '{"values": ["paid"]}', "error")]+ @parameterized.expand([("data_quality_checks",), ("data_quality_check_runs",), ("data_quality_health",)])+ def test_catalog_denial_hides_metric_definitions_history_and_health(self, table: str) -> None:+ metric = Metric.objects.for_team(self.team.id).create(+ team=self.team,+ name="signups",+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS signups"},+ referenced_table_names=[],+ )+ check = self._check(+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name="signups",+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric}"},+ )+ self._run_for(check, referenced_subjects=[])+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ denied_user = self._create_user("[email protected]")+ AccessControl.objects.create(+ team=self.team,+ resource="data_catalog",+ organization_member=denied_user.organization_memberships.get(organization=self.organization),+ access_level="none",+ )+ query = HogQLQuery(query=f"SELECT subject_name FROM system.information_schema.{table}")+ allowed_runner = HogQLQueryRunner(query=query, team=self.team, user=self.user)+ denied_runner = HogQLQueryRunner(query=query, team=self.team, user=denied_user)+ allowed_response = allowed_runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert isinstance(allowed_response, CachedHogQLQueryResponse)+ assert allowed_response.is_cached is False+ assert allowed_response.results == [("signups",)]+ allowed_cached_response = allowed_runner.run(execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)+ assert isinstance(allowed_cached_response, CachedHogQLQueryResponse)+ assert allowed_cached_response.is_cached is True+ assert allowed_cached_response.results == [["signups"]]++ denied_cache_miss = denied_runner.run(execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)+ assert isinstance(denied_cache_miss, CacheMissResponse)+ denied_response = denied_runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert isinstance(denied_response, CachedHogQLQueryResponse)+ assert denied_response.results == []+ assert denied_response.is_cached is False+ denied_cached_response = denied_runner.run(execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)+ assert isinstance(denied_cached_response, CachedHogQLQueryResponse)+ assert denied_cached_response.is_cached is True+ assert denied_cached_response.results == []++ def test_catalog_only_member_can_discover_only_metric_checks(self) -> None:+ self._check()+ metric = Metric.objects.for_team(self.team.id).create(+ team=self.team,+ name="signups",+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS value"},+ referenced_table_names=[],+ )+ metric_check = self._check(+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name=metric.name,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric}"},+ )+ self._run_for(metric_check, referenced_subjects=[])+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_objects",+ organization_member=self.organization_membership,+ access_level="none",+ )+ cache.clear()+ for table in ("data_quality_checks", "data_quality_check_runs", "data_quality_health"):+ assert self._query(f"SELECT subject_name FROM system.information_schema.{table}") == [("signups",)]++ @parameterized.expand([("catalog_member", True), ("catalog_denied", False)])+ def test_a_query_scoped_token_reads_metric_checks_on_the_users_own_catalog_access(+ self, _name: str, allowed: bool+ ) -> None:+ metric = Metric.objects.for_team(self.team.id).create(+ team=self.team,+ name="signups",+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS value"},+ referenced_table_names=[],+ )+ self._check(+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name=metric.name,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric}"},+ )+ if not allowed:+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource="data_catalog",+ organization_member=self.organization_membership,+ access_level="none",+ )+ cache.clear()+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user, label="raw hogql", secure_value=hash_key_value(token), scopes=["query:read"]+ )+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/query/",+ {+ "query": {+ "kind": "HogQLQuery",+ "query": "SELECT subject_name FROM system.information_schema.data_quality_checks "+ "WHERE subject_type = 'metric'",+ }+ },+ format="json",+ headers={"Authorization": f"Bearer {token}"},+ )++ assert response.status_code == 200, response.content+ assert response.json()["results"] == ([["signups"]] if allowed else [])++ def test_soft_deleted_subject_hides_active_checks_but_preserves_admin_history(self) -> None:+ check = self._check()+ self._run_for(check)+ self.subject.deleted = True+ self.subject.save(update_fields=["deleted"])+ assert self._query("SELECT id FROM system.information_schema.data_quality_checks") == []+ assert self._query("SELECT subject_uuid FROM system.information_schema.data_quality_health") == []+ assert len(self._query("SELECT id FROM system.information_schema.data_quality_check_runs")) == 1+def test_deleted_checks_disappear_but_their_runs_stay_queryable(self) -> None:check = self._check()self._run_for(check)diff --git a/products/data_quality/backend/tests/test_metric_checks.py b/products/data_quality/backend/tests/test_metric_checks.pynew file mode 100644index 000000000000..48962d408d52--- /dev/null+++ b/products/data_quality/backend/tests/test_metric_checks.py@@ -0,0 +1,125 @@+from uuid import uuid4++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, patch++from parameterized import parameterized++from posthog.models.scoping import team_scope+from posthog.models.team import Team++from products.data_catalog.backend.facade.api import upsert_metric+from products.data_catalog.backend.facade.models import Metric+from products.data_quality.backend.logic import checks+from products.data_quality.backend.logic.errors import CheckConfigError, SubjectUnresolvableError+from products.data_quality.backend.models import DataQualityCheck++HOGQL = {"kind": "HogQLQuery", "query": "SELECT 1 AS value"}+QUERY = "SELECT * FROM {metric} WHERE value < 1"+++class TestMetricCheckAuthoring(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(team_scope(self.team.id))+ self.enterContext(+ patch(+ "posthog.hogql.query.execute_hogql_query", side_effect=AssertionError("Authoring executed ClickHouse")+ )+ )++ def _metric(self, definition: dict | None = None) -> Metric:+ return upsert_metric(+ team=self.team, user=self.user, name="revenue", description="Revenue", definition=definition or HOGQL+ )++ def _create(+ self,+ metric: Metric,+ *,+ check_type: str = "custom_sql",+ column_name: str = "",+ config: dict | None = None,+ name: str = "",+ team: Team | None = None,+ ) -> tuple[DataQualityCheck, bool]:+ return checks.upsert_check(+ team=team or self.team,+ user=self.user,+ subject_type="metric",+ subject_uuid=str(metric.id),+ check_type=check_type,+ column_name=column_name,+ config=config or {"query": QUERY},+ name=name,+ )++ def test_authoring_reupserts_the_same_check(self) -> None:+ metric = self._metric()+ check, created = self._create(metric)+ assert created+ assert str(check.subject_uuid) == str(metric.id)+ repeated, created = self._create(metric, name="revenue_min")+ assert not created+ assert repeated.id == check.id++ @parameterized.expand(+ [+ ("wrong_type", HOGQL, {"check_type": "row_count", "config": {"min": 1}}),+ ("markdown", {"kind": "MarkdownDefinition", "markdown": "Count customers."}, {}),+ ("trends", {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]}, {}),+ ("column", HOGQL, {"column_name": "value"}),+ ("missing_placeholder", HOGQL, {"config": {"query": "SELECT 1"}}),+ (+ "repeated_placeholder",+ HOGQL,+ {"config": {"query": "SELECT * FROM {metric} a JOIN {metric} b ON a.value = b.value"}},+ ),+ ("extra_placeholder", HOGQL, {"config": {"query": "SELECT * FROM {metric} WHERE value > {threshold}"}}),+ ("invalid_check", HOGQL, {"config": {"query": "SELECT FROM {metric}"}}),+ ("invalid_saved_query", {"kind": "HogQLQuery", "query": "SELECT ("}, {}),+ ]+ )+ def test_invalid_metric_check_is_rejected_before_saving(self, _name: str, definition: dict, options: dict) -> None:+ metric = self._metric(HOGQL if _name == "invalid_saved_query" else definition)+ if _name == "invalid_saved_query":+ metric.definition = definition+ metric.save(update_fields=["definition"])+ with self.assertRaises(CheckConfigError):+ self._create(metric, **options)+ assert not DataQualityCheck.objects.for_team(self.team.id).exists()++ @parameterized.expand([("deleted",), ("missing",), ("definitionless",)])+ def test_unavailable_metric_is_rejected(self, state: str) -> None:+ metric = self._metric()+ if state == "deleted":+ metric.deleted = True+ metric.save(update_fields=["deleted"])+ elif state == "missing":+ metric.id = uuid4()+ else:+ metric.definition = None+ metric.save(update_fields=["definition"])+ with self.assertRaises((CheckConfigError, SubjectUnresolvableError)):+ self._create(metric)++ def test_edit_validates_composition_and_preserves_definition_on_rejection(self) -> None:+ metric = self._metric()+ check, _ = self._create(metric)+ edited_query = "SELECT * FROM {metric} WHERE value < 2"+ checks.edit_check(team=self.team, check=check, editor=self.user, config={"query": edited_query})+ with self.assertRaises(CheckConfigError):+ checks.edit_check(team=self.team, check=check, editor=self.user, config={"query": "SELECT 1"})+ check.refresh_from_db()+ assert check.config == {"query": edited_query}+ assert check.definition_author == self.user++ def test_manual_suite_passes_metric_selector(self) -> None:+ metric = self._metric()+ with patch("products.data_quality.backend.logic.checks.sync_connect") as connect:+ connect.return_value.start_workflow = AsyncMock()+ suite = checks.start_check_suite(+ team=self.team, user=self.user, subject_type="metric", subject_uuids=[str(metric.id)]+ )+ assert suite.subject_uuid == str(metric.id)+ assert connect.return_value.start_workflow.call_args.args[1]["metric_ids"] == [str(metric.id)]diff --git a/products/data_quality/backend/tests/test_metric_query.py b/products/data_quality/backend/tests/test_metric_query.pynew file mode 100644index 000000000000..c7bf18cb9e45--- /dev/null+++ b/products/data_quality/backend/tests/test_metric_query.py@@ -0,0 +1,153 @@+import pytest+from unittest.mock import patch++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.database.models import SavedQuery, TableNode+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import print_prepared_ast+from posthog.hogql.resolver import resolve_types++from products.data_catalog.backend.facade.contracts import HogQLMetricDefinition+from products.data_quality.backend.logic.errors import CheckConfigError+from products.data_quality.backend.logic.metric_query import bind_metric_query+++def _print(query: ast.SelectQuery | ast.SelectSetQuery) -> str:+ return print_prepared_ast(query, context=HogQLContext(enable_select_queries=True), dialect="hogql")+++def test_binds_the_metric_relation_with_its_saved_query_and_constants() -> None:+ """Catches string interpolation leaking saved metric placeholders into a check query."""+ metric = HogQLMetricDefinition(+ query="SELECT count() AS signups FROM events WHERE event = {event_name}",+ values={"event_name": "signup"},+ )++ bound = bind_metric_query("SELECT * FROM {metric} WHERE signups < 100", metric)++ printed = _print(bound)+ assert "FROM (SELECT count() AS signups FROM events WHERE equals(event, 'signup'))" in printed+ assert "WHERE less(signups, 100)" in printed+ assert "{metric}" not in printed+ assert "{event_name}" not in printed+++ ("check_query", "message"),+ [+ (+ "SELECT * FROM events",+ "Metric custom_sql checks must use exactly one {metric} relation placeholder.",+ ),+ (+ "SELECT * FROM {metric} JOIN {metric} USING id",+ "Metric custom_sql checks must use exactly one {metric} relation placeholder.",+ ),+ (+ "SELECT * FROM {other}",+ "Metric custom_sql checks must use exactly one {metric} relation placeholder.",+ ),+ (+ "SELECT * FROM {metric} WHERE {filters}",+ "Metric custom_sql checks cannot use {filters}.",+ ),+ (+ "SELECT {1 + 1} FROM {metric}",+ "Metric custom_sql checks cannot use expression placeholders.",+ ),+ ],+)+def test_rejects_ambiguous_or_unsafe_metric_check_placeholders(check_query: str, message: str) -> None:+ """Catches a check query binding a metric outside one unambiguous relation position."""+ metric = HogQLMetricDefinition(query="SELECT 1 AS signups", values={})++ with pytest.raises(CheckConfigError, match=f"^{message}$"):+ bind_metric_query(check_query, metric)+++ ("metric_query", "check_query", "message"),+ [+ (+ "SELECT FROM events",+ "SELECT * FROM {metric}",+ "Could not parse the metric query.",+ ),+ (+ "SELECT 1 AS signups",+ "SELECT * FORM {metric}",+ "Could not parse the metric custom_sql query.",+ ),+ ],+)+def test_hides_parser_internals_for_invalid_metric_or_check_hogql(+ metric_query: str, check_query: str, message: str+) -> None:+ """Catches parser implementation details escaping through metric-check validation."""+ metric = HogQLMetricDefinition(query=metric_query, values={})++ with patch("products.data_quality.backend.logic.metric_query.capture_exception") as capture:+ with pytest.raises(CheckConfigError, match=f"^{message}$"):+ bind_metric_query(check_query, metric)+ capture.assert_not_called()+++ ("failing_query", "message"),+ [+ ("metric", "Could not parse the metric query."),+ ("check", "Could not parse the metric custom_sql query."),+ ],+)+def test_reports_unexpected_parser_failures_without_exposing_details(failing_query: str, message: str) -> None:+ metric = HogQLMetricDefinition(query="SELECT 1 AS signups", values={})+ parser_error = RuntimeError("Unexpected parser failure with private query contents")+ results = [parser_error] if failing_query == "metric" else [parse_select(metric.query), parser_error]++ with (+ patch("products.data_quality.backend.logic.metric_query.parse_select", side_effect=results),+ patch("products.data_quality.backend.logic.metric_query.capture_exception") as capture,+ ):+ with pytest.raises(CheckConfigError, match=f"^{message}$"):+ bind_metric_query("SELECT * FROM {metric}", metric)+ capture.assert_called_once_with(parser_error)+++def test_rejects_cte_metric_reuse() -> None:+ """Catches duplicate metric expansion when a check reuses a CTE."""+ metric = HogQLMetricDefinition(query="SELECT count() AS signups FROM events", values={})++ with pytest.raises(CheckConfigError, match="cannot use CTEs"):+ bind_metric_query(+ "WITH failures AS (SELECT * FROM {metric} WHERE signups < 100) "+ "SELECT * FROM failures UNION ALL SELECT * FROM failures",+ metric,+ )+++ ("metric_query", "check_query"),+ [+ ("SELECT * FROM orders", "WITH orders AS (SELECT 123 AS total) SELECT * FROM {metric}"),+ (+ "SELECT * FROM orders",+ "WITH orders AS (SELECT 123 AS total) SELECT * FROM orders UNION ALL SELECT * FROM {metric}",+ ),+ ("SELECT * FROM orders", "SELECT * FROM (WITH orders AS (SELECT 123 AS total) SELECT * FROM {metric})"),+ ("SELECT orders AS total", "WITH 123 AS orders SELECT * FROM {metric}"),+ ("SELECT * FROM saved_orders", "WITH orders AS (SELECT 123 AS total) SELECT * FROM {metric}"),+ ],+)+def test_check_ctes_cannot_capture_metric_identifiers(metric_query: str, check_query: str) -> None:+ metric = HogQLMetricDefinition(query=metric_query, values={})+ database = Database()+ database.tables.children["saved_orders"] = TableNode(+ name="saved_orders",+ table=SavedQuery(id="saved-orders", name="saved_orders", query="SELECT * FROM orders", fields={}),+ )+ context = HogQLContext(database=database, enable_select_queries=True)++ with pytest.raises(CheckConfigError, match="cannot use CTEs"):+ resolve_types(bind_metric_query(check_query, metric), context, dialect="hogql")diff --git a/products/data_quality/backend/tests/test_models.py b/products/data_quality/backend/tests/test_models.pyindex ff5a3f4bf12b..86074ae6a3f3 100644--- a/products/data_quality/backend/tests/test_models.py+++ b/products/data_quality/backend/tests/test_models.py@@ -6,6 +6,10 @@ from django.db import IntegrityError, transactionfrom parameterized import parameterized+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.scoping import team_scope++from products.data_catalog.backend.facade.api import upsert_metricfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.enums import (CheckRunStatus,@@ -46,26 +50,77 @@ class TestDataQualityModels(BaseTest):)assert table_subject.pk is not None- def test_a_deleted_check_frees_its_definition_for_a_new_one(self) -> None:+ @parameterized.expand(+ [(SubjectType.VIEW, "saved_query_id"), (SubjectType.TABLE, "table_id"), (SubjectType.METRIC, "metric_id")]+ )+ def test_a_deleted_check_frees_its_definition_for_a_new_one(self, subject_type: SubjectType, fk_name: str) -> None:# Authoring a definition that was deleted earlier is a new check with its own id and# history, not a resurrection of the row the user believes is gone.- deleted = self._create_check(deleted=True)+ subject = {"subject_type": subject_type, "saved_query_id": None, fk_name: uuid4()}+ deleted = self._create_check(deleted=True, **subject)- replacement = self._create_check()+ replacement = self._create_check(**subject)assert replacement.pk != deleted.pk- def test_orphaned_checks_escape_fingerprint_uniqueness(self) -> None:+ @parameterized.expand([(SubjectType.VIEW,), (SubjectType.TABLE,), (SubjectType.METRIC,)])+ def test_orphaned_checks_escape_fingerprint_uniqueness(self, subject_type: SubjectType) -> None:# SET_NULL orphaning must never be blocked by the constraint, even for twin fingerprints.- self._create_check(saved_query_id=None)- second = self._create_check(saved_query_id=None)+ self._create_check(saved_query_id=None, subject_type=subject_type)+ second = self._create_check(saved_query_id=None, subject_type=subject_type)assert second.pk is not Nonedef test_subject_binding_rejects_contradictory_rows(self) -> None:+ assert DataQualityCheck._meta.get_field("metric").deconstruct()[3]["db_index"] is Falsewith self.assertRaises(IntegrityError), transaction.atomic():self._create_check(table_id=uuid4())with self.assertRaises(IntegrityError), transaction.atomic():self._create_check(subject_type=SubjectType.TABLE)+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="revenue",+ description="Revenue",+ definition={"kind": "HogQLQuery", "query": "SELECT 1"},+ )+ for binding in [+ {"metric_id": metric.id},+ {"metric_id": metric.id, "saved_query_id": None},+ {"subject_type": "metric"},+ {"subject_type": "metric", "saved_query_id": None, "table_id": uuid4()},+ {"subject_type": "metric", "saved_query_id": None, "table_id": uuid4(), "metric_id": metric.id},+ ]:+ with self.subTest(binding=binding), self.assertRaises(IntegrityError), transaction.atomic():+ self._create_check(**binding)+ check = self._create_check(subject_type="metric", saved_query_id=None, metric_id=metric.id)+ assert check.subject_uuid == metric.id+ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create_check(subject_type="metric", saved_query_id=None, metric_id=metric.id)++ def test_moving_a_check_to_another_metric_keeps_its_audit_entry(self) -> None:+ # A subject FK enters the diff as a Metric instance, which the activity encoder cannot+ # serialize, and one unserializable change drops the whole entry -- including the fields a+ # person did edit in the same save.+ first, second = (+ upsert_metric(+ team=self.team,+ user=self.user,+ name=name,+ description="Revenue",+ definition={"kind": "HogQLQuery", "query": "SELECT 1"},+ )+ for name in ("revenue", "refunds")+ )+ check = self._create_check(subject_type=SubjectType.METRIC, saved_query_id=None, metric_id=first.id)+ check.metric_id = second.id+ check.description = "Revenue must be non-empty"++ with team_scope(self.team.id):+ check.save()++ entry = ActivityLog.objects.get(scope="DataQualityCheck", item_id=str(check.id), activity="updated")+ assert entry.detail is not None+ assert [change["field"] for change in entry.detail["changes"]] == ["description"]def test_blank_names_coexist_but_set_names_are_unique(self) -> None:self._create_check()@@ -105,6 +160,7 @@ class TestDataQualityModels(BaseTest):model.objects.filter(id=subject_id).delete()def test_run_history_survives_deleting_the_definition(self) -> None:+ assert "subject_version" not in {field.name for field in DataQualityCheckRun._meta.fields}check = self._create_check()suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger=SuiteRunTrigger.MANUALdiff --git a/products/data_quality/backend/tests/test_notifications.py b/products/data_quality/backend/tests/test_notifications.pyindex ca181e6ee015..1410ba66ba1e 100644--- a/products/data_quality/backend/tests/test_notifications.py+++ b/products/data_quality/backend/tests/test_notifications.py@@ -1,9 +1,12 @@+from contextlib import nullcontextfrom uuid import uuid4from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.core.cache import cache+from django.db import connection+from django.test.utils import CaptureQueriesContextfrom parameterized import parameterized@@ -11,6 +14,7 @@ from posthog.constants import AvailableFeaturefrom posthog.models import OrganizationMembership, Userfrom products.access_control.backend.models.access_control import AccessControl+from products.data_catalog.backend.facade.models import Metricfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.enums import (CheckRunStatus,@@ -22,12 +26,14 @@ from products.data_quality.backend.facade.enums import (from products.data_quality.backend.logic.notifications import (_blocking_referenced_names,_WarehouseSubjectResolver,+ notify_check_started_failing,notify_materialization_blocked,)from products.data_quality.backend.logic.runner import run_checkfrom products.data_quality.backend.logic.subject_access import referenced_subject_namesfrom products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom products.notifications.backend.facade.enums import TargetType+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSourceRUNNER_QUERY = "products.data_quality.backend.logic.runner.execute_hogql_query"CREATE_NOTIFICATION = "products.data_quality.backend.logic.notifications.create_notification"@@ -75,6 +81,130 @@ class TestDataQualityNotifications(BaseTest):referenced_names=referenced_subject_names(self.team.id, check.check_type, check.config),)+ @parameterized.expand(+ [+ ("metric_source",),+ ("additional_table",),+ ("catalog",),+ ("changed_source",),+ ("unknown_source",),+ ("nested_cte_source",),+ ]+ )+ def test_metric_notification_filters_recipients_and_links_to_tests(self, denied_resource: str) -> None:+ additional = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ metric = Metric.objects.for_team(self.team.id).create(+ team=self.team,+ name="signups",+ definition={"kind": "HogQLQuery", "query": "SELECT * FROM orders"},+ referenced_table_names=["orders"],+ )+ check = self._check(+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name="old_name",+ column_name="",+ check_type=CheckType.CUSTOM_SQL,+ config={+ "query": "SELECT * FROM {metric}"+ if denied_resource == "unknown_source"+ else "SELECT * FROM {metric} JOIN customers ON 1 = 1"+ },+ )+ if denied_resource == "nested_cte_source":+ metric.definition = {+ "kind": "HogQLQuery",+ "query": "SELECT * FROM orders UNION ALL "+ "SELECT * FROM (WITH orders AS (SELECT 123 AS total) SELECT * FROM orders)",+ }+ metric.save(update_fields=["definition"])+ check.config = {"query": "SELECT * FROM {metric}"}+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(config=check.config)+ blocked = User.objects.create_and_join(self.organization, "[email protected]", "password")+ if denied_resource == "unknown_source":+ OrganizationMembership.objects.filter(organization=self.organization, user=self.user).update(+ level=OrganizationMembership.Level.ADMIN+ )+ if denied_resource == "catalog":+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource="data_catalog",+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=blocked),+ access_level="none",+ )+ cache.clear()+ else:+ self._deny_view_for_member(additional if denied_resource == "additional_table" else self.view, blocked)+ with patch(CREATE_NOTIFICATION) as notifications:+ if denied_resource in ("changed_source", "unknown_source", "nested_cte_source"):+ check.created_by = self.user+ DataQualityCheck.objects.for_team(self.team.id).filter(id=check.id).update(created_by=self.user)+ self.suite_run.trigger = SuiteRunTrigger.SCHEDULED+ self.suite_run.save(update_fields=["trigger"])++ def change_metric(*args: object, **kwargs: object) -> _Response:+ metric.definition = {"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ metric.referenced_table_names = []+ metric.save(update_fields=["definition", "referenced_table_names"])+ return _Response(3)++ pinning = (+ patch("products.data_quality.backend.logic.runner.pin_referenced_subjects", return_value=None)+ if denied_resource == "unknown_source"+ else nullcontext()+ )+ with patch(RUNNER_QUERY, side_effect=change_metric), pinning:+ outcome = run_check(check, self.suite_run, self.team)+ assert outcome.status == CheckRunStatus.FAILED+ else:+ notify_check_started_failing(check, 3)+ assert notifications.call_count == 1+ notification = notifications.call_args.args[0]+ assert notification.resource_type == "data_catalog"+ assert notification.resource_id == str(metric.id)+ assert notification.source_url == f"/project/{self.team.id}/data-catalog/metrics/signups?tab=tests"+ assert notification.title == "Data quality check failed on signups"+ with CaptureQueriesContext(connection) as queries:+ recipients = notification.resolver.resolve(TargetType.TEAM, str(self.team.id), self.team.id)+ metric_reads = [+ query for query in queries.captured_queries if f'FROM "{Metric._meta.db_table}"' in query["sql"]+ ]+ assert len(metric_reads) <= 1+ assert self.user.id in recipients+ assert blocked.id not in recipients++ @parameterized.expand([("metric",), ("view",)])+ def test_a_subject_deleted_before_the_notice_sends_nothing(self, subject_type: str) -> None:+ if subject_type == "metric":+ metric = Metric.objects.for_team(self.team.id).create(+ team=self.team, name="signups", definition={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ check = self._check(+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name="signups",+ column_name="",+ check_type=CheckType.CUSTOM_SQL,+ config={"query": "SELECT * FROM {metric}"},+ )+ metric.deleted = True+ metric.save(update_fields=["deleted"])+ else:+ check = self._check()+ self.view.deleted = True+ self.view.save(update_fields=["deleted"])++ with patch(CREATE_NOTIFICATION) as notifications:+ notify_check_started_failing(check, 3)++ notifications.assert_not_called()+@parameterized.expand([("first_failure", "", CheckSeverity.ERROR, 3, 1),@@ -169,6 +299,38 @@ class TestDataQualityNotifications(BaseTest):assert allowed.id in resolvedassert blocked.id not in resolved+ @parameterized.expand([("table",), ("source",)])+ def test_table_notifications_preserve_object_and_source_grants(self, granted_resource: str) -> None:+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ allowed = self._create_user("[email protected]")+ blocked = self._create_user("[email protected]")+ source = ExternalDataSource.objects.create(team=self.team, source_type="Stripe")+ table = DataWarehouseTable.objects.create(+ team=self.team,+ name="orders_table",+ format="Parquet",+ url_pattern="s3://bucket/orders",+ external_data_source=source,+ created_by=self.user,+ )+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")+ AccessControl.objects.create(+ team=self.team,+ resource="external_data_source" if granted_resource == "source" else "warehouse_table",+ resource_id=str(source.id if granted_resource == "source" else table.id),+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=allowed),+ access_level="viewer",+ )+ check = self._check(+ subject_type=SubjectType.TABLE, saved_query_id=None, table_id=table.id, subject_name=table.name+ )+ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)++ assert allowed.id in resolved+ assert self.user.id in resolved+ assert blocked.id not in resolved+def _deny_view_for_member(self, view, member: User) -> None:# Deny one member object-level access to a view the way the HogQL database sees it, so# denied_subject_names() picks it up -- the same setup the REST run-history tests use.@@ -193,12 +355,14 @@ class TestDataQualityNotifications(BaseTest):@parameterized.expand([- ("custom_sql", CheckType.CUSTOM_SQL, "", {"query": "SELECT 1 FROM orders"}),- ("relationships", CheckType.RELATIONSHIPS, "customer_id", None),+ ("custom_sql", CheckType.CUSTOM_SQL, "", {"query": "SELECT 1 FROM orders"}, True),+ ("relationships", CheckType.RELATIONSHIPS, "customer_id", None, True),+ ("custom_sql_without_enforcement", CheckType.CUSTOM_SQL, "", {"query": "SELECT 1 FROM orders"}, False),+ ("relationships_without_enforcement", CheckType.RELATIONSHIPS, "customer_id", None, False),])def test_members_denied_a_referenced_subject_do_not_get_the_notification(- self, _name, check_type, column_name, config+ self, _name, check_type, column_name, config, enforce_warehouse_access: bool) -> None:# A relationships check reads a target subject and a custom_sql check reads arbitrary tables,# so the failing-row count is a count oracle over those too. A member allowed the declared@@ -219,7 +383,13 @@ class TestDataQualityNotifications(BaseTest):config=config,)- resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)+ with patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda name, *args, **kwargs: (+ enforce_warehouse_access and name == "hogql-warehouse-access-control"+ ),+ ):+ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)assert self.user.id in resolvedassert blocked.id not in resolveddiff --git a/products/data_quality/backend/tests/test_run_check_suite.py b/products/data_quality/backend/tests/test_run_check_suite.pyindex b79693bd00fe..9f8df23a7c75 100644--- a/products/data_quality/backend/tests/test_run_check_suite.py+++ b/products/data_quality/backend/tests/test_run_check_suite.py@@ -118,6 +118,11 @@ class TestCheckSuiteActivities(BaseTest):assert suite_run.subject_type == SubjectType.TABLEassert suite_run.subject_uuid == table_id+ def test_mixed_metric_and_view_suite_has_no_single_subject(self) -> None:+ prepared = self._prepare(metric_ids=[str(uuid4())])+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=prepared.suite_run_id)+ assert suite.subject_uuid is None+def test_an_unflagged_org_prepares_an_empty_suite(self) -> None:self._check()diff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.pyindex 989fa9d2fbd2..947cc6f36bb4 100644--- a/products/data_quality/backend/tests/test_runner.py+++ b/products/data_quality/backend/tests/test_runner.py@@ -6,9 +6,15 @@ from unittest.mock import patchfrom parameterized import parameterized+from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.printer import prepare_ast_for_printing+from posthog.clickhouse.query_tagging import Feature, Product, QueryTags, get_query_tags+from posthog.models.team import Teamfrom posthog.models.user import User+from products.data_catalog.backend.facade.api import upsert_metricfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_quality.backend.facade.enums import (CheckRunStatus,@@ -34,7 +40,9 @@ class _Response:class TestCheckRunner(BaseTest):def setUp(self) -> None:super().setUp()- self.view = DataWarehouseSavedQuery.objects.create(team=self.team, name="orders", query={"kind": "HogQLQuery"})+ self.view = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS customer_id"}+ )self.suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger=SuiteRunTrigger.MANUAL)@@ -51,6 +59,99 @@ class TestCheckRunner(BaseTest):}return DataQualityCheck.objects.for_team(self.team.id).create(**{**defaults, **kwargs})+ def _metric_check(self, **overrides: object) -> DataQualityCheck:+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="revenue",+ description="Revenue",+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS value"},+ )+ return self._check(+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric} WHERE value < 1"},+ **overrides,+ )++ @parameterized.expand(+ [+ ("passed", 0, None, CheckRunStatus.PASSED),+ ("failed", 3, None, CheckRunStatus.FAILED),+ ("errored", 0, RuntimeError("Execution failed"), CheckRunStatus.ERRORED),+ ]+ )+ def test_metric_sql_uses_the_common_result_path(+ self, _name: str, count: int, error: Exception | None, expected: CheckRunStatus+ ) -> None:+ check = self._metric_check()+ self.suite_run.created_by = self.user+ with patch(+ RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [count, count]), side_effect=error+ ):+ outcome = run_check(check, self.suite_run, self.team)+ assert outcome.status == expected+ assert outcome.failed_row_count == (None if error else count)+ assert DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check).status == expected++ @parameterized.expand(+ [+ ("manual", SuiteRunTrigger.MANUAL, True, True, False),+ ("manual_missing_initiator", SuiteRunTrigger.MANUAL, False, True, True),+ ("scheduled_creator", SuiteRunTrigger.SCHEDULED, False, True, False),+ ("scheduled_missing_author", SuiteRunTrigger.SCHEDULED, False, False, True),+ ]+ )+ def test_metric_run_requires_the_correct_principal(+ self, _name: str, trigger: SuiteRunTrigger, initiator: bool, author: bool, errors: bool+ ) -> None:+ check = self._metric_check(created_by=self.user if author else None)+ self.suite_run.trigger = trigger+ self.suite_run.created_by = self.user if initiator else None+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])) as query:+ outcome = run_check(check, self.suite_run, self.team)+ assert outcome.status == (CheckRunStatus.ERRORED if errors else CheckRunStatus.PASSED)+ if errors:+ query.assert_not_called()+ else:+ assert query.call_args.kwargs["user"] == self.user+ assert query.call_args.kwargs["bypass_warehouse_access_control"] is False++ def test_metric_definition_drift_reaches_the_next_execution(self) -> None:+ check = self._metric_check()+ self.suite_run.created_by = self.user++ def execute_with_resolution(+ *, query: ast.SelectQuery, team: Team, user: User, bypass_warehouse_access_control: bool, **kwargs: object+ ) -> _Response:+ prepare_ast_for_printing(+ query,+ HogQLContext(+ team_id=team.id,+ user=user,+ enable_select_queries=True,+ bypass_warehouse_access_control=bypass_warehouse_access_control,+ ),+ "clickhouse",+ )+ return _Response(["failure_count", "observed_value"], [0, 0])++ with patch(RUNNER_QUERY, side_effect=execute_with_resolution):+ assert run_check(check, self.suite_run, self.team).status == CheckRunStatus.PASSED+ upsert_metric(+ team=self.team,+ user=self.user,+ name="revenue",+ description="Revenue",+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS replacement"},+ )+ outcome = run_check(check, self.suite_run, self.team)+ assert outcome.status == CheckRunStatus.ERRORED+ assert "value" in outcome.error+@parameterized.expand([("no_failing_rows", 0, CheckRunStatus.PASSED),@@ -213,14 +314,34 @@ class TestCheckRunner(BaseTest):assert query.call_args.kwargs["bypass_warehouse_access_control"] is Falseassert query.call_args.kwargs["user"] == self.user- def test_an_edited_referencing_check_runs_as_whoever_last_changed_it(self) -> None:+ @parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])+ def test_a_manual_referencing_check_without_an_initiator_never_reaches_the_warehouse(+ self, _name, check_type: CheckType+ ) -> None:+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger=SuiteRunTrigger.MANUAL+ )+ check = self._referencing_check(check_type, created_by=self.user)++ with patch(RUNNER_QUERY) as query:+ outcome = run_check(check, suite_run, self.team)++ assert outcome.status == CheckRunStatus.ERRORED+ query.assert_not_called()++ @parameterized.expand([("view",), ("metric",)])+ def test_an_edited_referencing_check_runs_as_whoever_last_changed_it(self, subject_type: str) -> None:# The creator may never have seen what the check reads now, and may have lost access to it;# the editor is the one whose warehouse ACL was checked against the current definition.editor = User.objects.create_and_join(self.organization, "[email protected]", None)suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger=SuiteRunTrigger.MATERIALIZATION)- check = self._referencing_check(CheckType.CUSTOM_SQL, created_by=self.user, definition_author=editor)+ check = (+ self._metric_check(created_by=self.user, definition_author=editor)+ if subject_type == "metric"+ else self._referencing_check(CheckType.CUSTOM_SQL, created_by=self.user, definition_author=editor)+ )with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])) as query:run_check(check, suite_run, self.team)diff --git a/products/data_quality/backend/tests/test_runs_api.py b/products/data_quality/backend/tests/test_runs_api.pyindex a75f8786f7ff..942e2fd61fad 100644--- a/products/data_quality/backend/tests/test_runs_api.py+++ b/products/data_quality/backend/tests/test_runs_api.py@@ -1,17 +1,23 @@+from datetime import timedeltafrom uuid import uuid4from posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.core.cache import cache+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import statusfrom posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, PersonalAPIKey+from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.db_context_capturing import capture_db_queriesfrom products.access_control.backend.models.access_control import AccessControl+from products.data_catalog.backend.facade.models import Metricfrom products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Nodefrom products.data_quality.backend.facade import apifrom products.data_quality.backend.facade.enums import CheckRunStatus, CheckType, SubjectStatus, SubjectType@@ -52,6 +58,14 @@ class TestDataQualityRunAPI(APIBaseTest):view.save(update_fields=["table", "is_materialized"])return backing_table+ def _metric(self, name: str) -> Metric:+ return Metric.objects.for_team(self.team.id).create(+ team=self.team,+ name=name,+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS value"},+ referenced_table_names=[],+ )+def _check(self, view: DataWarehouseSavedQuery, **overrides) -> DataQualityCheck:return DataQualityCheck.objects.for_team(self.team.id).create(**{@@ -94,18 +108,385 @@ class TestDataQualityRunAPI(APIBaseTest):self.addCleanup(warehouse_ac.stop)cache.clear()- def test_running_with_no_selection_runs_every_enabled_check(self) -> None:+ def _authenticate_token(self, kind: str, scopes: list[str]) -> None:+ if kind == "pat":+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user, label="Data quality", secure_value=hash_key_value(token), scopes=scopes+ )+ else:+ application = OAuthApplication.objects.create(+ name="Data quality",+ user=self.user,+ organization=self.organization,+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ )+ token = f"pha_{uuid4().hex}"+ OAuthAccessToken.objects.create(+ user=self.user,+ application=application,+ token=token,+ expires=timezone.now() + timedelta(hours=1),+ scope=" ".join(scopes),+ )+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")++ @parameterized.expand(+ [+ (kind, resource, admin)+ for kind in ("pat", "oauth")+ for resource in ("warehouse_objects", "data_catalog")+ for admin in (False, True)+ ]+ )+ def test_project_endpoints_filter_token_subjects(self, kind: str, resource: str, admin: bool) -> None:+ warehouse_check = self._check(self.orders)+ metric = self._metric("signups")+ metric_check = self._check(+ self.orders,+ saved_query_id=None,+ metric_id=metric.id,+ subject_type=SubjectType.METRIC,+ subject_name=metric.name,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric}"},+ )+ allowed, denied = (+ (warehouse_check, metric_check) if resource == "warehouse_objects" else (metric_check, warehouse_check)+ )+ suites = []+ for check in (allowed, denied):+ assert check.subject_uuid is not None+ suites.append(+ DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team,+ trigger="manual",+ subject_type=check.subject_type,+ subject_uuid=check.subject_uuid,+ )+ )+ mixed = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")+ for check in (allowed, denied):+ assert check.subject_uuid is not None+ api.record_check_run(+ self.team.id,+ suite_run=mixed,+ quality_check=check,+ subject_type=check.subject_type,+ subject_uuid=check.subject_uuid,+ subject_name=check.subject_name,+ check_type=check.check_type,+ check_fingerprint=check.fingerprint,+ status=CheckRunStatus.PASSED,+ referenced_subjects=[],+ )+ if admin:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save(update_fields=["level"])+ self._authenticate_token(kind, [f"{resource}:write", "query:read"])++ listed = self.client.get(self.checks_url)+ assert listed.status_code == 200, listed.json()+ assert listed.json()["count"] == 1+ assert [check["id"] for check in listed.json()["results"]] == [str(allowed.id)]+ health = self.client.get(f"{self.checks_url}health/")+ assert health.status_code == 200, health.json()+ assert [row["subject_type"] for row in health.json()] == [allowed.subject_type]+ history = self.client.get(self.url)+ assert history.status_code == 200, history.json()+ assert [suite["id"] for suite in history.json()["results"]] == [str(suites[0].id)]+ assert self.client.get(f"{self.url}{suites[1].id}/").status_code == 404+ assert self._run(check_ids=[str(denied.id)]).status_code == 403+ assert self._run(check_ids=[str(allowed.id)]).status_code == 200+ temporal = MagicMock(start_workflow=AsyncMock())+ with patch(START_SUITE, return_value=temporal):+ swept = self.client.post(self.url, {}, format="json")+ assert swept.status_code == 200, swept.json()+ assert temporal.start_workflow.call_args.args[1]["check_ids"] == [str(allowed.id)]++ @parameterized.expand([(kind, admin) for kind in ("pat", "oauth") for admin in (False, True)])+ def test_catalog_token_cannot_read_warehouse_through_a_metric_check(self, kind: str, admin: bool) -> None:+ metric = self._metric("signups")+ check = self._check(+ self.orders,+ saved_query_id=None,+ metric_id=metric.id,+ subject_type=SubjectType.METRIC,+ subject_name=metric.name,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric} JOIN orders ON 1 = 1"},+ )+ if admin:+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save(update_fields=["level"])+ self._authenticate_token(kind, ["data_catalog:write", "query:read"])+ listed = self.client.get(self.checks_url)+ assert listed.status_code == 200+ assert listed.json()["results"] == []+ assert self.client.get(f"{self.checks_url}health/").json() == []+ assert self._run(check_ids=[str(check.id)]).status_code == 403+ temporal = MagicMock(start_workflow=AsyncMock())+ with patch(START_SUITE, return_value=temporal):+ swept = self.client.post(self.url, {}, format="json")+ assert swept.status_code == 200+ temporal.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"] == []+ with patch(START_SUITE, return_value=temporal):+ assert self.client.post(f"{nested_url}{check.id}/run/").status_code == 403++ @parameterized.expand(+ [+ (["query:read", "data_catalog:read"], 200, 403),+ (["query:read"], 403, 403),+ (["data_catalog:write"], 403, 403),+ (["*"], 200, 200),+ ]+ )+ def test_project_subject_scope_requirements(self, scopes: list[str], read_status: int, write_status: int) -> None:+ self._authenticate_token("pat", scopes)+ assert self.client.get(self.checks_url).status_code == read_status+ assert self._run().status_code == write_status++ @parameterized.expand(+ [+ (kind, subject_type, level)+ for kind in ("pat", "oauth")+ for subject_type in ("table", "view")+ for level in ("read", "write")+ ]+ )+ def test_nested_warehouse_routes_honor_their_own_scopes(self, kind: str, subject_type: str, level: str) -> None:+ subject: DataWarehouseSavedQuery | DataWarehouseTable+ if 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.orders+ check = 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"])++ listed = self.client.get(nested)+ 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+ with 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++ def test_catalog_only_members_see_teammates_metric_checks_and_suites(self) -> None:+ author = self._create_user("[email protected]")+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_objects",+ organization_member=self.organization_membership,+ access_level="none",+ )+ metric = self._metric("active_users")+ check = self._check(+ self.orders,+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name=metric.name,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric}"},+ created_by=author,+ )+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger="manual", subject_type=SubjectType.METRIC, subject_uuid=metric.id, created_by=author+ )self._check(self.orders)- self._check(self.customers)+ cache.clear()+ nested = f"/api/projects/{self.team.id}/data_catalog/metrics/{metric.id}/"++ for url in (self.checks_url, f"{nested}checks/"):+ 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/"):+ response = self.client.get(url)+ assert response.status_code == 200, response.json()+ assert [row["id"] for row in response.json()["results"]] == [str(suite.id)]++ @parameterized.expand(+ [+ (subject_type, access_level, enforce_warehouse_access)+ for subject_type in (SubjectType.TABLE, SubjectType.VIEW)+ for access_level in ("viewer", "editor")+ for enforce_warehouse_access in (False, True)+ ]+ )+ def test_specific_warehouse_grants_apply_to_check_routes(+ self, subject_type: SubjectType, access_level: str, enforce_warehouse_access: bool+ ) -> None:+ author = self._create_user("[email protected]")+ subjects: list[DataWarehouseSavedQuery | DataWarehouseTable]+ if subject_type == SubjectType.TABLE:+ subjects = [+ DataWarehouseTable.objects.create(team=self.team, name=name, format="Parquet", created_by=author)+ 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,+ subject_type=subject_type,+ subject_name=subject.name,+ created_by=author,+ **{"saved_query_id": None, subject_fk: subject.id},+ )+ for subject in subjects+ ]+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")+ AccessControl.objects.create(+ team=self.team,+ resource=f"warehouse_{subject_type}",+ resource_id=str(subjects[0].id),+ organization_member=self.organization_membership,+ access_level=access_level,+ )+ allowed_suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team,+ trigger="manual",+ created_by=author,+ subject_type=subject_type,+ subject_uuid=granted.subject_uuid,+ )+ mixed_suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger="manual", created_by=author+ )+ for check in (granted, ungranted):+ assert check.subject_uuid is not None+ api.record_check_run(+ self.team.id,+ suite_run=mixed_suite,+ quality_check=check,+ subject_type=subject_type,+ subject_uuid=check.subject_uuid,+ subject_name=check.subject_name,+ check_type=check.check_type,+ check_fingerprint=check.fingerprint,+ referenced_subjects=[],+ status=CheckRunStatus.PASSED,+ )+ cache.clear()+ flag = patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda name, *args, **kwargs: (+ enforce_warehouse_access and name == "hogql-warehouse-access-control"+ ),+ )+ 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/"++ for url in (nested, self.checks_url):+ listed = self.client.get(url)+ assert listed.status_code == status.HTTP_200_OK, listed.json()+ assert listed.json()["count"] == 1+ assert [row["id"] for row in listed.json()["results"]] == [str(granted.id)]+ assert self.client.get(denied_nested).status_code == status.HTTP_403_FORBIDDEN+ history = 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)]+ assert self.client.get(f"{self.url}{mixed_suite.id}/").status_code == status.HTTP_404_NOT_FOUND++ 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+ denied_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()+ 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)++ @parameterized.expand([("metric",), ("view",)])+ def test_deleted_subject_checks_disappear_immediately(self, kind: str) -> None:+ subject = self._metric("signups") if kind == "metric" else self.orders+ if kind == "metric":+ self._check(self.orders, saved_query_id=None, metric_id=subject.id, subject_type=SubjectType.METRIC)+ else:+ self._check(self.orders)+ subject.deleted = True+ subject.save(update_fields=["deleted"])+ assert self.client.get(self.checks_url).json()["results"] == []+ assert self.client.get(f"{self.checks_url}health/").json() == []+ assert self._run().json()["status"] == "empty"++ @parameterized.expand([("unrestricted", False), ("restricted", True)])+ def test_running_with_no_selection_runs_every_enabled_check(self, _name: str, restricted: bool) -> None:+ enabled = [self._check(self.orders), self._check(self.customers)]+ enabled.extend(self._check(self._make_view(f"view_{index}")) for index in range(4))+ metrics = [self._metric(f"metric_{index}") for index in range(3)]+ enabled.extend(+ self._check(+ self.orders,+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name=metric.name,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric} WHERE value < 1"},+ )+ for metric in metrics+ for _ in range(2)+ )self._check(self.customers, column_name="total", enabled=False)+ if restricted:+ self._deny(self._make_view("secrets"))- response = self._run()+ temporal = MagicMock(start_workflow=AsyncMock())+ with patch(START_SUITE, return_value=temporal), capture_db_queries() as captured:+ response = self.client.post(self.url, {}, format="json")assert response.status_code == status.HTTP_200_OK, response.json()suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=response.json()["id"])assert suite_run.status == "running"# A sweep has no single subject, so the response has to say so rather than name one.assert response.json()["subject_type"] is None+ assert set(temporal.start_workflow.call_args.args[1]["check_ids"]) == {str(check.id) for check in enabled}+ statements = [query["sql"] for query in captured.captured_queries]+ metric_definition_reads = [+ sql+ for sql in statements+ if '"data_catalog_metric"."definition"' in sql and '"data_catalog_metric"."id" IN (' in sql+ ]+ assert len(metric_definition_reads) == int(restricted), metric_definition_reads+ assert not any('"posthog_datawarehousesavedquery"."id" =' in sql for sql in statements)def test_a_sweep_leaves_out_checks_on_a_denied_subject(self) -> None:# "Everything" means everything this member can see. A denied subject is not part of it.@@ -143,6 +524,21 @@ class TestDataQualityRunAPI(APIBaseTest):assert response.json()["status"] == "empty"connect.assert_not_called()+ @parameterized.expand([("named",), ("swept",)])+ def test_run_selection_respects_denied_references(self, selection: str) -> None:+ check = self._check(+ self.customers,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM orders"},+ )+ self._deny_orders()+ body = {"check_ids": [str(check.id)]} if selection == "named" else {}+ response = self._run(**body)+ assert response.status_code == (403 if selection == "named" else 200), response.json()+ if selection == "swept":+ assert response.json()["status"] == "empty"+def test_naming_a_denied_check_is_refused(self) -> None:# Naming one is an attempt to read it, so it 403s rather than being silently dropped.denied = self._check(self.orders)@@ -340,6 +736,91 @@ class TestDataQualityRunAPI(APIBaseTest):assert {row["subject_name"] for row in listed.json()["results"]} == {"customers"}assert {row["subject_uuid"] for row in health.json()} == {str(self.customers.id)}+ def test_catalog_only_overview_filters_before_scanning_and_paginating(self) -> None:+ page_size = 150+ visible_count = 205+ visibility_batch_size = 200+ metrics = [self._metric(f"metric_{index}") for index in range(3)]+ visible_checks = [+ DataQualityCheck(+ team=self.team,+ subject_type=SubjectType.METRIC,+ metric_id=metrics[index % len(metrics)].id,+ subject_name=metrics[index % len(metrics)].name,+ check_type=CheckType.CUSTOM_SQL,+ config={"query": "SELECT * FROM {metric} WHERE value < 1"},+ name=f"visible_{index:03d}",+ fingerprint=uuid4().hex,+ created_by=self.user,+ owner=self.user,+ )+ for index in range(visible_count)+ ]+ hidden_warehouse_checks = [+ DataQualityCheck(+ team=self.team,+ subject_type=SubjectType.VIEW,+ saved_query_id=self.orders.id,+ subject_name=self.orders.name,+ check_type=CheckType.NOT_NULL,+ column_name="id",+ name=f"hidden_{index:03d}",+ fingerprint=uuid4().hex,+ )+ for index in range(visible_count)+ ]+ DataQualityCheck.objects.for_team(self.team.id).bulk_create([*visible_checks, *hidden_warehouse_checks])+ for metric in metrics:+ self._check(+ self.orders,+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name=metric.name,+ name=f"hidden_reference_{metric.name}",+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric} CROSS JOIN orders"},+ )+ self._deny_orders()+ self._authenticate_token("pat", ["data_catalog:read", "query:read"])+ expected = sorted(visible_checks, key=lambda check: (check.subject_name, check.name))+ visible_ids = {str(check.id) for check in visible_checks}++ for offset in (0, page_size):+ with capture_db_queries() as captured:+ response = self.client.get(self.checks_url, {"limit": page_size, "offset": offset})+ assert response.status_code == status.HTTP_200_OK, response.json()+ body = response.json()+ assert body["count"] == visible_count+ assert [row["id"] for row in body["results"]] == [+ str(check.id) for check in expected[offset : offset + page_size]+ ]+ assert all(row["owner"] == self.user.email for row in body["results"])+ assert bool(body["next"]) == (offset == 0)++ statements = [query["sql"] for query in captured.captured_queries]+ scans = [+ sql for sql in statements if '"data_quality_dataqualitycheck"."config"' in sql and " LIMIT " not in sql+ ]+ assert len(scans) == 1, scans+ assert '"data_quality_dataqualitycheck"."metric_id" IN (' in scans[0]+ assert '"posthog_user"' not in scans[0]+ assert '"data_quality_dataqualitycheck"."description"' not in scans[0]+ metric_definition_reads = [+ sql+ for sql in statements+ if '"data_catalog_metric"."definition"' in sql and '"data_catalog_metric"."id" IN (' in sql+ ]+ assert 1 <= len(metric_definition_reads) <= 2, metric_definition_reads+ run_lookups = [+ sql for sql in statements if '"data_quality_dataqualitycheckrun"."quality_check_id" IN (' in sql+ ]+ assert run_lookups+ assert all(+ sum(identifier in sql for identifier in visible_ids) <= visibility_batch_size for sql in run_lookups+ ), run_lookups+def test_the_overview_hides_a_check_that_reads_a_denied_subject(self) -> None:# The parent is allowed, but the config names "orders" and the status answers questions# about its rows, so listing the check is a directory entry for a table the member cannot read.@@ -495,11 +976,26 @@ class TestDataQualityRunAPI(APIBaseTest):)for index in range(5)]+ # More metrics than the page checks, so the catalog's size cannot reach the result.+ metrics = [self._metric(f"metric_{index}") for index in range(5)]+ metric_checks = [+ self._check(+ self.orders,+ subject_type=SubjectType.METRIC,+ saved_query_id=None,+ metric_id=metric.id,+ subject_name=metric.name,+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT * FROM {metric} WHERE value < 1"},+ )+ for metric in metrics[:2]+ ]- with self.assertNumQueries(2):- located = api.subject_locations(self.team.id, [*views, *tables])+ with self.assertNumQueries(4):+ located = api.subject_locations(self.team.id, [*views, *tables, *metric_checks])- assert len(located) == 5+ assert len(located) == 7def _synced_table(self, name: str) -> tuple[DataWarehouseTable, ExternalDataSchema]:source = ExternalDataSource.objects.create(team=self.team, source_type="Stripe")diff --git a/products/data_quality/backend/tests/test_subject_access.py b/products/data_quality/backend/tests/test_subject_access.pynew file mode 100644index 000000000000..cd4821c11d16--- /dev/null+++ b/products/data_quality/backend/tests/test_subject_access.py@@ -0,0 +1,336 @@+from contextlib import nullcontext+from dataclasses import replace+from types import SimpleNamespace++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.cache import cache++from parameterized import parameterized++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.printer import prepare_ast_for_printing++from posthog.constants import AvailableFeature+from posthog.models.team import Team+from posthog.models.user import User++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.access_control.backend.models.access_control import AccessControl+from products.data_catalog.backend.facade.api import upsert_metric+from products.data_catalog.backend.facade.models import Metric+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_quality.backend.facade.enums import SubjectType+from products.data_quality.backend.logic.checks import upsert_check+from products.data_quality.backend.logic.permissions import writable_subjects+from products.data_quality.backend.logic.runner import run_check+from products.data_quality.backend.logic.subject_access import (+ DenialContext,+ definition_reads_unreadable_subject,+ denial_context,+ hidden_check_ids,+ pin_referenced_subjects,+ readable_subjects,+ referenced_subject_names,+ subject_metadata,+ without_denied_runs,+)+from products.data_quality.backend.logic.subjects import resolve_subject+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+++class TestMetricSubjectAccess(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.metric_table = DataWarehouseTable.objects.create(+ team=self.team,+ name="revenue_rows",+ format="Parquet",+ url_pattern="s3://bucket/revenue",+ columns={"amount": {"clickhouse": "Int64", "hogql": "integer"}},+ )+ self.extra_view = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="thresholds", query={"kind": "HogQLQuery", "query": "SELECT 1 AS minimum"}+ )+ self.metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="revenue",+ description="Revenue",+ definition={"kind": "HogQLQuery", "query": "SELECT amount FROM revenue_rows"},+ )+ self.subject = resolve_subject(self.team.id, "metric", self.metric.id)+ self.config = {"query": "SELECT * FROM {metric} WHERE amount < (SELECT minimum FROM thresholds)"}++ @parameterized.expand(+ [("metric_table", {"revenue_rows"}, True), ("extra_table", {"thresholds"}, True), ("allowed", set(), False)]+ )+ def test_composed_references_control_access(self, _name: str, denied: set[str], expected: bool) -> None:+ database = Database.create_for(team=self.team, user=self.user)+ context = DenialContext(+ readable=readable_subjects(self.team.id, denied),+ denied=denied,+ database=database,+ metadata=subject_metadata(self.team.id),+ )+ assert (+ definition_reads_unreadable_subject(self.team.id, "custom_sql", self.config, context, subject=self.subject)+ is expected+ )++ @parameterized.expand(+ [+ ("disabled_viewer", False, "viewer"),+ ("disabled_editor", False, "editor"),+ ("enabled_viewer", True, "viewer"),+ ("enabled_editor", True, "editor"),+ ]+ )+ def test_context_preserves_specific_grants_and_denies_ungranted_dependencies(+ self, _name: str, enforce_warehouse_access: bool, access_level: str+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ member = self._create_user("[email protected]")+ membership = member.organization_memberships.get(organization=self.organization)+ source = ExternalDataSource.objects.create(team=self.team, source_type="Stripe")+ self.metric_table.external_data_source = source+ self.metric_table.save(update_fields=["external_data_source"])+ granted_table = DataWarehouseTable.objects.create(+ team=self.team,+ name="granted_rows",+ format="Parquet",+ url_pattern="s3://bucket/granted",+ columns={"amount": {"clickhouse": "Int64", "hogql": "integer"}},+ )+ ungranted_table = DataWarehouseTable.objects.create(+ team=self.team,+ name="ungranted_rows",+ format="Parquet",+ url_pattern="s3://bucket/ungranted",+ columns={"amount": {"clickhouse": "Int64", "hogql": "integer"}},+ )+ ungranted_view = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="ungranted_view", query={"kind": "HogQLQuery", "query": "SELECT 1 AS amount"}+ )+ for name in ["ungranted_rows", "ungranted_view"]:+ Metric.objects.for_team(self.team.id).create(+ team=self.team,+ name=f"metric_{name}",+ definition={"kind": "HogQLQuery", "query": f"SELECT 1 AS amount FROM {name}"},+ referenced_table_names=[name],+ )+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")+ for resource, identifier in [+ ("warehouse_table", granted_table.id),+ ("warehouse_view", self.extra_view.id),+ ("external_data_source", source.id),+ ]:+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=str(identifier),+ organization_member=membership,+ access_level=access_level,+ )+ cache.clear()+ access = UserAccessControl(member, team=self.team)+ with patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda name, *args, **kwargs: (+ enforce_warehouse_access and name == "hogql-warehouse-access-control"+ ),+ ):+ database = Database.create_for(team=self.team, user=member, user_access_control=access)+ context = denial_context(self.team.id, database)++ assert context.readable.table_ids == frozenset({self.metric_table.id, granted_table.id})+ assert context.readable.view_ids == frozenset({self.extra_view.id})+ assert context.readable.metric_ids == frozenset({self.metric.id})+ assert {ungranted_table.name, ungranted_view.name} <= context.denied+ assert not definition_reads_unreadable_subject(+ self.team.id, "custom_sql", self.config, context, subject=self.subject+ )+ for name in [ungranted_table.name, ungranted_view.name]:+ assert definition_reads_unreadable_subject(+ self.team.id,+ "custom_sql",+ {"query": f"SELECT * FROM {{metric}} WHERE amount < (SELECT 1 FROM {name})"},+ context,+ subject=self.subject,+ )+ writable = writable_subjects(context, access, allowed=frozenset(SubjectType))+ assert writable.table_ids == (context.readable.table_ids if access_level == "editor" else frozenset())+ assert writable.view_ids == (context.readable.view_ids if access_level == "editor" else frozenset())++ def test_pins_both_saved_metric_and_check_references(self) -> None:+ assert set(referenced_subject_names(self.team.id, "custom_sql", self.config, subject=self.subject)) == {+ "revenue_rows",+ "thresholds",+ }+ pinned = pin_referenced_subjects(self.team.id, "custom_sql", self.config, subject=self.subject)+ assert pinned is not None+ assert {(ref["subject_type"], ref["subject_uuid"]) for ref in pinned} == {+ ("table", str(self.metric_table.id)),+ ("view", str(self.extra_view.id)),+ }++ @parameterized.expand([("allowed", set(), True), ("denied", {"revenue_rows"}, False)])+ def test_readable_metric_identity_controls_history(self, _name: str, denied: set[str], expected: bool) -> None:+ check, suite = self._check_and_suite()+ run = DataQualityCheckRun.objects.for_team(self.team.id).create(+ team=self.team,+ quality_check=check,+ suite_run=suite,+ subject_type="metric",+ subject_uuid=self.metric.id,+ subject_name=self.metric.name,+ check_type="custom_sql",+ check_fingerprint=check.fingerprint,+ referenced_subjects=[],+ status="passed",+ )+ readable = readable_subjects(self.team.id, denied)+ assert readable.contains("metric", self.metric.id) is expected+ context = DenialContext(+ readable=readable,+ denied=denied,+ database=Database.create_for(team=self.team, user=self.user),+ metadata=subject_metadata(self.team.id),+ )+ assert (+ without_denied_runs(DataQualityCheckRun.objects.for_team(self.team.id), context).filter(id=run.id).exists()+ is expected+ )++ def test_repeated_metric_checks_resolve_in_a_bounded_number_of_queries(self) -> None:+ check, _ = self._check_and_suite()+ context = DenialContext(+ readable=readable_subjects(self.team.id, set()),+ denied=set(),+ database=Database.create_for(team=self.team, user=self.user),+ metadata=subject_metadata(self.team.id),+ )+ with self.assertNumQueries(4):+ assert hidden_check_ids(self.team.id, [check] * 20, context) == set()+ context = replace(context, denied=context.denied | {"thresholds"})+ with self.assertNumQueries(2):+ assert hidden_check_ids(self.team.id, [check] * 20, context) == {check.id}++ def test_failed_composition_cannot_record_empty_references(self) -> None:+ assert pin_referenced_subjects(self.team.id, "custom_sql", {"query": "SELECT 1"}, subject=self.subject) is None++ def _check_and_suite(self) -> tuple[DataQualityCheck, DataQualitySuiteRun]:+ check, _ = upsert_check(+ team=self.team,+ user=self.user,+ subject_type="metric",+ subject_uuid=str(self.metric.id),+ check_type="custom_sql",+ column_name="",+ config=self.config,+ )+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger="manual", created_by=self.user+ )+ return check, suite++ @parameterized.expand([("metric_table",), ("extra_view",)])+ def test_runtime_denies_each_composed_warehouse_reference(self, denied_subject: str) -> None:+ check, suite = self._check_and_suite()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ subject = self.metric_table if denied_subject == "metric_table" else self.extra_view+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_table" if denied_subject == "metric_table" else "warehouse_view",+ resource_id=str(subject.id),+ organization_member=self.organization_membership,+ access_level="none",+ )+ cache.clear()++ def execute_with_resolution(+ *, query: ast.SelectQuery, team: Team, user: User, bypass_warehouse_access_control: bool, **kwargs: object+ ) -> SimpleNamespace:+ prepare_ast_for_printing(+ query,+ HogQLContext(+ team_id=team.id,+ user=user,+ enable_select_queries=True,+ bypass_warehouse_access_control=bypass_warehouse_access_control,+ ),+ "clickhouse",+ )+ return SimpleNamespace(results=[[0, 0]], columns=["failure_count", "observed_value"])++ with (+ patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda name, *args, **kwargs: name == "hogql-warehouse-access-control",+ ),+ patch(+ "products.data_quality.backend.logic.runner.execute_hogql_query", side_effect=execute_with_resolution+ ),+ ):+ outcome = run_check(check, suite, self.team)+ assert outcome.status == "errored"+ assert subject.name in outcome.error++ @parameterized.expand(+ [+ ("success", False, False),+ ("engine_error", True, False),+ ("discovery_failure", False, True),+ ]+ )+ def test_run_pins_the_definition_executed_during_a_metric_edit(+ self, _name: str, engine_fails: bool, discovery_fails: bool+ ) -> None:+ check, suite = self._check_and_suite()++ def execute_with_edit(**kwargs: object) -> SimpleNamespace:+ upsert_metric(+ team=self.team,+ user=self.user,+ name="revenue",+ description="Revenue",+ definition={"kind": "HogQLQuery", "query": "SELECT 1 AS amount"},+ )+ if engine_fails:+ raise RuntimeError("Query execution failed")+ return SimpleNamespace(results=[[0, 0]], columns=["failure_count", "observed_value"])++ discovery = (+ patch(+ "products.data_quality.backend.logic.runner.pin_referenced_subjects",+ side_effect=[None, [{"subject_type": "view", "subject_uuid": str(self.extra_view.id)}]],+ )+ if discovery_fails+ else nullcontext()+ )+ with (+ discovery,+ patch("products.data_quality.backend.logic.runner.execute_hogql_query", side_effect=execute_with_edit),+ ):+ outcome = run_check(check, suite, self.team)+ assert outcome.status == ("errored" if engine_fails else "passed")+ run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)+ if discovery_fails:+ assert run.referenced_subjects is None+ return+ assert run.referenced_subjects is not None+ assert {ref["subject_uuid"] for ref in run.referenced_subjects} == {+ str(self.metric_table.id),+ str(self.extra_view.id),+ }+ assert "revenue_rows" in run.compiled_querydiff --git a/products/data_quality/backend/tests/test_subjects.py b/products/data_quality/backend/tests/test_subjects.pyindex 250f6be5fe54..cf7f98e1ef79 100644--- a/products/data_quality/backend/tests/test_subjects.py+++ b/products/data_quality/backend/tests/test_subjects.py@@ -8,17 +8,65 @@ from posthog.hogql.database.database import Databasefrom posthog.models.team import Team+from products.data_catalog.backend.facade.api import upsert_metricfrom 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 SubjectType-from products.data_quality.backend.logic.subject_access import readable_subjects-from products.data_quality.backend.logic.subjects import resolve_subject+from products.data_quality.backend.logic.subject_access import readable_subjects, subject_metadata+from products.data_quality.backend.logic.subjects import resolve_subject, 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 ExternalDataSourceclass TestSubjectResolver(BaseTest):+ def test_metric_resolution_tracks_definition_and_soft_deletion(self) -> None:+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="revenue",+ description="Revenue",+ definition={"kind": "HogQLQuery", "query": "SELECT 1"},+ )+ with self.assertNumQueries(2):+ resolved = resolve_subject(self.team.id, "metric", metric.id)+ assert resolved.exists+ assert resolved.name == "revenue"+ assert resolved.definition_kind == "HogQLQuery"+ assert resolved.metric_definition is not None+ assert resolved.metric_definition.query == "SELECT 1"+ upsert_metric(+ team=self.team,+ user=self.user,+ name="revenue",+ description="Revenue",+ definition={"kind": "HogQLQuery", "query": "SELECT 2"},+ )+ updated = resolve_subject(self.team.id, "metric", metric.id)+ assert updated.metric_definition is not None+ assert updated.metric_definition.query == "SELECT 2"+ assert subject_column_type(self.team.id, "metric", metric.id, "amount") is None+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ assert not resolve_subject(other_team.id, "metric", metric.id).exists+ metric.deleted = True+ metric.save(update_fields=["deleted"])+ assert not resolve_subject(self.team.id, "metric", metric.id).exists++ @parameterized.expand(+ [+ ("markdown", {"kind": "MarkdownDefinition", "markdown": "Count customers."}),+ ("trends", {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]}),+ ("definitionless", None),+ ]+ )+ def test_unsupported_live_metrics_remain_resolvable(self, _name: str, definition: dict | None) -> None:+ metric = upsert_metric(+ team=self.team, user=self.user, name="revenue", description="Revenue", definition=definition+ )+ resolved = resolve_subject(self.team.id, "metric", metric.id)+ assert resolved.exists+ assert resolved.metric_definition is None+def _table(self, name: str = "stripe_customers") -> DataWarehouseTable:return DataWarehouseTable.objects.create(team=self.team, name=name, format="Parquet", url_pattern="s3://bucket/x"@@ -134,3 +182,24 @@ class TestReadableSubjectSnapshot(BaseTest):backing_tables = data_modeling_facade.backing_table_ids_by_saved_query(self.team.id)assert backing_tables == {backing_table.id: view.id}++ def test_shared_metadata_keeps_recipient_permissions_separate(self) -> None:+ allowed = self._table("allowed")+ denied = self._table("denied")+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="shared_metric",+ description="A shared source",+ definition={"kind": "HogQLQuery", "query": "SELECT * FROM denied"},+ )+ metadata = subject_metadata(self.team.id)+ with self.assertNumQueries(0):+ restricted = readable_subjects(self.team.id, {"denied"}, metadata=metadata)+ unrestricted = readable_subjects(self.team.id, set(), metadata=metadata)+ catalog_denied = readable_subjects(self.team.id, set(), metadata=metadata, can_read_catalog=False)+ assert restricted.table_ids == {allowed.id}+ assert metric.id not in restricted.metric_ids+ assert unrestricted.table_ids == {allowed.id, denied.id}+ assert metric.id in unrestricted.metric_ids+ assert not catalog_denied.metric_idsdiff --git a/products/data_quality/frontend/checksApi.test.ts b/products/data_quality/frontend/checksApi.test.tsnew file mode 100644index 000000000000..9974898bd2da--- /dev/null+++ b/products/data_quality/frontend/checksApi.test.ts@@ -0,0 +1,96 @@+import { checksApi, type DataQualitySubjectRef, type DataQualitySubjectType } from './checksApi'+import * as generated from './generated/api'++jest.mock('lib/api', () => ({+ __esModule: true,+ default: {},+ ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },+ ApiError: class ApiError extends Error {},+}))++jest.mock('./generated/api')++const ROUTE_PREFIX: Record<DataQualitySubjectType, string> = {+ table: 'warehouseTables',+ view: 'warehouseSavedQueries',+ metric: 'dataCatalogMetrics',+}++interface Operation {+ name: string+ route: string+ call: (ref: DataQualitySubjectRef) => Promise<unknown>+ trailingArgs: 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>++describe('checksApi', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ })++ 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}`++ await operation.call({ subjectType, subjectId: 'subject-1' })++ expect(mocked[expected]).toHaveBeenCalledWith('1', 'subject-1', ...operation.trailingArgs)+ })+})diff --git a/products/data_quality/frontend/checksApi.ts b/products/data_quality/frontend/checksApi.tsindex 0bf6f4abafb2..50825a3ffc34 100644--- a/products/data_quality/frontend/checksApi.ts+++ b/products/data_quality/frontend/checksApi.ts@@ -1,6 +1,18 @@import { ApiConfig, ApiError } from 'lib/api'import {+ dataCatalogMetricsCheckSuiteRunsCheckRunsList,+ dataCatalogMetricsCheckSuiteRunsList,+ dataCatalogMetricsCheckSuiteRunsRetrieve,+ dataCatalogMetricsChecksCheckTypesList,+ dataCatalogMetricsChecksCreate,+ dataCatalogMetricsChecksDestroy,+ dataCatalogMetricsChecksHealthRetrieve,+ dataCatalogMetricsChecksList,+ dataCatalogMetricsChecksPartialUpdate,+ dataCatalogMetricsChecksRunAllCreate,+ dataCatalogMetricsChecksRunCreate,+ dataCatalogMetricsChecksRunsList,warehouseSavedQueriesCheckSuiteRunsCheckRunsList,warehouseSavedQueriesCheckSuiteRunsList,warehouseSavedQueriesCheckSuiteRunsRetrieve,@@ -40,7 +52,7 @@ export function apiErrorDetail(error: unknown): string | null {return error instanceof ApiError ? error.detail : null}-export type DataQualitySubjectType = 'table' | 'view'+export type DataQualitySubjectType = 'table' | 'view' | 'metric'export interface DataQualitySubjectRef {subjectType: DataQualitySubjectType@@ -49,73 +61,114 @@ export interface DataQualitySubjectRef {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,+ },+}function projectId(): string {return String(ApiConfig.getCurrentTeamId())}-function isView({ subjectType }: DataQualitySubjectRef): boolean {- return subjectType === 'view'+function routesFor({ subjectType }: DataQualitySubjectRef): SubjectRoutes {+ return ROUTES[subjectType]}export const checksApi = {list: (ref: DataQualitySubjectRef, limit: number): Promise<PaginatedDataQualityCheckListApi> =>- isView(ref)- ? warehouseSavedQueriesChecksList(projectId(), ref.subjectId, { limit })- : warehouseTablesChecksList(projectId(), ref.subjectId, { limit }),+ routesFor(ref).list(projectId(), ref.subjectId, { limit }),create: (ref: DataQualitySubjectRef, body: CreateBody): Promise<DataQualityCheckApi> =>- isView(ref)- ? warehouseSavedQueriesChecksCreate(projectId(), ref.subjectId, body)- : warehouseTablesChecksCreate(projectId(), ref.subjectId, body),+ routesFor(ref).create(projectId(), ref.subjectId, body),partialUpdate: (ref: DataQualitySubjectRef, id: string, body: PatchBody): Promise<DataQualityCheckApi> =>- isView(ref)- ? warehouseSavedQueriesChecksPartialUpdate(projectId(), ref.subjectId, id, body)- : warehouseTablesChecksPartialUpdate(projectId(), ref.subjectId, id, body),+ routesFor(ref).partialUpdate(projectId(), ref.subjectId, id, body),destroy: (ref: DataQualitySubjectRef, id: string): Promise<void> =>- isView(ref)- ? warehouseSavedQueriesChecksDestroy(projectId(), ref.subjectId, id)- : warehouseTablesChecksDestroy(projectId(), ref.subjectId, id),+ routesFor(ref).destroy(projectId(), ref.subjectId, id),run: (ref: DataQualitySubjectRef, id: string): Promise<DataQualitySuiteRunApi> =>- isView(ref)- ? warehouseSavedQueriesChecksRunCreate(projectId(), ref.subjectId, id)- : warehouseTablesChecksRunCreate(projectId(), ref.subjectId, id),+ routesFor(ref).run(projectId(), ref.subjectId, id),runAll: (ref: DataQualitySubjectRef): Promise<DataQualitySuiteRunApi> =>- isView(ref)- ? warehouseSavedQueriesChecksRunAllCreate(projectId(), ref.subjectId)- : warehouseTablesChecksRunAllCreate(projectId(), ref.subjectId),+ routesFor(ref).runAll(projectId(), ref.subjectId),runs: (ref: DataQualitySubjectRef, id: string): Promise<DataQualityCheckRunApi[]> =>- isView(ref)- ? warehouseSavedQueriesChecksRunsList(projectId(), ref.subjectId, id)- : warehouseTablesChecksRunsList(projectId(), ref.subjectId, id),+ routesFor(ref).runs(projectId(), ref.subjectId, id),checkTypes: (ref: DataQualitySubjectRef): Promise<DataQualityCheckTypeApi[]> =>- isView(ref)- ? warehouseSavedQueriesChecksCheckTypesList(projectId(), ref.subjectId)- : warehouseTablesChecksCheckTypesList(projectId(), ref.subjectId),+ routesFor(ref).checkTypes(projectId(), ref.subjectId),health: (ref: DataQualitySubjectRef): Promise<DataQualitySubjectHealthApi> =>- isView(ref)- ? warehouseSavedQueriesChecksHealthRetrieve(projectId(), ref.subjectId)- : warehouseTablesChecksHealthRetrieve(projectId(), ref.subjectId),+ routesFor(ref).health(projectId(), ref.subjectId),suiteRuns: (ref: DataQualitySubjectRef, limit: number): Promise<PaginatedDataQualitySuiteRunListApi> =>- isView(ref)- ? warehouseSavedQueriesCheckSuiteRunsList(projectId(), ref.subjectId, { limit })- : warehouseTablesCheckSuiteRunsList(projectId(), ref.subjectId, { limit }),+ routesFor(ref).suiteRuns(projectId(), ref.subjectId, { limit }),suiteRunRetrieve: (ref: DataQualitySubjectRef, id: string): Promise<DataQualitySuiteRunApi> =>- isView(ref)- ? warehouseSavedQueriesCheckSuiteRunsRetrieve(projectId(), ref.subjectId, id)- : warehouseTablesCheckSuiteRunsRetrieve(projectId(), ref.subjectId, id),+ routesFor(ref).suiteRunRetrieve(projectId(), ref.subjectId, id),suiteRunCheckRuns: (ref: DataQualitySubjectRef, id: string): Promise<DataQualityCheckRunApi[]> =>- isView(ref)- ? warehouseSavedQueriesCheckSuiteRunsCheckRunsList(projectId(), ref.subjectId, id)- : warehouseTablesCheckSuiteRunsCheckRunsList(projectId(), ref.subjectId, id),+ routesFor(ref).suiteRunCheckRuns(projectId(), ref.subjectId, id),}diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.tsindex dcbe6df0d0cc..1388971ad8fe 100644--- a/products/data_quality/frontend/generated/api.schemas.ts+++ b/products/data_quality/frontend/generated/api.schemas.ts@@ -7,15 +7,62 @@* 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+ * * `metric` - metric*/export type SubjectTypeEnumApi = (typeof SubjectTypeEnumApi)[keyof typeof SubjectTypeEnumApi]export const SubjectTypeEnumApi = {Table: 'table',View: 'view',+ Metric: 'metric',} as const/**@@ -51,6 +98,68 @@ 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@@ -122,28 +231,25 @@ export interface UserBasicApi {/*** Type-specific configuration, validated against the check type's JSON schema.*/-export type DataQualityOverviewCheckApiConfig = { [key: string]: unknown }+export type DataQualityCheckApiConfig = { [key: string]: unknown }/**- * A check plus where its subject can be opened, for the project-wide list.- *- * The per-subject surfaces already know their parent; only this one lists checks across every- * table and view, so only this one needs to say where each subject lives. The ids are resolved- * for a whole page at once and handed in through ``subject_locations`` in the context.+ * The subject is implied by the URL (the parent saved query or table), never part of the body.*/-export interface DataQualityOverviewCheckApi {+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' (a synced warehouse table) or 'view' (a saved query).+ /** Kind of catalog object being checked: 'table', 'view', or 'metric'.** * `table` - table- * * `view` - view */+ * * `view` - view+ * * `metric` - metric */readonly subject_type: SubjectTypeEnumApi/**- * Id of the table or view being checked -- the parent resource in the URL.+ * Id of the table, view, or metric being checked, from the parent resource in the URL.* @nullable*/readonly subject_uuid: string | null@@ -167,7 +273,7 @@ export interface DataQualityOverviewCheckApi {* * `custom_sql` - custom_sql */check_type: CheckTypeEnumApi/** Type-specific configuration, validated against the check type's JSON schema. */- config?: DataQualityOverviewCheckApiConfig+ config?: DataQualityCheckApiConfig/** 'error' failures mark the subject failing and notify; 'warn' failures only surface.** * `error` - error@@ -225,191 +331,46 @@ export interface DataQualityOverviewCheckApi {readonly created_at: string/** @nullable */readonly updated_at: string | null- /**- * Data modeling node of the view this check audits, or null when it is on no DAG or the subject is a table.- * @nullable- */- readonly subject_node_id: string | null- /**- * Warehouse source of the table this check audits, or null when the subject is a view.- * @nullable- */- readonly subject_source_id: string | null- /**- * Warehouse source schema of the table this check audits, or null when the subject is a view.- * @nullable- */- readonly subject_schema_id: string | null-}--export interface PaginatedDataQualityOverviewCheckListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: DataQualityOverviewCheckApi[]-}--/**- * Per-subject rollup, the same rule the information_schema.data_quality_health table uses.- */-export interface DataQualitySubjectHealthApi {- /** 'table' or 'view'. */- subject_type: string- /** Id of the table or view. */- subject_uuid: string- /** failing (an error-severity check failed), erroring (a check could not run), warn (only warn-severity failures), healthy, or unknown (nothing has run yet). */- health: string- /** How many enabled, non-deleted checks cover this subject. */- checks_total: number- /** How many of those checks last reported a failure. */- checks_failing: number}-export interface DataQualitySuiteRunApi {- readonly id: string- /** manual, materialization, or source_sync. */- readonly trigger: string- /** running, completed, failed, or empty (nothing matched the trigger). */- readonly status: string- /**- * 'table' or 'view' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.- * @nullable- */- readonly subject_type: string | null- /**- * Set when the run targets exactly one subject.- * @nullable- */- readonly subject_uuid: string | null- readonly workflow_id: string- readonly checks_passed: number- readonly checks_failed: number- readonly checks_errored: number- readonly checks_skipped: number- /** @nullable */- readonly started_at: string | null- /** @nullable */- readonly finished_at: string | null- /** Why the suite itself failed, as opposed to an individual check. */- readonly error: string- readonly created_at: string-}--export interface PaginatedDataQualitySuiteRunListApi {+export interface PaginatedDataQualityCheckListApi {count: number/** @nullable */next?: string | null/** @nullable */previous?: string | null- results: DataQualitySuiteRunApi[]-}--/**- * What to run in a project-wide suite run.- */-export interface DataQualityRunRequestApi {- /** Ids of the checks to run. Omit to run every enabled check in the project. */- check_ids?: string[]-}--/**- * Config this run executed, snapshotted so an edit to the check cannot rewrite history. Null for runs recorded before snapshots existed -- unknown, not 'same as the check has now'.- * @nullable- */-export type DataQualityCheckRunApiCheckConfig = { [key: string]: unknown } | null--export interface DataQualityCheckRunApi {- readonly id: string- /**- * The definition executed. Nulled rather than cascaded so history outlives hard deletes.- * @nullable- */- readonly quality_check: string | null- /**- * 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+ results: DataQualityCheckApi[]}/*** Type-specific configuration, validated against the check type's JSON schema.*/-export type DataQualityCheckApiConfig = { [key: string]: unknown }+export type PatchedDataQualityCheckApiConfig = { [key: string]: unknown }/*** The subject is implied by the URL (the parent saved query or table), never part of the body.*/-export interface DataQualityCheckApi {- 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. */description?: string- /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).+ /** Kind of catalog object being checked: 'table', 'view', or 'metric'.** * `table` - table- * * `view` - view */- readonly subject_type: SubjectTypeEnumApi+ * * `view` - view+ * * `metric` - metric */+ readonly subject_type?: SubjectTypeEnumApi/**- * Id of the table or view being checked -- the parent resource in the URL.+ * Id of the table, view, or metric being checked, from the parent resource in the URL.* @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@@ -424,9 +385,9 @@ export interface DataQualityCheckApi {* * `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?: DataQualityCheckApiConfig+ config?: PatchedDataQualityCheckApiConfig/** 'error' failures mark the subject failing and notify; 'warn' failures only surface.** * `error` - error@@ -440,26 +401,26 @@ export interface DataQualityCheckApi {* 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@@ -480,49 +441,80 @@ export interface DataQualityCheckApi {/** 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 PaginatedDataQualityCheckListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: DataQualityCheckApi[]+/**+ * 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}/*** Type-specific configuration, validated against the check type's JSON schema.*/-export type PatchedDataQualityCheckApiConfig = { [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 PatchedDataQualityCheckApi {- readonly id?: string+export interface DataQualityOverviewCheckApi {+ 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' (a synced warehouse table) or 'view' (a saved query).+ /** Kind of catalog object being checked: 'table', 'view', or 'metric'.** * `table` - table- * * `view` - view */- readonly subject_type?: SubjectTypeEnumApi+ * * `view` - view+ * * `metric` - metric */+ readonly subject_type: SubjectTypeEnumApi/**- * Id of the table or view being checked -- the parent resource in the URL.+ * Id of the table, view, or metric being checked, from the parent resource in the URL.* @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@@ -537,9 +529,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?: DataQualityOverviewCheckApiConfig/** 'error' failures mark the subject failing and notify; 'warn' failures only surface.** * `error` - error@@ -553,26 +545,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@@ -593,29 +585,69 @@ 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+ /**+ * 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}-/**- * JSON schema the config object is validated against.- */-export type DataQualityCheckTypeApiConfigSchema = { [key: string]: unknown }+export interface PaginatedDataQualityOverviewCheckListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: DataQualityOverviewCheckApi[]+}/**- * One entry of the check-type catalog, so an agent can author config without guessing.+ * What to run in a project-wide suite run.*/-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 interface DataQualityRunRequestApi {+ /** Ids of the checks to run. Omit to run every enabled check in the project. */+ check_ids?: string[]+}++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 DataQualityChecksListParams = {diff --git a/products/data_quality/frontend/generated/api.ts b/products/data_quality/frontend/generated/api.tsindex 268ca67d5cd6..7e3e6540b7b1 100644--- a/products/data_quality/frontend/generated/api.ts+++ b/products/data_quality/frontend/generated/api.ts@@ -9,6 +9,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ DataCatalogMetricsCheckSuiteRunsListParams,+ DataCatalogMetricsChecksListParams,DataQualityCheckApi,DataQualityCheckRunApi,DataQualityCheckTypeApi,@@ -44,6 +46,322 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getDataCatalogMetricsCheckSuiteRunsListUrl = (+ projectId: string,+ metricId: string,+ params?: DataCatalogMetricsCheckSuiteRunsListParams+) => {+ 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}/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}/`+}++/**+ * Read-only reports for this subject's check-suite executions.+ */+export const dataCatalogMetricsCheckSuiteRunsRetrieve = async (+ projectId: string,+ metricId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getDataCatalogMetricsCheckSuiteRunsRetrieveUrl(projectId, metricId, id), {+ ...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/`+}++/**+ * 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 dataCatalogMetricsChecksCreate = async (+ projectId: string,+ metricId: string,+ dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getDataCatalogMetricsChecksCreateUrl(projectId, metricId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataQualityCheckApi),+ })+}++export const getDataCatalogMetricsChecksRetrieveUrl = (projectId: string, metricId: string, id: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const dataCatalogMetricsChecksRetrieve = async (+ projectId: string,+ metricId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getDataCatalogMetricsChecksRetrieveUrl(projectId, metricId, id), {+ ...options,+ method: 'GET',+ })+}++export const getDataCatalogMetricsChecksUpdateUrl = (projectId: string, metricId: string, id: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/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 dataCatalogMetricsChecksUpdate = async (+ projectId: string,+ metricId: string,+ id: string,+ dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getDataCatalogMetricsChecksUpdateUrl(projectId, metricId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataQualityCheckApi),+ })+}++export const getDataCatalogMetricsChecksPartialUpdateUrl = (projectId: string, metricId: string, id: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/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 dataCatalogMetricsChecksPartialUpdate = async (+ projectId: string,+ metricId: string,+ id: string,+ patchedDataQualityCheckApi?: NonReadonly<PatchedDataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getDataCatalogMetricsChecksPartialUpdateUrl(projectId, metricId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedDataQualityCheckApi),+ })+}++export const getDataCatalogMetricsChecksDestroyUrl = (projectId: string, metricId: string, id: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const dataCatalogMetricsChecksDestroy = async (+ projectId: string,+ metricId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getDataCatalogMetricsChecksDestroyUrl(projectId, metricId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getDataCatalogMetricsChecksRunCreateUrl = (projectId: string, metricId: string, id: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/run/`+}++/**+ * Run this check now. Returns the suite run to poll for the report.+ */+export const dataCatalogMetricsChecksRunCreate = async (+ projectId: string,+ metricId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getDataCatalogMetricsChecksRunCreateUrl(projectId, metricId, id), {+ ...options,+ method: 'POST',+ })+}++export const getDataCatalogMetricsChecksRunsListUrl = (projectId: string, metricId: string, id: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/${id}/runs/`+}++/**+ * Recent run history for this check, newest first.+ */+export const dataCatalogMetricsChecksRunsList = async (+ projectId: string,+ metricId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualityCheckRunApi[]> => {+ return apiMutator<DataQualityCheckRunApi[]>(getDataCatalogMetricsChecksRunsListUrl(projectId, metricId, 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 (+ 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/`+}++/**+ * 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',+ })+}++export const getDataCatalogMetricsChecksRunAllCreateUrl = (projectId: string, metricId: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${metricId}/checks/run_all/`+}++/**+ * Run every enabled check on this table or view. Returns the suite run to poll.+ */+export const dataCatalogMetricsChecksRunAllCreate = async (+ projectId: string,+ metricId: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getDataCatalogMetricsChecksRunAllCreateUrl(projectId, metricId), {+ ...options,+ method: 'POST',+ })+}+export const getDataQualityChecksListUrl = (projectId: string, params?: DataQualityChecksListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/data_quality/frontend/generated/api.zod.ts b/products/data_quality/frontend/generated/api.zod.tsindex 268781339680..26c9096df3d1 100644--- a/products/data_quality/frontend/generated/api.zod.ts+++ b/products/data_quality/frontend/generated/api.zod.ts@@ -9,6 +9,235 @@*/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.+ */+export const dataCatalogMetricsChecksCreateBodyNameOneMax = 128++export const dataCatalogMetricsChecksCreateBodyNameOneRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataCatalogMetricsChecksCreateBodyNameTwoMax = 0++export const dataCatalogMetricsChecksCreateBodyColumnNameMax = 400++export const dataCatalogMetricsChecksCreateBodyAiModelMax = 128++export const dataCatalogMetricsChecksCreateBodyConfidenceMin = 0+export const dataCatalogMetricsChecksCreateBodyConfidenceMax = 1++export const DataCatalogMetricsChecksCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .union([+ zod+ .string()+ .max(dataCatalogMetricsChecksCreateBodyNameOneMax)+ .regex(dataCatalogMetricsChecksCreateBodyNameOneRegExp),+ zod.string().max(dataCatalogMetricsChecksCreateBodyNameTwoMax),+ ])+ .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'+ )+ .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(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.')+/*** 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.*/diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.tsindex 527ac546ab24..d8ade838a639 100644--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.test.ts@@ -7,6 +7,7 @@ import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'import {+ dataCatalogMetricsChecksDestroy,dataQualityChecksHealthList,dataQualityChecksList,dataQualityRunsCreate,@@ -40,6 +41,7 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({}))jest.mock('products/data_quality/frontend/generated/api', () => ({+ dataCatalogMetricsChecksDestroy: jest.fn(),dataQualityChecksList: jest.fn(),dataQualityChecksHealthList: jest.fn(),dataQualityRunsCreate: jest.fn(),@@ -386,6 +388,19 @@ describe('dataQualityOverviewLogic', () => {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'))await mountLogic()@@ -512,6 +527,16 @@ describe('dataQualityOverviewLogic', () => {{ subject_type: 'table', subject_uuid: 'uuid-table', subject_source_id: null },'/data-management/sources/self-managed-uuid-table/schemas',],+ [+ 'a metric on its catalog page',+ { subject_type: 'metric', subject_uuid: 'uuid-metric', subject_metric_name: 'signups' },+ '/data-catalog/metrics/signups',+ ],+ [+ 'a metric whose name did not come through',+ { subject_type: 'metric', subject_uuid: 'uuid-metric', subject_metric_name: null },+ null,+ ],])('links %s', (_case, overrides, expected) => {expect(subjectDetailUrl(buildCheck('check-1', 'orders', null, overrides))).toEqual(expected)})diff --git a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts b/products/data_quality/frontend/overview/dataQualityOverviewLogic.tsindex 964111230aa5..0ef86e851ab1 100644--- a/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts+++ b/products/data_quality/frontend/overview/dataQualityOverviewLogic.ts@@ -80,6 +80,10 @@ export function subjectDetailUrl(check: DataQualityOverviewCheckApi): string | nif (check.subject_type === 'view') {return check.subject_node_id ? urls.nodeDetail(check.subject_node_id, 'tests') : null}+ if (check.subject_type === 'metric') {+ // The catalog addresses a metric by name, so a row that came without one has no route.+ return check.subject_metric_name ? urls.dataCatalogMetric(check.subject_metric_name) : null+ }if (check.subject_source_id && check.subject_schema_id) {return urls.dataWarehouseSourceSchema(check.subject_source_id, check.subject_schema_id)}diff --git a/products/data_quality/mcp/tools.yaml b/products/data_quality/mcp/tools.yamlindex bf35922b3541..0a68ff18907e 100644--- a/products/data_quality/mcp/tools.yaml+++ b/products/data_quality/mcp/tools.yaml@@ -9,6 +9,48 @@ 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-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-update:+ operation: data_catalog_metrics_checks_update+ enabled: falsedata-quality-check-create-on-table:operation: warehouse_tables_checks_createenabled: truediff --git a/products/notifications/backend/tests/test_api.py b/products/notifications/backend/tests/test_api.pyindex eb56d0063094..2c9e0130f5ce 100644--- a/products/notifications/backend/tests/test_api.py+++ b/products/notifications/backend/tests/test_api.py@@ -10,8 +10,10 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework.test import APIClient-from posthog.models import Organization, Team, User+from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, Team, User+from products.access_control.backend.models.access_control import AccessControlfrom products.notifications.backend.cache import _unread_count_cache_keyfrom products.notifications.backend.models import NotificationArchiveState, NotificationEvent, NotificationReadState@@ -53,6 +55,23 @@ class TestNotificationsAPI(BaseTest):assert resp.json()["results"][0]["title"] == "Test notification"assert resp.json()["results"][0]["read"] is False+ def test_catalog_notification_disappears_after_access_revocation(self) -> None:+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]+ self.organization.save(update_fields=["available_product_features"])+ self.event.resource_type = "data_catalog"+ self.event.save(update_fields=["resource_type"])+ url = f"/api/environments/{self.team.id}/notifications/"+ assert [event["id"] for event in self.client.get(url).json()["results"]] == [str(self.event.id)]+ AccessControl.objects.create(+ team=self.team,+ resource="data_catalog",+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=self.user),+ access_level="none",+ )+ cache.clear()+ assert self.client.get(url).json()["results"] == []+ assert self.client.get(url + "unread_count/").json()["count"] == 0+def test_unread_count(self):resp = self.client.get(f"/api/environments/{self.team.id}/notifications/unread_count/")assert resp.status_code == 200diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex d2c7802a57d8..112069cff56c 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -19,6 +19,7 @@ exception is ``soft_delete_tables``: consumers may not iterate the model to call"""from collections.abc import Collection+from typing import TYPE_CHECKINGfrom uuid import UUIDfrom django.db.models import Prefetch, QuerySet@@ -60,6 +61,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceTypefrom . import contracts+if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl+__all__ = [# capability functions"get_source",@@ -73,6 +77,7 @@ __all__ = ["get_queryable_table","resolve_object_by_name","direct_access_table_ids",+ "allowed_table_ids","list_tables_for_source","list_jobs_for_source","list_column_statistics",@@ -375,6 +380,56 @@ def direct_access_table_ids(team_id: int) -> set[UUID]:return set(rows)+def allowed_table_ids(+ team_id: int,+ user_access_control: "UserAccessControl",+ *,+ required_level: "AccessControlLevel" = "viewer",+ ids: Collection[UUID] | None = None,+) -> frozenset[UUID]:+ """The queryable tables this caller may reach at ``required_level``.++ ``ids`` narrows the objects loaded before their access controls are read, so a caller asking+ about one table does not pay for the whole warehouse. ``None`` asks about every table; an empty+ collection asks about none.+ """+ if ids is not None and not ids:+ return frozenset()+ if ids is None:+ return user_access_control.allowed_object_ids(+ "warehouse_table",+ team_id,+ required_level,+ lambda: _resolve_allowed_table_ids(team_id, user_access_control, required_level, None),+ )+ return _resolve_allowed_table_ids(team_id, user_access_control, required_level, ids)+++def _resolve_allowed_table_ids(+ team_id: int,+ user_access_control: "UserAccessControl",+ required_level: "AccessControlLevel",+ ids: Collection[UUID] | None,+) -> frozenset[UUID]:+ candidates = _DataWarehouseTable.raw_objects.queryable().filter(team_id=team_id)+ if ids is not None:+ candidates = candidates.filter(id__in=ids)+ tables = list(+ candidates.select_related("external_data_source").only(+ "id", "created_by_id", "external_data_source_id", "external_data_source__id"+ )+ )+ sources = {+ table.external_data_source_id: table.external_data_source+ for table in tables+ if table.external_data_source is not None+ }+ user_access_control.preload_object_access_controls([*tables, *sources.values()])+ return frozenset(+ table.id for table in tables if user_access_control.check_access_level_for_object(table, required_level)+ )++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/products/warehouse_sources/backend/tests/test_facade.py b/products/warehouse_sources/backend/tests/test_facade.pyindex cd603f302283..f9f5157a5653 100644--- a/products/warehouse_sources/backend/tests/test_facade.py+++ b/products/warehouse_sources/backend/tests/test_facade.py@@ -2,8 +2,14 @@ import uuidfrom posthog.test.base import BaseTest+from parameterized import parameterized++from posthog.constants import AvailableFeaturefrom posthog.models import Team+from posthog.models.organization import OrganizationMembership+from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl+from products.access_control.backend.models.access_control import AccessControlfrom products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfigfrom products.warehouse_sources.backend.facade import api, contracts, hogql, hooks, sources, temporalfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -177,6 +183,72 @@ class TestWarehouseSourcesFacade(BaseTest):assert result.name == "my_table"assert result.external_data_source_id == self.source.id+ @parameterized.expand(+ [+ ("legacy_viewer", False, "viewer"),+ ("legacy_editor", False, "editor"),+ ("most_specific_viewer", True, "viewer"),+ ("most_specific_editor", True, "editor"),+ ]+ )+ def test_allowed_table_ids_preserves_object_and_source_grants(+ self, _name: str, most_specific: bool, required_level: AccessControlLevel+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.uses_most_specific_access_resolution = most_specific+ self.organization.save(update_fields=["available_product_features", "uses_most_specific_access_resolution"])+ member = self._create_user("[email protected]")+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)+ AccessControl.objects.create(team=self.team, resource="warehouse_objects", access_level="none")+ AccessControl.objects.create(+ team=self.team,+ resource="external_data_source",+ resource_id=str(self.source.id),+ organization_member=membership,+ access_level="viewer",+ )+ granted = DataWarehouseTable.objects.create(team=self.team, name="granted", format="Parquet")+ overridden = DataWarehouseTable.objects.create(+ team=self.team, name="overridden", format="Parquet", external_data_source=self.source+ )+ ungranted = DataWarehouseTable.objects.create(team=self.team, name="ungranted", format="Parquet")+ owned = DataWarehouseTable.objects.create(team=self.team, name="owned", format="Parquet", created_by=member)+ DataWarehouseTable.objects.create(+ team=self.team, name="deleted", format="Parquet", created_by=member, deleted=True+ )+ other_team = Team.objects.create(organization=self.organization, name="other")+ DataWarehouseTable.objects.create(team=other_team, name="other", format="Parquet", created_by=member)+ for table, level in [(granted, "editor"), (overridden, "none")]:+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_table",+ resource_id=str(table.id),+ organization_member=membership,+ access_level=level,+ )++ access = UserAccessControl(member, team=self.team)+ expected = frozenset({granted.id, owned.id} | ({self.table.id} if required_level == "viewer" else set()))+ assert api.allowed_table_ids(self.team.id, access, required_level=required_level) == expected+ with self.assertNumQueries(0):+ assert api.allowed_table_ids(self.team.id, access, required_level=required_level) == expected++ narrowed = api.allowed_table_ids(+ self.team.id, access, required_level=required_level, ids=[granted.id, ungranted.id]+ )+ assert narrowed == frozenset({granted.id})+ with self.assertNumQueries(0):+ assert api.allowed_table_ids(self.team.id, access, required_level=required_level, ids=[]) == frozenset()++ membership.level = OrganizationMembership.Level.ADMIN+ membership.save(update_fields=["level"])+ admin = UserAccessControl(member, team=self.team)+ assert api.allowed_table_ids(self.team.id, admin, required_level=required_level) == frozenset(+ {self.table.id, granted.id, overridden.id, ungranted.id, owned.id}+ )+def test_list_jobs_for_source_carries_source_fields(self) -> None:job = ExternalDataJob.objects.create(team_id=self.team.pk,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8beb7e5aa704..d2258cfdb96f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22707,6 +22707,7 @@ export namespace Schemas {/*** * `table` - table* * `view` - view+ * * `metric` - metric*/export type SubjectTypeEnum = typeof SubjectTypeEnum[keyof typeof SubjectTypeEnum];@@ -22714,6 +22715,7 @@ export namespace Schemas {export const SubjectTypeEnum = {Table: 'table',View: 'view',+ Metric: 'metric',} as const;/**@@ -22737,13 +22739,14 @@ export namespace Schemas {name?: string;/** Why this check exists and what a failure means. */description?: string;- /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).+ /** Kind of catalog object being checked: 'table', 'view', or 'metric'.** * `table` - table- * * `view` - view */+ * * `view` - view+ * * `metric` - metric */readonly subject_type: SubjectTypeEnum;/**- * Id of the table or view being checked -- the parent resource in the URL.+ * Id of the table, view, or metric being checked, from the parent resource in the URL.* @nullable*/readonly subject_uuid: string | null;@@ -22940,13 +22943,14 @@ export namespace Schemas {name?: string;/** Why this check exists and what a failure means. */description?: string;- /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).+ /** Kind of catalog object being checked: 'table', 'view', or 'metric'.** * `table` - table- * * `view` - view */+ * * `view` - view+ * * `metric` - metric */readonly subject_type: SubjectTypeEnum;/**- * Id of the table or view being checked -- the parent resource in the URL.+ * Id of the table, view, or metric being checked, from the parent resource in the URL.* @nullable*/readonly subject_uuid: string | null;@@ -23043,6 +23047,11 @@ export namespace Schemas {* @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;}/**@@ -23057,9 +23066,9 @@ export namespace Schemas {* Per-subject rollup, the same rule the information_schema.data_quality_health table uses.*/export interface DataQualitySubjectHealth {- /** 'table' or 'view'. */+ /** 'table', 'view', or 'metric'. */subject_type: string;- /** Id of the table or view. */+ /** 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;@@ -23071,12 +23080,12 @@ export namespace Schemas {export interface DataQualitySuiteRun {readonly id: string;- /** manual, materialization, or source_sync. */+ /** manual, materialization, source_sync, or scheduled. */readonly trigger: string;/** running, completed, failed, or empty (nothing matched the trigger). */readonly status: string;/**- * 'table' or 'view' when the run targets exactly one subject, including a run of a single check on that subject; null for a run spanning several subjects.+ * '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;@@ -63712,13 +63721,14 @@ export namespace Schemas {name?: string;/** Why this check exists and what a failure means. */description?: string;- /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).+ /** Kind of catalog object being checked: 'table', 'view', or 'metric'.** * `table` - table- * * `view` - view */+ * * `view` - view+ * * `metric` - metric */readonly subject_type?: SubjectTypeEnum;/**- * Id of the table or view being checked -- the parent resource in the URL.+ * Id of the table, view, or metric being checked, from the parent resource in the URL.* @nullable*/readonly subject_uuid?: string | null;@@ -95895,6 +95905,28 @@ 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.diff --git a/tach.toml b/tach.tomlindex a7a02da605c1..3577b33684b4 100644--- a/tach.toml+++ b/tach.toml@@ -1411,6 +1411,7 @@ from = [path = "products.data_catalog"depends_on = ["posthog",+ "products.data_quality","products.data_tools","products.product_analytics","products.warehouse_sources",@@ -1436,6 +1437,7 @@ layer = "modules"path = "products.data_quality"depends_on = ["posthog",+ "products.data_catalog","products.data_modeling","products.notifications","products.warehouse_sources", "products.access_control",