: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 the checks REST API and information_schema tables (#74693)
Thiago Salvatore77124eebfe3b
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 5b399015f8aa..4231558e9796 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -93,6 +93,7 @@ from posthog.hogql.database.schema.hog_invocation_results import HogInvocationRefrom posthog.hogql.database.schema.information_schema import (direct_connection_information_schema_node,disable_data_catalog,+ disable_data_quality,)from posthog.hogql.database.schema.log_entries import (BatchExportLogEntriesTable,@@ -207,7 +208,7 @@ class SerializedField:description: str | None = None[email protected](frozen=False)class HogQLDatabaseSources:"""All I/O Database._build_from_sources needs, fetched up front by Database._fetch_sources so thebuild phase runs without any queries."""@@ -219,6 +220,7 @@ class HogQLDatabaseSources:is_managed_viewset_enabled: boolis_hogql_warehouse_access_control_enabled: boolis_data_catalog_enabled: bool+ is_data_quality_enabled: bool# Userless internal contexts that must resolve every warehouse table/view; skips access controlbypass_warehouse_access_control: booldirect_connection_metadata: dict[str, Any] | None@@ -1362,10 +1364,12 @@ class Database(BaseModel):send_feature_flag_events=False,)- # Function-local + facade-only: keeps the data_catalog product off the django.setup() path.+ # Function-local + facade-only: keeps the products off the django.setup() path.from products.data_catalog.backend.facade.flags import is_data_catalog_enabled # noqa: PLC0415+ from products.data_quality.backend.facade.flags import is_data_quality_checks_enabled # noqa: PLC0415data_catalog_enabled = is_data_catalog_enabled(team)+ data_quality_enabled = is_data_quality_checks_enabled(team)with timings.measure("database", emit_span=True):# Function-local: keeps the direct-SQL driver imports off the django.setup() path.@@ -1610,6 +1614,7 @@ class Database(BaseModel):is_managed_viewset_enabled=is_managed_viewset_enabled,is_hogql_warehouse_access_control_enabled=is_hogql_warehouse_access_control_enabled,is_data_catalog_enabled=data_catalog_enabled,+ is_data_quality_enabled=data_quality_enabled,# Managed warehouse is a built-in project datastore and has no warehouse-object ACL surface.# Principals that skip warehouse access control by design:# - synthetic users (project-wide service tokens, bypass object-level RBAC)@@ -1672,7 +1677,7 @@ class Database(BaseModel):with timings.measure("filter_system_tables_for_user", emit_span=True):database._apply_system_table_access(sources.user_access_control, sources.denied_system_table_names)- if not sources.is_data_catalog_enabled:+ if not sources.is_data_catalog_enabled or not sources.is_data_quality_enabled:system_node = database.tables.children.get("system")info_schema = (system_node.children.get("information_schema")@@ -1680,7 +1685,10 @@ class Database(BaseModel):else None)if info_schema is not None and hasattr(info_schema, "children"):- disable_data_catalog(info_schema)+ if not sources.is_data_catalog_enabled:+ disable_data_catalog(info_schema)+ if not sources.is_data_quality_enabled:+ disable_data_quality(info_schema)with timings.measure("modifiers", emit_span=True):if not database._is_direct_query():diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.pyindex 3edb2e16bc08..365f9a1176fc 100644--- a/posthog/hogql/database/schema/information_schema.py+++ b/posthog/hogql/database/schema/information_schema.py@@ -15,6 +15,7 @@ semantic layers — fetched lazily only when these tables are queried.import jsonimport hashlib+from collections import defaultdictfrom typing import TYPE_CHECKING, Any, NamedTuple, Optionalfrom django.db.models import Q@@ -856,6 +857,54 @@ _METRICS_COLUMNS: list[tuple[str, str]] = [("created_at", _STRING),]+_DATA_QUALITY_CHECKS_COLUMNS: list[tuple[str, str]] = [+ ("id", _STRING),+ ("name", _NULLABLE_STRING),+ ("subject_type", _STRING),+ ("subject_uuid", _NULLABLE_STRING),+ ("subject_name", _STRING),+ ("subject_status", _STRING),+ ("column_name", _NULLABLE_STRING),+ ("check_type", _STRING),+ ("config", _NULLABLE_STRING),+ ("severity", _STRING),+ ("enabled", _BOOLEAN),+ ("last_status", _NULLABLE_STRING),+ ("last_run_at", _NULLABLE_STRING),+ ("created_at", _STRING),+]++_DATA_QUALITY_CHECK_RUNS_COLUMNS: list[tuple[str, str]] = [+ ("id", _STRING),+ ("check_id", _NULLABLE_STRING),+ ("suite_run_id", _STRING),+ ("subject_type", _STRING),+ ("subject_uuid", _STRING),+ ("subject_name", _STRING),+ ("check_type", _STRING),+ ("column_name", _NULLABLE_STRING),+ ("status", _STRING),+ ("failed_row_count", _NULLABLE_INTEGER),+ ("observed_value", _NULLABLE_FLOAT),+ ("error", _NULLABLE_STRING),+ ("duration_ms", _NULLABLE_INTEGER),+ ("created_at", _STRING),+]++_DATA_QUALITY_HEALTH_COLUMNS: list[tuple[str, str]] = [+ ("subject_type", _STRING),+ ("subject_uuid", _STRING),+ ("subject_name", _STRING),+ ("health", _STRING),+ ("checks_total", _INTEGER),+ ("checks_failing", _INTEGER),+ ("checks_erroring", _INTEGER),+ ("last_run_at", _NULLABLE_STRING),+]++# Bounded so a chatty project cannot turn one information_schema query into a full history scan.+_CHECK_RUNS_WINDOW = 500+_CERTIFICATIONS_COLUMNS: list[tuple[str, str]] = [("id", _STRING),("target_name", _STRING),@@ -988,6 +1037,167 @@ def _catalog_metrics(context: "HogQLContext", allowed: Optional[frozenset[str]])return []+def _can_read_data_quality(context: "HogQLContext") -> bool:+ """Whether the caller can read warehouse metadata, mirroring the REST viewsets' resource gate.++ Check rows are derived warehouse metadata -- they name columns and carry compiled queries -- so+ reading them is warehouse read access (either resource resolves through warehouse_objects).+ Fails closed with no access-control context (service tokens, shared links).+ """+ access_control = context.database.user_access_control if context.database is not None else None+ if access_control is None:+ access_control = context.user_access_control+ 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")+++def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[str]]) -> list[list[Any]]:+ """Load the team's data quality check definitions as information_schema rows (fail-soft).++ Hides checks whose subject table or view the caller is denied: the row carries the compiled+ ``config`` and the denormalized subject name, so leaking it leaks the shape of a table the member+ cannot read. Mirrors the metric loader's ``_references_denied_table`` pass.+ """+ team_id = context.team_id+ if team_id is None or not _can_read_data_quality(context):+ return []+ from products.data_quality.backend.facade.models import DataQualityCheck # noqa: PLC0415++ try:+ denied = 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")+ if allowed is not None:+ queryset = queryset.filter(name__in=allowed)+ return [+ [+ str(check.id),+ check.name or None,+ check.subject_type,+ str(check.subject_uuid) if check.subject_uuid else None,+ check.subject_name,+ check.subject_status,+ check.column_name or None,+ check.check_type,+ json.dumps(check.config) if check.config else None,+ check.severity,+ check.enabled,+ check.last_status or None,+ check.last_run_at.isoformat() if check.last_run_at else None,+ check.created_at.isoformat(),+ ]+ for check in queryset+ if not _references_denied_table([check.subject_name], denied)+ ]+ except Exception:+ logger.exception("information_schema: failed to load data quality checks", team_id=team_id)+ return []+++def _data_quality_check_runs(context: "HogQLContext", allowed: Optional[frozenset[str]]) -> list[list[Any]]:+ """Load the team's most recent check executions as information_schema rows (fail-soft).++ Runs outlive their definitions on purpose: a deleted check's history stays queryable so a+ regression can still be dated. Rows for a denied subject are dropped *before* the window is+ applied, so a member cannot read the leaked counts nor infer their number from a short page.+ """+ team_id = context.team_id+ if team_id is None or not _can_read_data_quality(context):+ return []+ from products.data_quality.backend.facade.models import DataQualityCheckRun # noqa: PLC0415++ try:+ denied = context.database._denied_tables if context.database is not None else set()+ base = DataQualityCheckRun.objects.for_team(team_id)+ if allowed is not None:+ base = base.filter(subject_name__in=allowed)+ # Drop denied subjects in SQL (not by scanning rows in Python) so the window is a bounded+ # LIMIT rather than a full-history scan that skips denied rows one by one. The distinct set of+ # subject names is small, so resolving which are denied is cheap; excluding them before the+ # window still drops denied rows before it applies.+ if denied:+ blocked = {+ name+ for name in base.values_list("subject_name", flat=True).distinct()+ if _references_denied_table([name], denied)+ }+ if blocked:+ base = base.exclude(subject_name__in=blocked)+ return [+ [+ str(run.id),+ str(run.quality_check_id) if run.quality_check_id else None,+ str(run.suite_run_id),+ run.subject_type,+ str(run.subject_uuid),+ run.subject_name,+ run.check_type,+ run.column_name or None,+ run.status,+ run.failed_row_count,+ run.observed_value,+ run.error or None,+ run.duration_ms,+ run.created_at.isoformat(),+ ]+ for run in base.order_by("-created_at")[:_CHECK_RUNS_WINDOW]+ ]+ except Exception:+ logger.exception("information_schema: failed to load data quality check runs", team_id=team_id)+ return []+++def _data_quality_health(context: "HogQLContext", allowed: Optional[frozenset[str]]) -> list[list[Any]]:+ """Roll the team's checks up per subject (fail-soft), using the same rule as the REST endpoint.++ Subjects the caller is denied never surface: the rollup counts (total/failing/erroring) are a+ count oracle over rows the member cannot read otherwise.+ """+ team_id = context.team_id+ if team_id is None or not _can_read_data_quality(context):+ return []+ from products.data_quality.backend.facade.api import CheckStatusRow, roll_up_health # noqa: PLC0415+ from products.data_quality.backend.facade.models import DataQualityCheck # noqa: PLC0415++ try:+ denied = 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)+ if allowed is not None:+ checks_qs = checks_qs.filter(subject_name__in=allowed)+ by_subject: dict[tuple[str, str], list[Any]] = defaultdict(list)+ for check in checks_qs:+ if _references_denied_table([check.subject_name], denied):+ continue+ # A hard-deleted subject has no id to key a rollup on, and its checks only skip.+ if check.subject_uuid is None:+ continue+ by_subject[(check.subject_type, str(check.subject_uuid))].append(check)++ rows: list[list[Any]] = []+ for (subject_type, subject_uuid), checks in by_subject.items():+ last_runs = [check.last_run_at for check in checks if check.last_run_at]+ rows.append(+ [+ subject_type,+ subject_uuid,+ checks[0].subject_name,+ roll_up_health(+ CheckStatusRow(severity=check.severity, last_status=check.last_status) for check in checks+ ),+ len(checks),+ sum(1 for check in checks if check.last_status == "failed"),+ sum(1 for check in checks if check.last_status == "errored"),+ max(last_runs).isoformat() if last_runs else None,+ ]+ )+ return rows+ except Exception:+ logger.exception("information_schema: failed to roll up data quality health", team_id=team_id)+ return []++def _certification_key(table_name: str, table: Table, table_type: str, materialized_view_ids: dict[str, str]) -> Optional[_CertificationKey]:@@ -1664,6 +1874,163 @@ class InformationSchemaRelationshipProposalsTable(InformationSchemaTable):return "system__information_schema__relationship_proposals"+class InformationSchemaDataQualityChecksTable(LazyTable):+ description: str = (+ "Data quality checks defined on the project's warehouse tables and views (dbt-test style); 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 "+ "rollup. An empty result means the subject has no checks yet."+ )+ 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_uuid": _string_field(+ "subject_uuid", nullable=True, description="UUID of the checked table or view; NULL once hard-deleted."+ ),+ "subject_name": _string_field("subject_name", description="Queryable name of the checked table or view."),+ "subject_status": _string_field(+ "subject_status", description="'active', or 'orphaned' once the subject stops resolving."+ ),+ "column_name": _string_field(+ "column_name", nullable=True, description="Checked column; NULL for table-scoped types like row_count."+ ),+ "check_type": _string_field(+ "check_type",+ description="not_null, unique, accepted_values, relationships, row_count, freshness, or custom_sql.",+ ),+ "config": _string_field("config", nullable=True, description="Type-specific configuration, as JSON."),+ "severity": _string_field(+ "severity", description="'error' (failure marks the subject failing) or 'warn' (surfaces only)."+ ),+ "enabled": BooleanDatabaseField(name="enabled", description="Disabled checks are never run."),+ "last_status": _string_field(+ "last_status",+ nullable=True,+ description="Newest outcome: passed, failed, errored, or skipped. NULL when never run.",+ ),+ "last_run_at": _string_field("last_run_at", nullable=True, description="ISO timestamp of the newest run."),+ "created_at": _string_field("created_at", description="ISO timestamp when the check was created."),+ }++ def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:+ allowed = _pushdown_table_filter(node, "name")+ return _rows_select(+ context,+ "data_quality_checks",+ _DATA_QUALITY_CHECKS_COLUMNS,+ _data_quality_checks(context, allowed),+ allowed,+ )++ def to_printed_clickhouse(self, context: "HogQLContext") -> str:+ return "information_schema.data_quality_checks"++ def to_printed_hogql(self) -> str:+ return "system__information_schema__data_quality_checks"+++class InformationSchemaDataQualityCheckRunsTable(LazyTable):+ description: str = (+ "Recent data quality check executions; one row per run, newest first, bounded to the latest few hundred. "+ "failed_row_count is how many rows violated the assertion (0 is a pass); observed_value is the check's "+ "headline number and is recorded on passes too, so it reads as a time series. Failing rows are never "+ "stored -- re-run the check's compiled query via the REST API to see them. Runs for deleted checks stay "+ "queryable, with check_id NULL."+ )+ fields: dict[str, FieldOrTable] = {+ "id": _string_field("id", description="Stable UUID of this execution."),+ "check_id": _string_field(+ "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_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."),+ "status": _string_field(+ "status",+ description="'passed', 'failed' (assertion violated), 'errored' (could not run), or 'skipped'.",+ ),+ "failed_row_count": IntegerDatabaseField(+ name="failed_row_count",+ nullable=True,+ description="Rows violating the assertion. NULL for bounds checks like row_count.",+ ),+ "observed_value": FloatDatabaseField(+ name="observed_value",+ nullable=True,+ description="The check's headline number (row count, staleness in seconds, ...).",+ ),+ "error": _string_field("error", nullable=True, description="Why the run errored, when status='errored'."),+ "duration_ms": IntegerDatabaseField(name="duration_ms", nullable=True, description="How long the run took."),+ "created_at": _string_field("created_at", description="ISO timestamp of the run."),+ }++ def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:+ allowed = _pushdown_table_filter(node, "subject_name")+ return _rows_select(+ context,+ "data_quality_check_runs",+ _DATA_QUALITY_CHECK_RUNS_COLUMNS,+ _data_quality_check_runs(context, allowed),+ allowed,+ )++ def to_printed_clickhouse(self, context: "HogQLContext") -> str:+ return "information_schema.data_quality_check_runs"++ def to_printed_hogql(self) -> str:+ return "system__information_schema__data_quality_check_runs"+++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, "+ "'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."),+ "health": _string_field(+ "health", description="'failing', 'erroring', 'warn', 'healthy', or 'unknown'. Worst outcome wins."+ ),+ "checks_total": IntegerDatabaseField(+ name="checks_total", description="Enabled, non-deleted checks covering this subject."+ ),+ "checks_failing": IntegerDatabaseField(+ name="checks_failing", description="How many of those last reported a failure."+ ),+ "checks_erroring": IntegerDatabaseField(+ name="checks_erroring", description="How many of those last failed to run at all."+ ),+ "last_run_at": _string_field(+ "last_run_at", nullable=True, description="ISO timestamp of the most recent run on this subject."+ ),+ }++ def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:+ allowed = _pushdown_table_filter(node, "subject_name")+ return _rows_select(+ context,+ "data_quality_health",+ _DATA_QUALITY_HEALTH_COLUMNS,+ _data_quality_health(context, allowed),+ allowed,+ )++ def to_printed_clickhouse(self, context: "HogQLContext") -> str:+ return "information_schema.data_quality_health"++ def to_printed_hogql(self) -> str:+ return "system__information_schema__data_quality_health"++def information_schema_node() -> TableNode:"""The `information_schema` namespace, mounted under `system` (see `SystemTables.children`)."""return TableNode(@@ -1678,6 +2045,15 @@ def information_schema_node() -> TableNode:"relationship_proposals": TableNode(name="relationship_proposals", table=InformationSchemaRelationshipProposalsTable()),+ "data_quality_checks": TableNode(+ name="data_quality_checks", table=InformationSchemaDataQualityChecksTable()+ ),+ "data_quality_check_runs": TableNode(+ name="data_quality_check_runs", table=InformationSchemaDataQualityCheckRunsTable()+ ),+ "data_quality_health": TableNode(+ name="data_quality_health", table=InformationSchemaDataQualityHealthTable()+ ),},)@@ -1716,3 +2092,9 @@ def disable_data_catalog(info_schema: TableNode) -> None:relationships.table.fields.pop("confidence", None)relationships.table.fields.pop("reasoning", None)relationships.table.description = _RELATIONSHIPS_DESCRIPTION+++def disable_data_quality(info_schema: TableNode) -> None:+ info_schema.children.pop("data_quality_checks", None)+ info_schema.children.pop("data_quality_check_runs", None)+ info_schema.children.pop("data_quality_health", None)diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.pyindex d8e58b7a04dd..1fed2bb0f086 100644--- a/posthog/hogql_queries/access_controlled_resources.py+++ b/posthog/hogql_queries/access_controlled_resources.py@@ -32,6 +32,18 @@ _DATA_CATALOG_INFORMATION_SCHEMA_TABLES = frozenset(})+# `system.information_schema` tables gated behind warehouse read access (see+# `_can_read_data_quality` in information_schema.py). They carry check definitions, run outcomes, and+# per-subject health. A query touching any of these must partition the cache by warehouse access,+# or an allowed user's cached rows would be served to a denied user on a cache hit.+_DATA_QUALITY_INFORMATION_SCHEMA_TABLES = frozenset(+ {+ "system.information_schema.data_quality_checks",+ "system.information_schema.data_quality_check_runs",+ "system.information_schema.data_quality_health",+ }+)+def queried_access_controlled_resources(query, team: "Team") -> Optional[set[str]]:"""The set of access-control scope names a query reads, e.g. "notebook", "warehouse_table".@@ -82,6 +94,16 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[strscopes.add("warehouse_table")scopes.add("warehouse_view")+ # The data-quality information_schema tables are gated on warehouse read access, and their+ # rows are hidden per the caller's warehouse-object denials (the loaders drop a+ # check/run/health row whose subject table or view the caller can't see). Without this, two+ # users with different warehouse grants share a cache key and the denied one is served the+ # 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("warehouse_table")+ scopes.add("warehouse_view")+# Connection-scoped queries read the external source's upstream data directly. Their tables# are virtual (named by ExternalDataSchema.name) or physical direct rows, which the# warehouse-table name lookup below can't reliably match — so fail closed and partition thediff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.pyindex 65ed1a06accd..c105d247e8a0 100644--- a/posthog/hogql_queries/test/test_access_controlled_resources.py+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py@@ -96,6 +96,25 @@ class TestQueriedAccessControlledResources(BaseTest):"select reasoning from system.information_schema.relationship_proposals",{"data_catalog", "external_data_source", "warehouse_table", "warehouse_view"},),+ # The data-quality information_schema tables partition on warehouse object access, which is+ # what their loaders gate on, and their rows are hidden per-object via the caller's denied+ # tables — so an allowed user's cached check configs / run counts can't leak to a user with+ # less warehouse access on a cache hit.+ (+ "information_schema_data_quality_checks",+ "select config from system.information_schema.data_quality_checks",+ {"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"},+ ),+ (+ "information_schema_data_quality_health",+ "select health from system.information_schema.data_quality_health",+ {"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/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.pyindex 949bdb7e691e..5aa883d3ad23 100644--- a/products/data_quality/backend/facade/api.py+++ b/products/data_quality/backend/facade/api.py@@ -7,28 +7,56 @@ the AST-bearing ``CheckPlan`` stay inside ``logic``, since they are compiler intdata. ORM model classes never cross here either -- ``facade/models.py`` is their one channel."""+from ..logic.checks import (+ checks_for_subject,+ ensure_name_available,+ soft_delete_check,+ start_check_suite,+ subject_health,+ update_check,+ upsert_check,+ validate_check,+)from ..logic.compiler import compile_check, related_subject_ref+from ..logic.config import get_gate_config, set_gate_materialization_on_checksfrom ..logic.contracts import CompiledCheck, SubjectReffrom ..logic.errors import CheckConfigError, SubjectUnresolvableError+from ..logic.health import CheckStatusRow, roll_up_healthfrom ..logic.registry import UnknownCheckTypeError, list_check_typesfrom ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entry+from ..logic.subject_access import denied_subject_names, is_subject_denied, referenced_subject_namesfrom ..logic.subjects import resolve_subjectfrom ..logic.triggers import materialization_audit_mode as quality_audit_modefrom .contracts import CheckTypeInfo__all__ = ["CheckConfigError",+ "CheckStatusRow","CheckTypeInfo","CompiledCheck","SubjectRef","SubjectUnresolvableError","UnknownCheckTypeError",+ "checks_for_subject","compile_check","compute_fingerprint",+ "denied_subject_names",+ "ensure_name_available","from_config_entry",+ "get_gate_config",+ "is_subject_denied","list_check_types","quality_audit_mode",+ "referenced_subject_names","related_subject_ref","resolve_subject",+ "roll_up_health",+ "set_gate_materialization_on_checks",+ "soft_delete_check",+ "start_check_suite",+ "subject_health","to_config_entry",+ "update_check",+ "upsert_check",+ "validate_check",]diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.pynew file mode 100644index 000000000000..e1b43211a6b6--- /dev/null+++ b/products/data_quality/backend/logic/checks.py@@ -0,0 +1,254 @@+"""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.+"""++import asyncio+from dataclasses import asdict+from datetime import UTC, datetime+from typing import Any+from uuid import UUID, uuid4++from django.conf import settings+from django.db import IntegrityError, transaction+from django.db.models import QuerySet++from temporalio.common import RetryPolicy++from posthog.models.team import Team+from posthog.models.user import User+from posthog.temporal.common.client import sync_connect++from ..facade.contracts import CHECK_SUITE_WORKFLOW_NAME+from ..facade.enums import SubjectHealth, SubjectStatus, SubjectType, SuiteRunStatus, SuiteRunTrigger+from ..models import DataQualityCheck, DataQualitySuiteRun+from .compiler import related_subject_ref+from .errors import SubjectUnresolvableError+from .exceptions import CheckNameConflict+from .health import CheckStatusRow, roll_up_health+from .registry import get_spec+from .serialization import compute_fingerprint+from .spec import CheckConfig+from .subjects import resolve_subject++_UPSERTABLE_FIELDS = (+ "name",+ "description",+ "severity",+ "enabled",+ "tags",+ "created_source",+ "ai_model",+ "confidence",+ "reasoning",+ "owner",+)+++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}+++def validate_check(+ team: Team,+ subject_type: str,+ subject_uuid: str,+ check_type: str,+ column_name: str,+ config: dict[str, Any],+) -> CheckConfig:+ """Reject a check the compiler could never run, at authoring time rather than at run time.++ Returns the parsed config so callers do not validate twice, and so the fingerprint hashes the+ normalized form rather than whatever representation the request happened to use.+ """+ parsed = get_spec(check_type).validate(config, column_name)++ if not resolve_subject(team.id, subject_type, subject_uuid).exists:+ raise SubjectUnresolvableError(f"No {subject_type} with id {subject_uuid} in this project.")++ related = related_subject_ref(check_type, config)+ if related and not resolve_subject(team.id, *related).exists:+ raise SubjectUnresolvableError(f"The referenced {related[0]} {related[1]} does not exist.")++ return parsed+++def upsert_check(+ *,+ team: Team,+ user: User | None,+ subject_type: str,+ subject_uuid: str,+ check_type: str,+ column_name: str,+ config: dict[str, Any],+ **optional: Any,+) -> tuple[DataQualityCheck, bool]:+ """Create the check, or refine the one already carrying this fingerprint. Returns (check, created)."""+ parsed = validate_check(team, subject_type, subject_uuid, check_type, column_name, config)+ subject = resolve_subject(team.id, subject_type, subject_uuid)++ fingerprint = compute_fingerprint(+ subject_type=subject_type,+ subject_uuid=str(subject_uuid),+ check_type=check_type,+ column_name=column_name,+ config=parsed.model_dump(mode="json"),+ )+ existing = _find_by_fingerprint(team.id, subject_type, subject_uuid, fingerprint)+ fields = {key: value for key, value in optional.items() if key in _UPSERTABLE_FIELDS and value is not None}++ # Checked here rather than before the fingerprint lookup: re-proposing an identical named check+ # must upsert, and a name conflict with *itself* is not a conflict.+ ensure_name_available(team.id, fields.get("name") or "", exclude_id=existing.id if existing else None)++ if existing is None:+ try:+ # Savepoint so a lost race rolls back cleanly instead of poisoning an outer transaction.+ with transaction.atomic():+ check = DataQualityCheck.objects.for_team(team.id).create(+ team=team,+ created_by=user,+ subject_type=subject_type,+ subject_name=subject.name,+ subject_status=SubjectStatus.ACTIVE,+ check_type=check_type,+ column_name=column_name,+ config=config,+ fingerprint=fingerprint,+ **_subject_fk(subject_type, subject_uuid),+ **fields,+ )+ return check, True+ except IntegrityError:+ # Check-then-insert race: a concurrent identical request inserted this fingerprint between+ # the lookup above and this create. Refetch and refine the row it won with, so the loser+ # gets the promised existing check (HTTP 200) rather than a 500. A collision on any other+ # constraint (e.g. the name) is a genuine conflict, not this race -- re-raise it.+ existing = _find_by_fingerprint(team.id, subject_type, subject_uuid, fingerprint)+ if existing is None:+ raise++ return update_check(existing, **fields, deleted=False), False+++def _find_by_fingerprint(+ team_id: int, subject_type: str, subject_uuid: str, fingerprint: str+) -> DataQualityCheck | None:+ return (+ DataQualityCheck.objects.for_team(team_id)+ .filter(fingerprint=fingerprint, **_subject_fk(subject_type, subject_uuid))+ .first()+ )+++def update_check(check: DataQualityCheck, **fields: Any) -> DataQualityCheck:+ """Apply presentation changes. The assertion itself is immutable -- re-create instead."""+ changed = []+ for key, value in fields.items():+ if key in _UPSERTABLE_FIELDS or key == "deleted":+ setattr(check, key, value)+ changed.append(key)++ if changed:+ check.save(update_fields=[*changed, "updated_at"])+ return check+++def soft_delete_check(check: DataQualityCheck) -> None:+ """Hide the definition but keep its run history queryable."""+ check.deleted = True+ check.deleted_at = datetime.now(UTC)+ check.enabled = False+ check.save(update_fields=["deleted", "deleted_at", "enabled", "updated_at"])+++def checks_for_subject(team_id: int, subject_type: str, subject_uuid: str | UUID) -> QuerySet[DataQualityCheck]:+ return DataQualityCheck.objects.for_team(team_id).filter(deleted=False, **_subject_fk(subject_type, subject_uuid))+++def subject_health(team_id: int, subject_type: str, subject_uuid: str | UUID) -> SubjectHealth:+ # Only enabled checks count toward health, matching the REST counts and the+ # information_schema.data_quality_health table -- the three must never disagree.+ rows = (+ checks_for_subject(team_id, subject_type, subject_uuid)+ .filter(enabled=True)+ .values_list("severity", "last_status")+ )+ return roll_up_health(CheckStatusRow(severity=severity, last_status=status) for severity, status in rows)+++def start_check_suite(+ *,+ team: Team,+ trigger: SuiteRunTrigger = SuiteRunTrigger.MANUAL,+ user: User | None = None,+ subject_type: str = "",+ subject_uuids: list[str] | None = None,+ check_ids: list[str] | None = None,+) -> DataQualitySuiteRun:+ """Kick off a suite run and hand back the row to poll.++ The row is created here rather than inside the workflow so the caller gets a pollable handle+ synchronously; the prepare activity fills in the batches.+ """+ # Deferred: importing anything under ``temporal`` executes its package __init__, which pulls+ # the workflow and activity modules (and temporalio's sandbox) onto the request import path.+ from ..temporal.contracts import RunCheckSuiteInputs # noqa: PLC0415++ subject_uuids = subject_uuids or []+ suite_run = DataQualitySuiteRun.objects.for_team(team.id).create(+ team=team,+ trigger=trigger,+ created_by=user,+ subject_type=subject_type if len(subject_uuids) == 1 else "",+ subject_uuid=subject_uuids[0] if len(subject_uuids) == 1 else None,+ workflow_id=f"data-quality-run-suite-{team.id}-{uuid4()}",+ started_at=datetime.now(UTC),+ )+ inputs = RunCheckSuiteInputs(+ team_id=team.id,+ trigger=trigger,+ saved_query_ids=subject_uuids if subject_type == SubjectType.VIEW else [],+ table_ids=subject_uuids if subject_type == SubjectType.TABLE else [],+ check_ids=check_ids or [],+ suite_run_id=str(suite_run.id),+ created_by_id=user.id if user else None,+ )+ try:+ temporal = sync_connect()+ asyncio.run(+ temporal.start_workflow(+ CHECK_SUITE_WORKFLOW_NAME,+ asdict(inputs),+ id=suite_run.workflow_id,+ task_queue=str(settings.DATA_MODELING_TASK_QUEUE),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ )+ except Exception as err:+ # The row is already committed, so leaving it would report `running` forever with no+ # workflow behind it. Close it out before surfacing the error to the caller.+ suite_run.status = SuiteRunStatus.FAILED+ suite_run.error = str(err)+ suite_run.finished_at = datetime.now(UTC)+ suite_run.save(update_fields=["status", "error", "finished_at", "updated_at"])+ raise++ return suite_run+++def ensure_name_available(team_id: int, name: str, exclude_id: UUID | str | None = None) -> None:+ if not name:+ return+ clashes = DataQualityCheck.objects.for_team(team_id).filter(name=name)+ if exclude_id is not None:+ clashes = clashes.exclude(id=exclude_id)+ if clashes.exists():+ raise CheckNameConflict(f"A check named '{name}' already exists in this project.")diff --git a/products/data_quality/backend/logic/config.py b/products/data_quality/backend/logic/config.pynew file mode 100644index 000000000000..c30abea68347--- /dev/null+++ b/products/data_quality/backend/logic/config.py@@ -0,0 +1,21 @@+"""Read and write the team-level data quality configuration."""++from typing import TYPE_CHECKING++from posthog.models.team.extensions import get_or_create_team_extension++from ..models import TeamDataQualityConfig++if TYPE_CHECKING:+ from posthog.models.team import Team+++def get_gate_config(team: "Team") -> TeamDataQualityConfig:+ return get_or_create_team_extension(team, TeamDataQualityConfig)+++def set_gate_materialization_on_checks(team: "Team", enabled: bool) -> TeamDataQualityConfig:+ config = get_or_create_team_extension(team, TeamDataQualityConfig)+ config.gate_materialization_on_checks = enabled+ config.save(update_fields=["gate_materialization_on_checks"])+ return configdiff --git a/products/data_quality/backend/logic/exceptions.py b/products/data_quality/backend/logic/exceptions.pynew file mode 100644index 000000000000..3423f58cbd24--- /dev/null+++ b/products/data_quality/backend/logic/exceptions.py@@ -0,0 +1,20 @@+"""Domain exceptions for data quality checks.++Subclassing DRF's APIException lets the viewset stay thin: raising these from the logic layer maps+to the right HTTP status automatically, no per-action try/except needed.+"""++from rest_framework import status+from rest_framework.exceptions import APIException+++class CheckNameConflict(APIException):+ """A 409 for a check name already taken within the project.++ ``detail`` must stay a plain string: the exceptions_hog handler cannot render dict details+ (it 500s).+ """++ status_code = status.HTTP_409_CONFLICT+ default_detail = "A check with this name already exists in this project."+ default_code = "check_name_conflict"diff --git a/products/data_quality/backend/logic/health.py b/products/data_quality/backend/logic/health.pynew file mode 100644index 000000000000..fba23312afb3--- /dev/null+++ b/products/data_quality/backend/logic/health.py@@ -0,0 +1,39 @@+"""Roll a subject's checks up into one health verdict.++Pure, and deliberately the only implementation: the REST endpoint and the+``information_schema.data_quality_health`` table must never disagree about what "failing" means.+"""++from collections.abc import Iterable+from dataclasses import dataclass++from ..facade.enums import CheckRunStatus, CheckSeverity, SubjectHealth+++@dataclass(frozen=True)+class CheckStatusRow:+ """The denormalized last-run state of one check, which is all a rollup needs."""++ severity: str+ last_status: str+++def roll_up_health(rows: Iterable[CheckStatusRow]) -> SubjectHealth:+ """Worst-first: an error-severity failure outranks an execution error, which outranks a warning."""+ statuses = list(rows)+ if not statuses:+ return SubjectHealth.UNKNOWN++ if any(_is_error_failure(row) for row in statuses):+ return SubjectHealth.FAILING+ if any(row.last_status == CheckRunStatus.ERRORED for row in statuses):+ return SubjectHealth.ERRORING+ if any(row.last_status == CheckRunStatus.FAILED for row in statuses):+ return SubjectHealth.WARN+ if any(row.last_status == CheckRunStatus.PASSED for row in statuses):+ return SubjectHealth.HEALTHY+ return SubjectHealth.UNKNOWN+++def _is_error_failure(row: CheckStatusRow) -> bool:+ return row.last_status == CheckRunStatus.FAILED and row.severity == CheckSeverity.ERRORdiff --git a/products/data_quality/backend/logic/spec.py b/products/data_quality/backend/logic/spec.pyindex ac4a29cec6d3..f21eddbe44cd 100644--- a/products/data_quality/backend/logic/spec.py+++ b/products/data_quality/backend/logic/spec.py@@ -66,6 +66,15 @@ 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]:+ """Warehouse names this check reads directly, besides its subject and related subject.++ Only ``custom_sql`` needs this -- its query names arbitrary tables. Every structured type+ reaches exactly its subject plus, via ``related_subject_ref``, one other, so the default is+ empty. Used to authorize every subject a check reads, since the worker executes with team+ scope only."""+ return []+@abstractmethoddef build(self,diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pynew file mode 100644index 000000000000..573b6706f665--- /dev/null+++ b/products/data_quality/backend/logic/subject_access.py@@ -0,0 +1,53 @@+"""Which check subjects the caller may not read.++The REST endpoint and the ``information_schema.data_quality_*`` tables must never disagree on+visibility, so both resolve denial from the same source: the warehouse-table denial the HogQL+database computes for the caller. A member denied a table or view must not read its checks, run+history, or health rollup -- those carry the compiled ``config``, failed-row counts, and observed+values, which together act as a count oracle over rows the member cannot read directly.+"""++from typing import TYPE_CHECKING, Any, Optional++from posthog.hogql.database.database import Database+from posthog.hogql.database.schema.information_schema import _references_denied_table++from .registry import get_spec+from .subjects import resolve_subject++if TYPE_CHECKING:+ from posthog.models import Team, User+ from posthog.rbac.user_access_control import UserAccessControl+++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)+++def referenced_subject_names(team_id: int, check_type: str, config: dict[str, Any]) -> list[str]:+ """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+ tables; the worker later runs both with team scope only. Authorizing these at the API is the one+ place a denied subject can be kept out of reach, so a check on an allowed subject can't be used as+ a count oracle over one the author cannot read. Assumes config already validated."""+ spec = get_spec(check_type)+ parsed = spec.parse_config(config)+ names = list(spec.referenced_table_names(parsed))+ if related := spec.related_subject_ref(parsed):+ ref = resolve_subject(team_id, related[0], related[1])+ if ref.exists:+ names.append(ref.name)+ return namesdiff --git a/products/data_quality/backend/logic/types/custom_sql.py b/products/data_quality/backend/logic/types/custom_sql.pyindex f1102bf1cb91..1cb16d70793e 100644--- a/products/data_quality/backend/logic/types/custom_sql.py+++ b/products/data_quality/backend/logic/types/custom_sql.py@@ -2,6 +2,7 @@ from pydantic import Field, field_validatorfrom 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@@ -59,6 +60,10 @@ class CustomSqlSpec(CheckTypeSpec):requires_column = Falsedescription = "Fails on every row the custom HogQL SELECT returns."+ def referenced_table_names(self, config: CheckConfig) -> list[str]:+ assert isinstance(config, CustomSqlConfig)+ return get_table_names(parse_failing_rows_query(config.query))+def build(self, subject: SubjectRef, column_name: str, config: CheckConfig, related: SubjectRef | None = None) -> CheckPlan:diff --git a/products/data_quality/backend/presentation/__init__.py b/products/data_quality/backend/presentation/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/data_quality/backend/presentation/serializers.py b/products/data_quality/backend/presentation/serializers.pynew file mode 100644index 000000000000..3ff9898e48ab--- /dev/null+++ b/products/data_quality/backend/presentation/serializers.py@@ -0,0 +1,299 @@+"""DRF serializers for data quality checks.++Source of truth for the generated frontend and MCP types, so every field carries help_text. The+per-type ``config`` shape is validated against the registry's JSON schema rather than modeled as a+union: a new check type must not need a serializer change.+"""++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import extend_schema_field, extend_schema_serializer+from rest_framework import serializers++from posthog.api.shared import UserBasicSerializer++from ..facade import api+from ..facade.enums import CheckSeverity, CheckType, CreatedSource, SubjectType+from ..facade.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+++@extend_schema_field(OpenApiTypes.OBJECT)+class CheckConfigField(serializers.JSONField):+ """Type-specific configuration. Call /check_types/ for the JSON schema of each type."""+++@extend_schema_serializer(component_name="DataQualityCheck")+class DataQualityCheckSerializer(serializers.ModelSerializer):+ """The subject is implied by the URL (the parent saved query or table), never part of the body."""++ 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).",+ )+ subject_uuid = serializers.SerializerMethodField(+ help_text="Id of the table or view being checked -- the parent resource in the URL."+ )+ check_type = serializers.ChoiceField(+ choices=[(t.value, t.value) for t in CheckType],+ help_text="Which assertion to make. Determines the shape of config; see /check_types/.",+ )+ severity = serializers.ChoiceField(+ choices=[(s.value, s.value) for s in CheckSeverity],+ required=False,+ help_text="'error' failures mark the subject failing and notify; 'warn' failures only surface.",+ )+ created_source = serializers.ChoiceField(+ choices=[(s.value, s.value) for s in CreatedSource],+ required=False,+ help_text="Whether a human ('user') or an agent ('ai_generated') authored this check.",+ )+ config = CheckConfigField(+ required=False,+ help_text="Type-specific configuration, validated against the check type's JSON schema.",+ )+ tags = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Free-form string labels for grouping and filtering.",+ )+ last_status = serializers.CharField(+ read_only=True,+ help_text="Outcome of the newest run: passed, failed, errored, skipped, or empty if never run.",+ )+ subject_status = serializers.CharField(+ read_only=True,+ help_text="'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted.",+ )+ owner = serializers.SerializerMethodField(help_text="Email of the human accountable for this check, or null.")+ created_by = UserBasicSerializer(read_only=True, help_text="User who first created this check.")++ class Meta:+ model = DataQualityCheck+ fields = [+ "id",+ "name",+ "description",+ "subject_type",+ "subject_uuid",+ "subject_name",+ "subject_status",+ "column_name",+ "check_type",+ "config",+ "severity",+ "enabled",+ "tags",+ "owner",+ "last_run_at",+ "last_status",+ "fingerprint",+ "created_source",+ "ai_model",+ "confidence",+ "reasoning",+ "created_by",+ "created_at",+ "updated_at",+ ]+ read_only_fields = [+ "id",+ "subject_name",+ "subject_status",+ "last_run_at",+ "last_status",+ "fingerprint",+ "created_by",+ "created_at",+ "updated_at",+ ]+ extra_kwargs = {+ "name": {+ "required": False,+ "help_text": "Optional identifier-safe handle, unique per project. Omit to address the check by id.",+ },+ "description": {"required": False, "help_text": "Why this check exists and what a failure means."},+ "subject_name": {"help_text": "Queryable name of the subject, refreshed on every run."},+ "column_name": {+ "required": False,+ "help_text": "Column the check applies to. Omit for table-scoped types like row_count.",+ },+ "enabled": {"required": False, "help_text": "Disabled checks are never run by any trigger."},+ "fingerprint": {+ "help_text": "sha256 of the subject, type, column, and config. Re-creating the same check upserts."+ },+ "ai_model": {"required": False, "help_text": "Model that generated the check, if AI-authored."},+ "confidence": {+ "required": False,+ "help_text": "AI author's confidence in the check, 0-1.",+ "min_value": 0.0,+ "max_value": 1.0,+ },+ "reasoning": {"required": False, "help_text": "AI author's reasoning, surfaced as review context."},+ }++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_owner(self, obj: DataQualityCheck) -> str | None:+ return obj.owner.email if obj.owner else None++ @extend_schema_field(serializers.UUIDField(allow_null=True))+ def get_subject_uuid(self, obj: DataQualityCheck) -> str | None:+ return str(obj.subject_uuid) if obj.subject_uuid else None++ # The assertion is the check's identity: it is what the fingerprint hashes and what the runner+ # compiles. Editing it in place would leave a fingerprint describing a different check, so+ # subsequent identical creates would duplicate instead of upserting. Re-create instead. The+ # subject needs no entry: it comes from the URL, and moving a check means re-creating it there.+ IMMUTABLE_AFTER_CREATE = ("check_type", "column_name", "config")++ def validate(self, attrs: dict) -> dict:+ if self.instance is not None:+ changed = [+ field+ for field in self.IMMUTABLE_AFTER_CREATE+ if field in attrs and attrs[field] != getattr(self.instance, field)+ ]+ if changed:+ raise serializers.ValidationError(+ dict.fromkeys(+ changed, "A check's assertion cannot be edited. Create a new check and delete this one."+ )+ )++ def resolved(field: str) -> str:+ return attrs.get(field) or getattr(self.instance, field, None) or ""++ # 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 {}),+ )+ except (api.CheckConfigError, api.SubjectUnresolvableError, api.UnknownCheckTypeError) as err:+ raise serializers.ValidationError({"config": str(err)})+ return attrs++ def update(self, instance: DataQualityCheck, validated_data: dict) -> DataQualityCheck:+ # Routed through update_check so writes stay restricted to the mutable field allowlist.+ name = validated_data.get("name")+ if name and name != instance.name:+ api.ensure_name_available(instance.team_id, name, exclude_id=instance.id)+ return api.update_check(instance, **validated_data)+++@extend_schema_serializer(component_name="DataQualityCheckRun")+class DataQualityCheckRunSerializer(serializers.ModelSerializer):+ status = serializers.CharField(read_only=True, help_text="passed, failed, errored, or skipped.")+ # Declared rather than derived: the model field carries no choices, so the schema would otherwise+ # publish check_type as a bare string.+ check_type = serializers.ChoiceField(+ choices=[(t.value, t.value) for t in CheckType],+ read_only=True,+ help_text="Which assertion this run made.",+ )++ class Meta:+ model = DataQualityCheckRun+ fields = [+ "id",+ "quality_check",+ "suite_run",+ "subject_type",+ "subject_uuid",+ "subject_name",+ "check_type",+ "column_name",+ "status",+ "failed_row_count",+ "observed_value",+ "compiled_query",+ "error",+ "duration_ms",+ "started_at",+ "finished_at",+ "created_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "failed_row_count": {"help_text": "Rows violating the assertion. Null for bounds checks like row_count."},+ "observed_value": {"help_text": "The check's headline number, recorded on passes too."},+ "compiled_query": {"help_text": "The HogQL that ran. Re-run it to see the offending rows."},+ "error": {"help_text": "Compilation or execution failure, when status is 'errored'."},+ }+++@extend_schema_serializer(component_name="DataQualitySuiteRun")+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.")+ subject_type = serializers.SerializerMethodField(+ help_text="'table' or 'view' when the run targets exactly one subject; null for a "+ "check-scoped or multi-subject run."+ )++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_subject_type(self, obj: DataQualitySuiteRun) -> str | None:+ # The model stores "" for a run that is not scoped to a single subject; the response schema+ # only permits table/view, so surface the unscoped case as null rather than a blank string.+ return obj.subject_type or None++ class Meta:+ model = DataQualitySuiteRun+ fields = [+ "id",+ "trigger",+ "status",+ "subject_type",+ "subject_uuid",+ "workflow_id",+ "checks_passed",+ "checks_failed",+ "checks_errored",+ "checks_skipped",+ "started_at",+ "finished_at",+ "error",+ "created_at",+ ]+ read_only_fields = fields+++@extend_schema_serializer(component_name="DataQualitySubjectHealth")+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.")+ 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)."+ )+ checks_total = serializers.IntegerField(help_text="How many enabled, non-deleted checks cover this subject.")+ checks_failing = serializers.IntegerField(help_text="How many of those checks last reported a failure.")+++@extend_schema_serializer(component_name="DataQualityGateConfig")+class DataQualityGateConfigSerializer(serializers.Serializer):+ """The team-level materialization gate. Checks always run and warn; this only toggles blocking."""++ gate_materialization_on_checks = serializers.BooleanField(+ help_text="When true, a materialization whose error-severity checks fail is not published; "+ "the previous version keeps serving and downstream models are skipped."+ )+++@extend_schema_serializer(component_name="DataQualityCheckType")+class CheckTypeSerializer(serializers.Serializer):+ """One entry of the check-type catalog, so an agent can author config without guessing."""++ check_type = serializers.CharField(help_text="Value to pass as check_type.")+ description = serializers.CharField(help_text="What the check asserts and what counts as a failure.")+ requires_column = serializers.BooleanField(help_text="Whether column_name must be set for this type.")+ config_schema = CheckConfigField(help_text="JSON schema the config object is validated against.")diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.pynew file mode 100644index 000000000000..df98494dba3c--- /dev/null+++ b/products/data_quality/backend/presentation/views.py@@ -0,0 +1,382 @@+"""DRF views for data quality checks, nested under the subjects they audit.++Checks hang off the existing warehouse surfaces -- ``warehouse_saved_queries/{id}/checks`` and+``warehouse_tables/{id}/checks`` -- the same way run/materialize/resume do, gated by warehouse+scopes rather than a scope of their own. Thin: validate via the serializer, call the facade,+serialize the result. Nothing here runs a check -- every trigger hands off to Temporal and returns+a suite-run handle to poll.+"""++from collections.abc import Callable+from typing import ClassVar, cast++from django.db.models import QuerySet++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view+from rest_framework import mixins, status, viewsets+from rest_framework.exceptions import PermissionDenied+from rest_framework.permissions import SAFE_METHODS+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.views import APIView++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.utils import action+from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin++from ..facade import api+from ..facade.enums import CheckRunStatus, SubjectType+from ..facade.flags import is_data_quality_checks_enabled+from ..facade.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from .serializers import (+ CheckTypeSerializer,+ DataQualityCheckRunSerializer,+ DataQualityCheckSerializer,+ DataQualityGateConfigSerializer,+ DataQualitySuiteRunSerializer,+ SubjectHealthSerializer,+)++_RECENT_RUNS_LIMIT = 50+++class _SubjectScopedViewSet(TeamAndOrgViewSetMixin):+ """Shared plumbing for viewsets nested under a warehouse saved query or table.++ Every entry point is gated on the product flag and on access to the parent subject -- the same+ name-based denial the information_schema loaders read, so REST and SQL can never disagree about+ which subjects a member may see. Most actions additionally require query access: run results are+ a count oracle over the underlying rows, so a member denied `query` must not reach them through+ a check. Only the check-type *catalog* stays ungated by query: static schema metadata.+ """++ team: Team+ subject_type: ClassVar[SubjectType]+ subject_field: ClassVar[str]+ QUERY_GATED_ACTIONS: ClassVar[frozenset[str]] = frozenset()++ @property+ def subject_uuid(self) -> str:+ return str(self.parents_query_dict[f"{self.subject_field}_id"])++ def initial(self, request: Request, *args, **kwargs) -> None:+ super().initial(request, *args, **kwargs)+ self._require_flag()+ if getattr(self, "action", None) in self.QUERY_GATED_ACTIONS:+ self._require_query_access()+ self._require_parent_subject_access()++ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:+ # Token callers carry scopes but no RBAC, so the query gate has to be a scope for them.+ if getattr(view, "action", None) in self.QUERY_GATED_ACTIONS:+ return [f"{self.scope_object}:{'read' if request.method in SAFE_METHODS else 'write'}", "query:read"]+ # Everything else defers along the MRO, so the access-control actions this viewset inherits+ # keep demanding access_control:read rather than riding the warehouse scope alone.+ parent = getattr(super(), "dangerously_get_required_scopes", None)+ return parent(request, view) if parent is not None else None++ def _require_flag(self) -> None:+ if not is_data_quality_checks_enabled(self.team):+ raise PermissionDenied("Data quality checks are not enabled for this project.")++ def _require_query_access(self) -> None:+ # required_scopes gates tokens; session users carry no scopes and AccessControlPermission+ # only checks the warehouse resource, so enforce query RBAC explicitly too.+ if not self.user_access_control.check_access_level_for_resource("query", "viewer"):+ raise PermissionDenied("You need query access to work with data quality checks.")++ def _require_parent_subject_access(self) -> None:+ """403 a denied parent -- for every action, including list.++ A member denied a view must not be able to enumerate its check configs or counts through+ this surface. Orphan-tolerant rather than 404ing: a parent that no longer resolves still+ serves its checks (they are skipped, not hidden), because resolution carries no RBAC to+ enforce and orphaned history must stay reachable -- but only for a caller who cannot be+ object-denied, since an orphan has no name left to check a denial against.+ """+ ref = api.resolve_subject(self.team.id, self.subject_type, self.subject_uuid)+ if not ref.exists:+ # Deleting the subject takes its denial with it: the orphan resolves to an empty name,+ # and the denial set is rebuilt from the subjects that still exist, so neither can show+ # the caller was allowed this one. Without that proof, only a caller who cannot be+ # object-denied keeps orphan access.+ if self._can_be_object_denied():+ raise PermissionDenied("You don't have access to this table or view.")+ return+ if api.is_subject_denied(ref.name, self._denied_subject_names()):+ raise PermissionDenied("You don't have access to this table or view.")++ def _can_be_object_denied(self) -> bool:+ """Whether object-level warehouse denials can apply to this caller at all.++ False for an org admin, or an organization without access controls: neither can be denied a+ single table or view, so an empty denial set is proof of access rather than missing data.+ """+ uac = self.user_access_control+ return uac is not None and not uac.is_organization_admin and uac.access_controls_supported++ def _denied_subject_names(self) -> set[str]:+ # Same denial the information_schema loaders read. Computed once per request.+ cached = getattr(self, "_denied_subjects_cache", None)+ if cached is None:+ # A warehouse subject can only be denied to a non-admin in an org with access controls, so+ # skip the (heavy) database build otherwise -- the denied set would be empty either way,+ # which keeps this in lock-step with the loaders rather than diverging from them.+ if not self._can_be_object_denied():+ cached = set()+ else:+ try:+ cached = api.denied_subject_names(+ self.team,+ cast(User, self.request.user),+ user_access_control=self.user_access_control,+ )+ except Exception as err:+ # Building the denial set walks every saved query; one malformed definition must+ # not 500 the surface. Failing open would leak denied subjects, so fail closed.+ capture_exception(err)+ raise PermissionDenied("Could not verify your access to this table or view.")+ self._denied_subjects_cache = cached+ return cached++ def _require_referenced_subject_access(self, check_type: str, config: dict) -> None:+ # The parent is not the only subject a check reads: a relationships check names a second+ # subject and a custom_sql query selects arbitrary tables, both run by the worker with team+ # scope only. Authorize them too, or a check on an allowed subject is a count oracle over a+ # denied one.+ denied = self._denied_subject_names()+ if not denied:+ return+ for name in api.referenced_subject_names(self.team.id, check_type, config):+ if api.is_subject_denied(name, denied):+ raise PermissionDenied("You don't have access to a table or view this check reads.")+++class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewsets.ModelViewSet):+ """CRUD for one subject's checks, plus the actions that run them and report on them."""++ QUERY_GATED_ACTIONS = frozenset(+ {"list", "retrieve", "create", "update", "partial_update", "destroy", "run", "run_all", "runs", "health"}+ )+ serializer_class = DataQualityCheckSerializer+ queryset = DataQualityCheck.objects.unscoped()++ def 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)+ if check_type := self.request.query_params.get("check_type"):+ queryset = queryset.filter(check_type=check_type)+ return queryset.order_by("-created_at")++ def get_serializer_context(self) -> dict:+ return {+ **super().get_serializer_context(),+ "subject_type": self.subject_type,+ "subject_uuid": self.subject_uuid,+ }++ @extend_schema(+ description="Create a check on this table or view, or refine the one already carrying the same "+ "fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.",+ )+ def create(self, request: Request, *args, **kwargs) -> Response:+ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ self._require_referenced_subject_access(data["check_type"], data.get("config") or {})++ optional = {+ key: data[key]+ for key in (+ "name",+ "description",+ "severity",+ "enabled",+ "tags",+ "created_source",+ "ai_model",+ "confidence",+ "reasoning",+ )+ if key in data+ }+ check, created = api.upsert_check(+ team=self.team,+ user=cast(User, request.user),+ subject_type=self.subject_type,+ subject_uuid=self.subject_uuid,+ check_type=data["check_type"],+ column_name=data.get("column_name", ""),+ config=data.get("config") or {},+ **optional,+ )+ return Response(+ self.get_serializer(check).data,+ status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,+ )++ def perform_destroy(self, instance: DataQualityCheck) -> None:+ api.soft_delete_check(instance)++ @extend_schema(+ description="Run this check now. Returns the suite run to poll for the report.",+ request=None,+ responses={200: DataQualitySuiteRunSerializer},+ )+ @action(methods=["POST"], detail=True)+ def run(self, request: Request, **kwargs) -> Response:+ # The parent gate cleared the declared subject; a check can still read a denied one+ # (relationships target, custom_sql table), so gate on every subject it references too.+ check = self.get_object()+ self._require_referenced_subject_access(check.check_type, check.config)+ suite_run = api.start_check_suite(team=self.team, user=cast(User, request.user), check_ids=[str(check.id)])+ return Response(DataQualitySuiteRunSerializer(suite_run).data)++ @extend_schema(+ description="Run every enabled check on this table or view. Returns the suite run to poll.",+ request=None,+ responses={200: DataQualitySuiteRunSerializer},+ )+ @action(methods=["POST"], detail=False, url_path="run_all")+ def run_all(self, request: Request, **kwargs) -> Response:+ # Each of the subject's checks may read a further subject the member is denied, so gate on+ # those too before running the batch. Only a restricted member has anything to check.+ if self._denied_subject_names():+ 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)+ suite_run = api.start_check_suite(+ team=self.team,+ user=cast(User, request.user),+ subject_type=self.subject_type,+ subject_uuids=[self.subject_uuid],+ )+ return Response(DataQualitySuiteRunSerializer(suite_run).data)++ @extend_schema(+ description="Recent run history for this check, newest first.",+ responses={200: DataQualityCheckRunSerializer(many=True)},+ )+ @action(methods=["GET"], detail=True, pagination_class=None)+ def runs(self, request: Request, **kwargs) -> Response:+ check = self.get_object()+ self._require_referenced_subject_access(check.check_type, check.config)+ runs = DataQualityCheckRun.objects.for_team(self.team_id).filter(quality_check=check).order_by("-created_at")+ return Response(DataQualityCheckRunSerializer(runs[:_RECENT_RUNS_LIMIT], many=True).data)++ @extend_schema(+ description="Health rollup for this table or view, from the denormalized status of its checks.",+ responses={200: SubjectHealthSerializer},+ )+ @action(methods=["GET"], detail=False, pagination_class=None)+ def health(self, request: Request, **kwargs) -> Response:+ checks = api.checks_for_subject(self.team_id, self.subject_type, self.subject_uuid).filter(enabled=True)+ failing = checks.filter(last_status=CheckRunStatus.FAILED)+ return Response(+ SubjectHealthSerializer(+ {+ "subject_type": self.subject_type,+ "subject_uuid": self.subject_uuid,+ "health": api.subject_health(self.team_id, self.subject_type, self.subject_uuid),+ "checks_total": checks.count(),+ "checks_failing": failing.count(),+ }+ ).data+ )++ @extend_schema(+ description="The check types this project can author, with the JSON schema of each type's config.",+ responses={200: CheckTypeSerializer(many=True)},+ )+ @action(methods=["GET"], detail=False, url_path="check_types", pagination_class=None)+ def check_types(self, request: Request, **kwargs) -> Response:+ return Response(CheckTypeSerializer(api.list_check_types(), many=True).data)+++class SavedQueryCheckViewSet(_BaseCheckViewSet):+ scope_object = "warehouse_view"+ subject_type = SubjectType.VIEW+ subject_field = "saved_query"+++class TableCheckViewSet(_BaseCheckViewSet):+ scope_object = "warehouse_table"+ subject_type = SubjectType.TABLE+ subject_field = "table"+++class _BaseSuiteRunViewSet(+ _SubjectScopedViewSet,+ AccessControlViewSetMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ viewsets.GenericViewSet,+):+ """Read-only reports for this subject's check-suite executions."""++ QUERY_GATED_ACTIONS = frozenset({"list", "retrieve", "check_runs"})+ serializer_class = DataQualitySuiteRunSerializer+ queryset = DataQualitySuiteRun.objects.unscoped()++ def safely_get_queryset(self, queryset: QuerySet[DataQualitySuiteRun]) -> QuerySet[DataQualitySuiteRun]:+ # The parent lookup is rewritten onto subject_uuid, so this lists the parent's own+ # single-subject suites. Multi-subject sweep suites stay reachable through+ # information_schema, which is the cross-subject surface.+ return queryset.filter(team_id=self.team_id).order_by("-created_at")++ @extend_schema(+ description="Every check execution in this suite run.",+ responses={200: DataQualityCheckRunSerializer(many=True)},+ )+ @action(methods=["GET"], detail=True, url_path="check_runs", pagination_class=None)+ def check_runs(self, request: Request, **kwargs) -> Response:+ suite_run = self.get_object()+ runs = DataQualityCheckRun.objects.for_team(self.team_id).filter(suite_run=suite_run).order_by("-created_at")+ return Response(DataQualityCheckRunSerializer(runs, many=True).data)+++def _parent_id_parameter(name: str, description: str) -> Callable[[type], type]:+ # The suite-run model carries the parent as subject_uuid, so drf-spectacular cannot derive the+ # nested path parameter's type from a model field; annotate it on every action instead.+ parameter = OpenApiParameter(name, OpenApiTypes.UUID, OpenApiParameter.PATH, description=description)+ schema = extend_schema(parameters=[parameter])+ return extend_schema_view(list=schema, retrieve=schema, check_runs=schema)+++@_parent_id_parameter("saved_query_id", "Id of the saved query whose suite runs these are.")+class SavedQuerySuiteRunViewSet(_BaseSuiteRunViewSet):+ scope_object = "warehouse_view"+ subject_type = SubjectType.VIEW+ subject_field = "saved_query"+ filter_rewrite_rules = {"saved_query_id": "subject_uuid"}+++@_parent_id_parameter("table_id", "Id of the warehouse table whose suite runs these are.")+class TableSuiteRunViewSet(_BaseSuiteRunViewSet):+ scope_object = "warehouse_table"+ subject_type = SubjectType.TABLE+ subject_field = "table"+ filter_rewrite_rules = {"table_id": "subject_uuid"}+++def data_quality_gate_response(team: Team, request: Request) -> Response:+ """GET/PATCH handler for the team's gate setting, mounted on the warehouse viewset.++ Lives here so the warehouse surface stays a thin mount: the flag gate, the serializer, and the+ config write all belong to this product.+ """+ if not is_data_quality_checks_enabled(team):+ raise PermissionDenied("Data quality checks are not enabled for this project.")+ if request.method == "PATCH":+ serializer = DataQualityGateConfigSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ config = api.set_gate_materialization_on_checks(+ team, serializer.validated_data["gate_materialization_on_checks"]+ )+ else:+ config = api.get_gate_config(team)+ return Response(DataQualityGateConfigSerializer(config).data)diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.pynew file mode 100644index 000000000000..9fbf2b47790f--- /dev/null+++ b/products/data_quality/backend/tests/test_api.py@@ -0,0 +1,572 @@+from uuid import uuid4++from posthog.test.base import APIBaseTest+from unittest.mock import AsyncMock, MagicMock, patch++from django.core.cache import cache+from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status+from rest_framework.test import APIRequestFactory++from posthog.constants import AvailableFeature++from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_quality.backend.facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectType+from products.data_quality.backend.logic import checks as checks_logic+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+from products.data_quality.backend.presentation.serializers import DataQualitySuiteRunSerializer+from products.data_quality.backend.presentation.views import SavedQueryCheckViewSet+from products.warehouse_sources.backend.models.credential import DataWarehouseCredential+from products.warehouse_sources.backend.models.table import DataWarehouseTable++from ee.models.rbac.access_control import AccessControl++START_SUITE = "products.data_quality.backend.logic.checks.sync_connect"+FLAG = "products.data_quality.backend.presentation.views.is_data_quality_checks_enabled"+++class TestCheckViewSetScopes(SimpleTestCase):+ @parameterized.expand(+ [+ ("query_gated_read", "list", "GET", ["warehouse_view:read", "query:read"]),+ ("query_gated_write", "create", "POST", ["warehouse_view:write", "query:read"]),+ ("inherited_access_control", "users_with_access", "GET", ["access_control:read"]),+ ]+ )+ def test_required_scopes_per_action(self, _name: str, action: str, method: str, expected: list[str]) -> None:+ # The query gate is this viewset's own scope rule; everything else has to keep deferring, or the+ # access-control actions it inherits would answer to a warehouse token with no access_control scope.+ view = SavedQueryCheckViewSet()+ view.action = action++ assert view.dangerously_get_required_scopes(APIRequestFactory().generic(method, "/"), view) == expected+++class TestDataQualityCheckAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.view = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS customer_id"}+ )+ self.url = self._checks_url(self.view.id)+ flag = patch(FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ def _checks_url(self, saved_query_id) -> str:+ return f"/api/projects/{self.team.id}/warehouse_saved_queries/{saved_query_id}/checks"++ def _suite_runs_url(self) -> str:+ return f"/api/projects/{self.team.id}/warehouse_saved_queries/{self.view.id}/check_suite_runs"++ def _gate_url(self) -> str:+ return f"/api/projects/{self.team.id}/data_warehouse/data_quality_gate/"++ def _table_checks_url(self) -> str:+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="_key", access_secret="_secret")+ table = DataWarehouseTable.objects.create(+ name="orders_source",+ team=self.team,+ columns={"customer_id": "String"},+ credential=credential,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="http://localhost:19000/bucket/orders_source",+ )+ return f"/api/projects/{self.team.id}/warehouse_tables/{table.id}/checks"++ def _payload(self, **overrides) -> dict:+ return {+ "check_type": CheckType.NOT_NULL,+ "column_name": "customer_id",+ **overrides,+ }++ def _create_check(self, **overrides) -> DataQualityCheck:+ response = self.client.post(f"{self.url}/", self._payload(**overrides))+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ return DataQualityCheck.objects.for_team(self.team.id).get(id=response.json()["id"])++ def _make_view(self, name: str) -> DataWarehouseSavedQuery:+ return DataWarehouseSavedQuery.objects.create(+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )++ def test_the_whole_surface_is_gated_on_the_feature_flag(self) -> None:+ with patch(FLAG, return_value=False):+ assert self.client.get(f"{self.url}/").status_code == status.HTTP_403_FORBIDDEN+ assert self.client.post(f"{self.url}/", self._payload()).status_code == status.HTTP_403_FORBIDDEN+ assert self.client.get(f"{self.url}/check_types/").status_code == status.HTTP_403_FORBIDDEN+ assert self.client.get(self._gate_url()).status_code == status.HTTP_403_FORBIDDEN++ @parameterized.expand([("view",), ("table",)])+ def test_create_returns_the_fingerprint_and_re_creating_upserts(self, kind: str) -> None:+ url = self.url if kind == "view" else self._table_checks_url()+ created = self.client.post(f"{url}/", self._payload())+ assert created.status_code == status.HTTP_201_CREATED, created.json()+ assert created.json()["fingerprint"]++ again = self.client.post(f"{url}/", self._payload(description="clarified"))++ assert again.status_code == status.HTTP_200_OK+ assert again.json()["id"] == created.json()["id"]+ assert again.json()["description"] == "clarified"+ assert DataQualityCheck.objects.for_team(self.team.id).count() == 1++ @parameterized.expand(+ [+ ("unknown_check_type", {"check_type": "anomaly"}),+ ("config_key_not_in_schema", {"config": {"tolerance": 3}}),+ ("column_required_but_missing", {"column_name": ""}),+ (+ "accepted_values_needs_values",+ {"check_type": CheckType.ACCEPTED_VALUES, "config": {"values": []}},+ ),+ ]+ )+ def test_invalid_definitions_are_rejected(self, _name, overrides: dict) -> None:+ response = self.client.post(f"{self.url}/", self._payload(**overrides))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert DataQualityCheck.objects.for_team(self.team.id).count() == 0++ def test_creating_under_an_unknown_parent_is_rejected(self) -> None:+ response = self.client.post(f"{self._checks_url(uuid4())}/", self._payload())++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert DataQualityCheck.objects.for_team(self.team.id).count() == 0++ def test_a_name_cannot_be_reused_within_a_project(self) -> None:+ self._create_check(name="orders_customer_id_not_null")++ clash = self.client.post(+ f"{self.url}/",+ self._payload(column_name="total", name="orders_customer_id_not_null"),+ )++ assert clash.status_code == status.HTTP_409_CONFLICT++ def test_a_differently_typed_config_upserts_instead_of_duplicating(self) -> None:+ # The fingerprint hashes config after its type model parses it, so an agent that sends+ # max_age_minutes as a string matches the check it already created with an int.+ first = self.client.post(+ f"{self.url}/",+ self._payload(check_type=CheckType.FRESHNESS, column_name="created_at", config={"max_age_minutes": 60}),+ )+ assert first.status_code == status.HTTP_201_CREATED++ again = self.client.post(+ f"{self.url}/",+ self._payload(check_type=CheckType.FRESHNESS, column_name="created_at", config={"max_age_minutes": "60"}),+ )++ assert again.status_code == status.HTTP_200_OK+ assert again.json()["id"] == first.json()["id"]+ assert DataQualityCheck.objects.for_team(self.team.id).count() == 1++ def test_re_creating_a_named_check_upserts_rather_than_conflicting(self) -> None:+ # The name belongs to the same check, so an identical re-propose must upsert, not 409.+ created = self.client.post(f"{self.url}/", self._payload(name="orders_customer_id_not_null"))+ assert created.status_code == status.HTTP_201_CREATED++ again = self.client.post(f"{self.url}/", self._payload(name="orders_customer_id_not_null"))++ assert again.status_code == status.HTTP_200_OK+ assert again.json()["id"] == created.json()["id"]++ @parameterized.expand([("check_type",), ("column_name",), ("config",)])+ def test_the_assertion_cannot_be_edited_in_place(self, field: str) -> None:+ # Editing it would leave the fingerprint describing a different check, so later identical+ # creates would duplicate instead of upserting.+ check = self._create_check()+ new_value = {+ "check_type": CheckType.UNIQUE,+ "column_name": "total",+ "config": {"values": ["a"]},+ }[field]++ response = self.client.patch(f"{self.url}/{check.id}/", {field: new_value})++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ check.refresh_from_db()+ assert str(getattr(check, field)) != str(new_value)++ def test_a_racing_identical_create_returns_the_winning_row_not_a_500(self) -> None:+ # Two identical creates can both miss the fingerprint lookup and race to insert; the uniqueness+ # constraint lets only one win. Simulate the loser by making its lookup miss the row the winner+ # already committed: it must catch the IntegrityError, refetch, and return the winner with 200.+ winner = self._create_check()++ with patch.object(checks_logic, "_find_by_fingerprint", side_effect=[None, winner]):+ response = self.client.post(f"{self.url}/", self._payload(description="racing"))++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["id"] == str(winner.id)+ assert DataQualityCheck.objects.for_team(self.team.id).count() == 1++ @parameterized.expand([("unscoped", "", None), ("single_view", SubjectType.VIEW, "view")])+ def test_suite_run_subject_type_is_null_when_not_scoped_to_one_subject(self, _name, stored, expected) -> None:+ # A manual check-id or multi-subject run stores a blank subject_type, but the response schema+ # only permits table/view -- surface the unscoped case as null, never a blank string.+ suite_run = DataQualitySuiteRun(team=self.team, trigger="manual", subject_type=stored)++ assert DataQualitySuiteRunSerializer(suite_run).data["subject_type"] == expected++ @parameterized.expand([("not_a_list", {"label": 1}), ("non_string_element", [{"nested": 1}])])+ def test_tags_must_be_a_list_of_strings(self, _name, tags) -> None:+ # The model field is untyped JSON; the serializer pins it to a list of strings so the generated+ # client and Zod schema are typed rather than accepting arbitrary JSON.+ response = self.client.post(f"{self.url}/", self._payload(tags=tags))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert DataQualityCheck.objects.for_team(self.team.id).count() == 0++ def test_a_workflow_that_cannot_start_does_not_strand_a_running_suite(self) -> None:+ check = self._create_check()++ with patch(START_SUITE, side_effect=RuntimeError("temporal down")):+ response = self.client.post(f"{self.url}/{check.id}/run/")++ assert response.status_code >= 500+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).latest("created_at")+ assert suite_run.status == "failed"+ assert suite_run.finished_at is not None++ def test_soft_delete_hides_the_check_but_keeps_it_readable_by_id(self) -> None:+ check = self._create_check()++ assert self.client.delete(f"{self.url}/{check.id}/").status_code == status.HTTP_204_NO_CONTENT++ assert self.client.get(f"{self.url}/").json()["results"] == []+ check.refresh_from_db()+ assert check.deleted is True+ assert check.enabled is False++ def test_list_is_scoped_to_the_parent_and_filters_by_check_type(self) -> None:+ self._create_check()+ self._create_check(check_type=CheckType.UNIQUE)+ other_view = self._make_view("refunds")+ other = self.client.post(f"{self._checks_url(other_view.id)}/", self._payload())+ assert other.status_code == status.HTTP_201_CREATED++ listed = self.client.get(f"{self.url}/")+ filtered = self.client.get(f"{self.url}/?check_type={CheckType.UNIQUE}")++ assert {row["subject_uuid"] for row in listed.json()["results"]} == {str(self.view.id)}+ assert len(listed.json()["results"]) == 2+ assert [row["check_type"] for row in filtered.json()["results"]] == [CheckType.UNIQUE]++ def test_check_types_exposes_a_config_schema_per_type(self) -> None:+ response = self.client.get(f"{self.url}/check_types/")++ assert response.status_code == status.HTTP_200_OK+ by_type = {row["check_type"]: row for row in response.json()}+ assert set(by_type) == {t.value for t in CheckType}+ assert by_type["accepted_values"]["config_schema"]["required"] == ["values"]+ assert by_type["row_count"]["requires_column"] is False++ @parameterized.expand(+ [+ ("no_checks", [], "unknown"),+ ("all_passing", [(CheckSeverity.ERROR, CheckRunStatus.PASSED)], "healthy"),+ (+ "error_severity_failure",+ [(CheckSeverity.ERROR, CheckRunStatus.FAILED), (CheckSeverity.WARN, CheckRunStatus.PASSED)],+ "failing",+ ),+ (+ "warn_only_failure",+ [(CheckSeverity.WARN, CheckRunStatus.FAILED), (CheckSeverity.ERROR, CheckRunStatus.PASSED)],+ "warn",+ ),+ (+ "execution_error_outranks_a_warning",+ [(CheckSeverity.WARN, CheckRunStatus.FAILED), (CheckSeverity.ERROR, CheckRunStatus.ERRORED)],+ "erroring",+ ),+ ]+ )+ def test_health_rolls_up_the_worst_outcome(self, _name, states: list[tuple], expected: str) -> None:+ for index, (severity, last_status) in enumerate(states):+ DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.VIEW,+ saved_query_id=self.view.id,+ subject_name="orders",+ check_type=CheckType.NOT_NULL,+ column_name=f"col_{index}",+ fingerprint=uuid4().hex,+ severity=severity,+ last_status=last_status,+ )++ response = self.client.get(f"{self.url}/health/")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["health"] == expected+ assert response.json()["checks_total"] == len(states)++ def test_health_ignores_disabled_checks(self) -> None:+ # A disabled failing check must not drive the verdict, or health would read 'failing' while+ # checks_failing counts 0 -- the verdict and the counts have to agree.+ common = {+ "team": self.team,+ "subject_type": SubjectType.VIEW,+ "saved_query_id": self.view.id,+ "subject_name": "orders",+ "check_type": CheckType.NOT_NULL,+ "severity": CheckSeverity.ERROR,+ }+ DataQualityCheck.objects.for_team(self.team.id).create(+ column_name="enabled_col", fingerprint=uuid4().hex, last_status=CheckRunStatus.PASSED, **common+ )+ DataQualityCheck.objects.for_team(self.team.id).create(+ column_name="disabled_col",+ fingerprint=uuid4().hex,+ last_status=CheckRunStatus.FAILED,+ enabled=False,+ **common,+ )++ response = self.client.get(f"{self.url}/health/")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["health"] == "healthy"+ assert response.json()["checks_total"] == 1+ assert response.json()["checks_failing"] == 0++ def test_run_returns_a_pollable_suite_run(self) -> None:+ check = self._create_check()++ with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):+ response = self.client.post(f"{self.url}/{check.id}/run/")++ assert response.status_code == status.HTTP_200_OK+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).get(id=response.json()["id"])+ assert suite_run.status == "running"+ assert response.json()["workflow_id"] == suite_run.workflow_id++ def test_run_all_records_the_subject_on_the_report(self) -> None:+ self._create_check()++ with patch(START_SUITE, return_value=MagicMock(start_workflow=AsyncMock())):+ response = self.client.post(f"{self.url}/run_all/")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["subject_uuid"] == str(self.view.id)++ def test_suite_runs_list_the_parents_single_subject_suites(self) -> None:+ # Multi-subject sweep suites carry no parent, so this surface must not serve them -- they+ # stay reachable through information_schema, the cross-subject surface.+ mine = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=self.view.id+ )+ sweep = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")+ DataQualityCheckRun.objects.for_team(self.team.id).create(+ team=self.team,+ suite_run=mine,+ subject_type=SubjectType.VIEW,+ subject_uuid=self.view.id,+ subject_name="orders",+ check_type=CheckType.NOT_NULL,+ check_fingerprint=uuid4().hex,+ status=CheckRunStatus.FAILED,+ failed_row_count=3,+ )++ base = self._suite_runs_url()+ listed = self.client.get(f"{base}/")++ assert {row["id"] for row in listed.json()["results"]} == {str(mine.id)}+ assert self.client.get(f"{base}/{sweep.id}/").status_code == status.HTTP_404_NOT_FOUND+ check_runs = self.client.get(f"{base}/{mine.id}/check_runs/")+ assert [row["subject_name"] for row in check_runs.json()] == ["orders"]++ def _deny_the_view(self) -> None:+ # Deny the default member object-level access to the "orders" view, the way the HogQL+ # database sees it -- so denied_subject_names() picks it up and the endpoint hides it.+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_view",+ resource_id=str(self.view.id),+ organization_member=self.organization_membership,+ access_level="none",+ )+ # Warehouse table/view denial only flows into the HogQL database behind this flag.+ 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()++ @parameterized.expand(+ [+ ("list", lambda self, check, suite: self.client.get(f"{self.url}/")),+ ("retrieve", lambda self, check, suite: self.client.get(f"{self.url}/{check.id}/")),+ ("create", lambda self, check, suite: self.client.post(f"{self.url}/", self._payload())),+ ("run", lambda self, check, suite: self.client.post(f"{self.url}/{check.id}/run/")),+ ("runs", lambda self, check, suite: self.client.get(f"{self.url}/{check.id}/runs/")),+ ("run_all", lambda self, check, suite: self.client.post(f"{self.url}/run_all/")),+ ("health", lambda self, check, suite: self.client.get(f"{self.url}/health/")),+ ("suite_runs_list", lambda self, check, suite: self.client.get(f"{self._suite_runs_url()}/")),+ (+ "suite_run_check_runs",+ lambda self, check, suite: self.client.get(f"{self._suite_runs_url()}/{suite.id}/check_runs/"),+ ),+ ]+ )+ def test_a_denied_parent_subject_blocks_every_action(self, _name: str, call) -> None:+ # Authoring, running, or reading anything under a table the member cannot query would leak+ # its shape and observed counts. The subject is the parent in the URL, so every action 403s.+ check = self._create_check()+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(+ team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=self.view.id+ )+ self._deny_the_view()++ assert call(self, check, suite).status_code == status.HTTP_403_FORBIDDEN++ def test_deleting_a_denied_subject_does_not_hand_its_history_over(self) -> None:+ # An orphan resolves to an empty name, which matches no denial, so deleting the view would+ # otherwise lift the member's denial along with it.+ self._create_check()+ self._deny_the_view()+ self.view.delete()++ assert self.client.get(f"{self.url}/").status_code == status.HTTP_403_FORBIDDEN++ def test_an_unrestricted_member_still_reads_an_orphaned_subjects_checks(self) -> None:+ # Orphaned history stays reachable: checks on a deleted subject are skipped, not hidden.+ self._create_check()+ self.view.delete()++ assert self.client.get(f"{self.url}/").status_code == status.HTTP_200_OK++ @parameterized.expand(+ [+ ("custom_sql", CheckType.CUSTOM_SQL, "", {"query": "SELECT 1 FROM orders"}),+ ("relationships", CheckType.RELATIONSHIPS, "customer_id", None),+ ]+ )+ def test_a_denied_referenced_subject_blocks_authoring(self, _name, check_type, column_name, config) -> None:+ # The parent is not the only subject a check reads: custom_sql selects arbitrary tables+ # and relationships names a second subject. Authoring one that reads the denied "orders" from an+ # allowed subject must 403 -- the worker runs it with team scope only, a count oracle otherwise.+ allowed = self._make_view("customers")+ if config is None:+ config = {"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(self.view.id), "to_column": "id"}+ self._deny_the_view()++ response = self.client.post(+ f"{self._checks_url(allowed.id)}/",+ self._payload(check_type=check_type, column_name=column_name, config=config),+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert DataQualityCheck.objects.for_team(self.team.id).count() == 0++ @parameterized.expand(+ [+ ("run", lambda self, url, check: self.client.post(f"{url}/{check.id}/run/")),+ ("run_all", lambda self, url, check: self.client.post(f"{url}/run_all/")),+ ("runs", lambda self, url, check: self.client.get(f"{url}/{check.id}/runs/")),+ ]+ )+ def test_a_denied_referenced_subject_blocks_triggering_and_reading_history(self, _name, call) -> None:+ # The parent subject stays allowed, so the check is visible -- but its custom_sql reads the+ # denied "orders". Triggering it (run, run_all) and reading its run history (runs, which+ # exposes counts from past executions) gate on every subject it references, not just the parent.+ allowed = self._make_view("customers")+ check = DataQualityCheck.objects.for_team(self.team.id).create(+ team=self.team,+ subject_type=SubjectType.VIEW,+ saved_query_id=allowed.id,+ subject_name="customers",+ check_type=CheckType.CUSTOM_SQL,+ config={"query": "SELECT 1 FROM orders"},+ fingerprint=uuid4().hex,+ )+ self._deny_the_view()++ assert call(self, self._checks_url(allowed.id), check).status_code == status.HTTP_403_FORBIDDEN++ @parameterized.expand(+ [+ ("create", lambda self, check: self.client.post(f"{self.url}/", self._payload(column_name="total"))),+ ("run", lambda self, check: self.client.post(f"{self.url}/{check.id}/run/")),+ ("run_all", lambda self, check: self.client.post(f"{self.url}/run_all/")),+ ("runs", lambda self, check: self.client.get(f"{self.url}/{check.id}/runs/")),+ ("list", lambda self, check: self.client.get(f"{self.url}/")),+ ("retrieve", lambda self, check: self.client.get(f"{self.url}/{check.id}/")),+ ("health", lambda self, check: self.client.get(f"{self.url}/health/")),+ ("suite_runs_list", lambda self, check: self.client.get(f"{self._suite_runs_url()}/")),+ ]+ )+ def test_query_denied_members_cannot_author_execute_or_read_check_outcomes(self, _name: str, call) -> None:+ # A check executes HogQL and its result columns are a count oracle over warehouse rows, and+ # reading a check back or its health rollup exposes the same counts one step removed, so+ # warehouse access alone must not be enough for any of them.+ check = self._create_check()+ AccessControl.objects.create(team=self.team, resource="query", access_level="none")+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": "access"}]+ self.organization.save()++ assert call(self, check).status_code == status.HTTP_403_FORBIDDEN++ def test_check_types_catalog_stays_readable_without_query_access(self) -> None:+ # The check-type catalog is static schema metadata with no execution state, so unlike the+ # check rows it is not gated on query access -- an agent must be able to discover config shapes.+ AccessControl.objects.create(team=self.team, resource="query", access_level="none")+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": "access"}]+ self.organization.save()++ assert self.client.get(f"{self.url}/check_types/").status_code == status.HTTP_200_OK++ def test_another_projects_checks_are_not_visible(self) -> None:+ check = self._create_check()+ other_team = self.create_team_with_organization(self.organization)++ response = self.client.get(+ f"/api/projects/{other_team.id}/warehouse_saved_queries/{self.view.id}/checks/{check.id}/"+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_the_materialization_gate_round_trips(self) -> None:+ url = self._gate_url()++ assert self.client.get(url).json() == {"gate_materialization_on_checks": False}++ patched = self.client.patch(url, {"gate_materialization_on_checks": True})++ assert patched.status_code == status.HTTP_200_OK+ assert patched.json() == {"gate_materialization_on_checks": True}+ assert self.client.get(url).json() == {"gate_materialization_on_checks": True}++ def test_writing_the_team_wide_gate_needs_resource_level_editor_access(self) -> None:+ # The gate is a project-wide setting, so an object-level editor grant on a single view must+ # not be enough to flip it -- writing needs resource-level warehouse editor access. Reading+ # stays open to a warehouse viewer.+ 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", access_level="viewer")+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_view",+ resource_id=str(self.view.id),+ organization_member=self.organization_membership,+ access_level="editor",+ )+ url = self._gate_url()++ assert self.client.get(url).status_code == status.HTTP_200_OK+ assert self.client.patch(url, {"gate_materialization_on_checks": True}).status_code == status.HTTP_403_FORBIDDENdiff --git a/products/data_quality/backend/tests/test_information_schema.py b/products/data_quality/backend/tests/test_information_schema.pynew file mode 100644index 000000000000..d7d9e2855c21--- /dev/null+++ b/products/data_quality/backend/tests/test_information_schema.py@@ -0,0 +1,184 @@+from uuid import uuid4++from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patch++from django.db import DatabaseError, connection+from django.test.utils import CaptureQueriesContext++from parameterized import parameterized++from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+from posthog.hogql.query import execute_hogql_query++from posthog.models.team import Team++from products.data_quality.backend.facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectType+from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun+++def _fail_queries_for_table(table_name: str):+ def wrapper(execute, sql, params, many, context):+ if table_name in sql:+ raise DatabaseError(f"Failed to load {table_name}")+ return execute(sql, params, many, context)++ return wrapper+++class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ flag_patch = patch(+ "products.data_quality.backend.facade.flags.is_data_quality_checks_enabled", return_value=True+ )+ flag_patch.start()+ self.addCleanup(flag_patch.stop)+ self.subject_uuid = uuid4()++ def _context(self, denied_tables: set[str] | None = None) -> HogQLContext:+ database = Database.create_for(team=self.team, user=self.user)+ if denied_tables:+ database._denied_tables |= denied_tables+ return HogQLContext(team=self.team, team_id=self.team.pk, database=database)++ def _check(self, team: Team | None = None, **kwargs) -> DataQualityCheck:+ team = team or self.team+ defaults = {+ "team": team,+ "subject_type": SubjectType.VIEW,+ "saved_query_id": self.subject_uuid,+ "subject_name": "orders",+ "check_type": CheckType.NOT_NULL,+ "column_name": "customer_id",+ "fingerprint": uuid4().hex,+ }+ return DataQualityCheck.objects.for_team(team.id).create(**{**defaults, **kwargs})++ def _run_for(self, check: DataQualityCheck, **kwargs) -> DataQualityCheckRun:+ suite_run = DataQualitySuiteRun.objects.for_team(check.team_id).create(team=check.team, trigger="manual")+ defaults = {+ "team": check.team,+ "quality_check": check,+ "suite_run": suite_run,+ "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.FAILED,+ "failed_row_count": 4,+ }+ return DataQualityCheckRun.objects.for_team(check.team_id).create(**{**defaults, **kwargs})++ def _query(self, sql: str, context: HogQLContext | None = None) -> list:+ return execute_hogql_query(sql, team=self.team, context=context or self._context()).results++ def test_checks_are_discoverable_with_their_config(self) -> None:+ self._check(+ name="orders_status_accepted",+ check_type=CheckType.ACCEPTED_VALUES,+ column_name="status",+ config={"values": ["paid"]},+ )++ rows = self._query(+ "SELECT name, subject_name, check_type, config, severity FROM system.information_schema.data_quality_checks"+ )++ assert rows == [("orders_status_accepted", "orders", "accepted_values", '{"values": ["paid"]}', "error")]++ def test_deleted_checks_disappear_but_their_runs_stay_queryable(self) -> None:+ check = self._check()+ self._run_for(check)+ DataQualityCheck.objects.for_team(self.team.id).filter(pk=check.pk).update(deleted=True)++ assert self._query("SELECT id FROM system.information_schema.data_quality_checks") == []+ assert len(self._query("SELECT id FROM system.information_schema.data_quality_check_runs")) == 1++ def test_rows_are_scoped_to_the_querying_team(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ self._check(team=other_team, subject_name="their_orders")+ self._check(subject_name="our_orders")++ rows = self._query("SELECT subject_name FROM system.information_schema.data_quality_checks")++ assert rows == [("our_orders",)]++ @parameterized.expand(+ [+ ("no_checks", [], "unknown", 0),+ ("passing", [(CheckSeverity.ERROR, CheckRunStatus.PASSED)], "healthy", 0),+ (+ "error_severity_failure",+ [(CheckSeverity.ERROR, CheckRunStatus.FAILED), (CheckSeverity.WARN, CheckRunStatus.PASSED)],+ "failing",+ 1,+ ),+ ("warn_only", [(CheckSeverity.WARN, CheckRunStatus.FAILED)], "warn", 1),+ ("execution_error", [(CheckSeverity.ERROR, CheckRunStatus.ERRORED)], "erroring", 0),+ ]+ )+ def test_health_matches_the_rest_endpoints_rollup(+ self, _name, states: list[tuple], expected_health: str, expected_failing: int+ ) -> None:+ for index, (severity, last_status) in enumerate(states):+ self._check(column_name=f"col_{index}", severity=severity, last_status=last_status)++ rows = self._query(+ "SELECT health, checks_total, checks_failing FROM system.information_schema.data_quality_health"+ )++ if not states:+ assert rows == []+ return+ assert rows == [(expected_health, len(states), expected_failing)]++ @parameterized.expand(+ [+ ("data_quality_checks", "data_quality_dataqualitycheck"),+ ("data_quality_check_runs", "data_quality_dataqualitycheckrun"),+ ("data_quality_health", "data_quality_dataqualitycheck"),+ ]+ )+ def test_a_broken_loader_degrades_to_no_rows(self, table: str, db_table: str) -> None:+ check = self._check()+ self._run_for(check)++ with CaptureQueriesContext(connection):+ with connection.execute_wrapper(_fail_queries_for_table(db_table)):+ results = self._query(f"SELECT * FROM system.information_schema.{table}")++ assert results == []++ @parameterized.expand(+ [+ ("checks", "SELECT subject_name FROM system.information_schema.data_quality_checks"),+ ("check_runs", "SELECT subject_name FROM system.information_schema.data_quality_check_runs"),+ ("health", "SELECT subject_name FROM system.information_schema.data_quality_health"),+ ]+ )+ def test_a_denied_subject_is_hidden_from_every_data_quality_table(self, _name: str, sql: str) -> None:+ denied = self._check(subject_name="orders", saved_query_id=uuid4())+ self._run_for(denied)+ allowed = self._check(subject_name="customers", saved_query_id=uuid4(), column_name="id")+ self._run_for(allowed)++ rows = self._query(sql, context=self._context(denied_tables={"orders"}))++ assert ("orders",) not in rows+ assert ("customers",) in rows++ def test_the_tables_are_absent_when_the_catalog_flag_is_off(self) -> None:+ with patch("products.data_quality.backend.facade.flags.is_data_quality_checks_enabled", return_value=False):+ listing = self._query(+ "SELECT table_name FROM system.information_schema.tables WHERE table_name ILIKE '%data_quality%'",+ context=HogQLContext(+ team=self.team,+ team_id=self.team.pk,+ database=Database.create_for(team=self.team, user=self.user),+ ),+ )++ assert listing == []diff --git a/products/data_quality/frontend/generated/api.schemas.ts b/products/data_quality/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..e1d2c79023ec--- /dev/null+++ b/products/data_quality/frontend/generated/api.schemas.ts@@ -0,0 +1,490 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+export interface DataQualitySuiteRunApi {+ readonly id: string+ /** manual, materialization, or source_sync. */+ readonly trigger: string+ /** running, completed, failed, or empty (nothing matched the trigger). */+ readonly status: string+ /**+ * 'table' or 'view' when the run targets exactly one subject; null for a check-scoped or multi-subject run.+ * @nullable+ */+ readonly subject_type: string | null+ /**+ * Set when the run targets exactly one subject.+ * @nullable+ */+ readonly subject_uuid: string | null+ readonly workflow_id: string+ readonly checks_passed: number+ readonly checks_failed: number+ readonly checks_errored: number+ readonly checks_skipped: number+ /** @nullable */+ readonly started_at: string | null+ /** @nullable */+ readonly finished_at: string | null+ /** Why the suite itself failed, as opposed to an individual check. */+ readonly error: string+ readonly created_at: string+}++export interface PaginatedDataQualitySuiteRunListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: DataQualitySuiteRunApi[]+}++/**+ * * `table` - table+ * * `view` - view+ */+export type SubjectTypeEnumApi = (typeof SubjectTypeEnumApi)[keyof typeof SubjectTypeEnumApi]++export const SubjectTypeEnumApi = {+ Table: 'table',+ View: 'view',+} as const++/**+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql+ */+export type CheckTypeEnumApi = (typeof CheckTypeEnumApi)[keyof typeof CheckTypeEnumApi]++export const CheckTypeEnumApi = {+ NotNull: 'not_null',+ Unique: 'unique',+ AcceptedValues: 'accepted_values',+ Relationships: 'relationships',+ RowCount: 'row_count',+ Freshness: 'freshness',+ CustomSql: 'custom_sql',+} as const++export interface DataQualityCheckRunApi {+ readonly id: string+ /**+ * The definition executed. Nulled rather than cascaded so history outlives hard deletes.+ * @nullable+ */+ readonly quality_check: string | null+ readonly suite_run: string+ readonly subject_type: SubjectTypeEnumApi+ readonly subject_uuid: string+ readonly subject_name: string+ /** Which assertion this run made.+ *+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql */+ readonly check_type: CheckTypeEnumApi+ readonly column_name: string+ /** passed, failed, errored, or skipped. */+ readonly status: string+ /**+ * Rows violating the assertion. Null for bounds checks like row_count.+ * @nullable+ */+ readonly failed_row_count: number | null+ /**+ * The check's headline number, recorded on passes too.+ * @nullable+ */+ readonly observed_value: number | null+ /** The HogQL that ran. Re-run it to see the offending rows. */+ readonly compiled_query: string+ /** Compilation or execution failure, when status is 'errored'. */+ readonly error: string+ /** @nullable */+ readonly duration_ms: number | null+ /** @nullable */+ readonly started_at: string | null+ /** @nullable */+ readonly finished_at: string | null+ readonly created_at: string+}++/**+ * * `error` - error+ * * `warn` - warn+ */+export type DataQualityCheckSeverityEnumApi =+ (typeof DataQualityCheckSeverityEnumApi)[keyof typeof DataQualityCheckSeverityEnumApi]++export const DataQualityCheckSeverityEnumApi = {+ Error: 'error',+ Warn: 'warn',+} as const++/**+ * * `user` - user+ * * `ai_generated` - ai_generated+ */+export type CreatedSourceEnumApi = (typeof CreatedSourceEnumApi)[keyof typeof CreatedSourceEnumApi]++export const CreatedSourceEnumApi = {+ User: 'user',+ AiGenerated: 'ai_generated',+} as const++/**+ * * `engineering` - Engineering+ * * `data` - Data+ * * `product` - Product Management+ * * `founder` - Founder+ * * `leadership` - Leadership+ * * `marketing` - Marketing+ * * `sales` - Sales / Success+ * * `student` - Student+ * * `other` - Other+ */+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]++export const RoleAtOrganizationEnumApi = {+ Engineering: 'engineering',+ Data: 'data',+ Product: 'product',+ Founder: 'founder',+ Leadership: 'leadership',+ Marketing: 'marketing',+ Sales: 'sales',+ Student: 'student',+ Other: 'other',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++/**+ * @nullable+ */+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null++export interface UserBasicApi {+ readonly id: number+ readonly uuid: string+ /**+ * @maxLength 200+ * @nullable+ */+ distinct_id?: string | null+ /** @maxLength 150 */+ first_name?: string+ /** @maxLength 150 */+ last_name?: string+ /** @maxLength 254 */+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ readonly hedgehog_config: UserBasicApiHedgehogConfig+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null+}++/**+ * Type-specific configuration, validated against the check type's JSON schema.+ */+export type DataQualityCheckApiConfig = { [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+ /**+ * Optional identifier-safe handle, unique per project. Omit to address the check by id.+ * @maxLength 128+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$+ */+ name?: string+ /** Why this check exists and what a failure means. */+ description?: string+ /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).+ *+ * * `table` - table+ * * `view` - view */+ readonly subject_type: SubjectTypeEnumApi+ /**+ * Id of the table or view being checked -- the parent resource in the URL.+ * @nullable+ */+ readonly subject_uuid: string | null+ /** Queryable name of the subject, refreshed on every run. */+ readonly subject_name: string+ /** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */+ readonly subject_status: string+ /**+ * Column the check applies to. Omit for table-scoped types like row_count.+ * @maxLength 400+ */+ column_name?: string+ /** Which assertion to make. Determines the shape of config; see /check_types/.+ *+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql */+ check_type: CheckTypeEnumApi+ /** Type-specific configuration, validated against the check type's JSON schema. */+ config?: DataQualityCheckApiConfig+ /** 'error' failures mark the subject failing and notify; 'warn' failures only surface.+ *+ * * `error` - error+ * * `warn` - warn */+ severity?: DataQualityCheckSeverityEnumApi+ /** Disabled checks are never run by any trigger. */+ enabled?: boolean+ /** Free-form string labels for grouping and filtering. */+ tags?: string[]+ /**+ * Email of the human accountable for this check, or null.+ * @nullable+ */+ readonly owner: string | null+ /**+ * When the check last executed.+ * @nullable+ */+ readonly last_run_at: string | null+ /** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */+ readonly last_status: string+ /** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */+ readonly fingerprint: string+ /** Whether a human ('user') or an agent ('ai_generated') authored this check.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnumApi+ /**+ * Model that generated the check, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string+ /**+ * AI author's confidence in the check, 0-1.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ confidence?: number | null+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string+ /** User who first created this check. */+ readonly created_by: UserBasicApi+ readonly created_at: string+ /** @nullable */+ readonly updated_at: string | null+}++export interface PaginatedDataQualityCheckListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: DataQualityCheckApi[]+}++/**+ * Type-specific configuration, validated against the check type's JSON schema.+ */+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 PatchedDataQualityCheckApi {+ readonly id?: string+ /**+ * Optional identifier-safe handle, unique per project. Omit to address the check by id.+ * @maxLength 128+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$+ */+ name?: string+ /** Why this check exists and what a failure means. */+ description?: string+ /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).+ *+ * * `table` - table+ * * `view` - view */+ readonly subject_type?: SubjectTypeEnumApi+ /**+ * Id of the table or view being checked -- the parent resource in the URL.+ * @nullable+ */+ readonly subject_uuid?: string | null+ /** Queryable name of the subject, refreshed on every run. */+ readonly subject_name?: string+ /** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */+ readonly subject_status?: string+ /**+ * Column the check applies to. Omit for table-scoped types like row_count.+ * @maxLength 400+ */+ column_name?: string+ /** Which assertion to make. Determines the shape of config; see /check_types/.+ *+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql */+ check_type?: CheckTypeEnumApi+ /** Type-specific configuration, validated against the check type's JSON schema. */+ config?: PatchedDataQualityCheckApiConfig+ /** 'error' failures mark the subject failing and notify; 'warn' failures only surface.+ *+ * * `error` - error+ * * `warn` - warn */+ severity?: DataQualityCheckSeverityEnumApi+ /** Disabled checks are never run by any trigger. */+ enabled?: boolean+ /** Free-form string labels for grouping and filtering. */+ tags?: string[]+ /**+ * Email of the human accountable for this check, or null.+ * @nullable+ */+ readonly owner?: string | null+ /**+ * When the check last executed.+ * @nullable+ */+ readonly last_run_at?: string | null+ /** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */+ readonly last_status?: string+ /** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */+ readonly fingerprint?: string+ /** Whether a human ('user') or an agent ('ai_generated') authored this check.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnumApi+ /**+ * Model that generated the check, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string+ /**+ * AI author's confidence in the check, 0-1.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ confidence?: number | null+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string+ /** User who first created this check. */+ readonly created_by?: UserBasicApi+ readonly created_at?: string+ /** @nullable */+ readonly updated_at?: string | null+}++/**+ * 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' or 'view'. */+ subject_type: string+ /** Id of the table or view. */+ subject_uuid: string+ /** failing (an error-severity check failed), erroring (a check could not run), warn (only warn-severity failures), healthy, or unknown (nothing has run yet). */+ health: string+ /** How many enabled, non-deleted checks cover this subject. */+ checks_total: number+ /** How many of those checks last reported a failure. */+ checks_failing: number+}++export type WarehouseSavedQueriesCheckSuiteRunsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type WarehouseSavedQueriesChecksListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type WarehouseTablesCheckSuiteRunsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type WarehouseTablesChecksListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/data_quality/frontend/generated/api.ts b/products/data_quality/frontend/generated/api.tsnew file mode 100644index 000000000000..60c69cc7acef--- /dev/null+++ b/products/data_quality/frontend/generated/api.ts@@ -0,0 +1,685 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ DataQualityCheckApi,+ DataQualityCheckRunApi,+ DataQualityCheckTypeApi,+ DataQualitySubjectHealthApi,+ DataQualitySuiteRunApi,+ PaginatedDataQualityCheckListApi,+ PaginatedDataQualitySuiteRunListApi,+ PatchedDataQualityCheckApi,+ WarehouseSavedQueriesCheckSuiteRunsListParams,+ WarehouseSavedQueriesChecksListParams,+ WarehouseTablesCheckSuiteRunsListParams,+ WarehouseTablesChecksListParams,+} from './api.schemas'++// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>++export const getWarehouseSavedQueriesCheckSuiteRunsListUrl = (+ projectId: string,+ savedQueryId: string,+ params?: WarehouseSavedQueriesCheckSuiteRunsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/check_suite_runs/?${stringifiedParams}`+ : `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/check_suite_runs/`+}++/**+ * Read-only reports for this subject's check-suite executions.+ */+export const warehouseSavedQueriesCheckSuiteRunsList = async (+ projectId: string,+ savedQueryId: string,+ params?: WarehouseSavedQueriesCheckSuiteRunsListParams,+ options?: RequestInit+): Promise<PaginatedDataQualitySuiteRunListApi> => {+ return apiMutator<PaginatedDataQualitySuiteRunListApi>(+ getWarehouseSavedQueriesCheckSuiteRunsListUrl(projectId, savedQueryId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseSavedQueriesCheckSuiteRunsRetrieveUrl = (+ projectId: string,+ savedQueryId: string,+ id: string+) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/check_suite_runs/${id}/`+}++/**+ * Read-only reports for this subject's check-suite executions.+ */+export const warehouseSavedQueriesCheckSuiteRunsRetrieve = async (+ projectId: string,+ savedQueryId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(+ getWarehouseSavedQueriesCheckSuiteRunsRetrieveUrl(projectId, savedQueryId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseSavedQueriesCheckSuiteRunsCheckRunsListUrl = (+ projectId: string,+ savedQueryId: string,+ id: string+) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/check_suite_runs/${id}/check_runs/`+}++/**+ * Every check execution in this suite run.+ */+export const warehouseSavedQueriesCheckSuiteRunsCheckRunsList = async (+ projectId: string,+ savedQueryId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualityCheckRunApi[]> => {+ return apiMutator<DataQualityCheckRunApi[]>(+ getWarehouseSavedQueriesCheckSuiteRunsCheckRunsListUrl(projectId, savedQueryId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseSavedQueriesChecksListUrl = (+ projectId: string,+ savedQueryId: string,+ params?: WarehouseSavedQueriesChecksListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/?${stringifiedParams}`+ : `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseSavedQueriesChecksList = async (+ projectId: string,+ savedQueryId: string,+ params?: WarehouseSavedQueriesChecksListParams,+ options?: RequestInit+): Promise<PaginatedDataQualityCheckListApi> => {+ return apiMutator<PaginatedDataQualityCheckListApi>(+ getWarehouseSavedQueriesChecksListUrl(projectId, savedQueryId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseSavedQueriesChecksCreateUrl = (projectId: string, savedQueryId: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/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 warehouseSavedQueriesChecksCreate = async (+ projectId: string,+ savedQueryId: string,+ dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getWarehouseSavedQueriesChecksCreateUrl(projectId, savedQueryId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataQualityCheckApi),+ })+}++export const getWarehouseSavedQueriesChecksRetrieveUrl = (projectId: string, savedQueryId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseSavedQueriesChecksRetrieve = async (+ projectId: string,+ savedQueryId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getWarehouseSavedQueriesChecksRetrieveUrl(projectId, savedQueryId, id), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseSavedQueriesChecksUpdateUrl = (projectId: string, savedQueryId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseSavedQueriesChecksUpdate = async (+ projectId: string,+ savedQueryId: string,+ id: string,+ dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getWarehouseSavedQueriesChecksUpdateUrl(projectId, savedQueryId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataQualityCheckApi),+ })+}++export const getWarehouseSavedQueriesChecksPartialUpdateUrl = (projectId: string, savedQueryId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseSavedQueriesChecksPartialUpdate = async (+ projectId: string,+ savedQueryId: string,+ id: string,+ patchedDataQualityCheckApi?: NonReadonly<PatchedDataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(+ getWarehouseSavedQueriesChecksPartialUpdateUrl(projectId, savedQueryId, id),+ {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedDataQualityCheckApi),+ }+ )+}++export const getWarehouseSavedQueriesChecksDestroyUrl = (projectId: string, savedQueryId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseSavedQueriesChecksDestroy = async (+ projectId: string,+ savedQueryId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getWarehouseSavedQueriesChecksDestroyUrl(projectId, savedQueryId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getWarehouseSavedQueriesChecksRunCreateUrl = (projectId: string, savedQueryId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/run/`+}++/**+ * Run this check now. Returns the suite run to poll for the report.+ */+export const warehouseSavedQueriesChecksRunCreate = async (+ projectId: string,+ savedQueryId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getWarehouseSavedQueriesChecksRunCreateUrl(projectId, savedQueryId, id), {+ ...options,+ method: 'POST',+ })+}++export const getWarehouseSavedQueriesChecksRunsListUrl = (projectId: string, savedQueryId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/${id}/runs/`+}++/**+ * Recent run history for this check, newest first.+ */+export const warehouseSavedQueriesChecksRunsList = async (+ projectId: string,+ savedQueryId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualityCheckRunApi[]> => {+ return apiMutator<DataQualityCheckRunApi[]>(+ getWarehouseSavedQueriesChecksRunsListUrl(projectId, savedQueryId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseSavedQueriesChecksCheckTypesListUrl = (projectId: string, savedQueryId: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/check_types/`+}++/**+ * The check types this project can author, with the JSON schema of each type's config.+ */+export const warehouseSavedQueriesChecksCheckTypesList = async (+ projectId: string,+ savedQueryId: string,+ options?: RequestInit+): Promise<DataQualityCheckTypeApi[]> => {+ return apiMutator<DataQualityCheckTypeApi[]>(+ getWarehouseSavedQueriesChecksCheckTypesListUrl(projectId, savedQueryId),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseSavedQueriesChecksHealthRetrieveUrl = (projectId: string, savedQueryId: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/health/`+}++/**+ * Health rollup for this table or view, from the denormalized status of its checks.+ */+export const warehouseSavedQueriesChecksHealthRetrieve = async (+ projectId: string,+ savedQueryId: string,+ options?: RequestInit+): Promise<DataQualitySubjectHealthApi> => {+ return apiMutator<DataQualitySubjectHealthApi>(+ getWarehouseSavedQueriesChecksHealthRetrieveUrl(projectId, savedQueryId),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseSavedQueriesChecksRunAllCreateUrl = (projectId: string, savedQueryId: string) => {+ return `/api/projects/${projectId}/warehouse_saved_queries/${savedQueryId}/checks/run_all/`+}++/**+ * Run every enabled check on this table or view. Returns the suite run to poll.+ */+export const warehouseSavedQueriesChecksRunAllCreate = async (+ projectId: string,+ savedQueryId: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getWarehouseSavedQueriesChecksRunAllCreateUrl(projectId, savedQueryId), {+ ...options,+ method: 'POST',+ })+}++export const getWarehouseTablesCheckSuiteRunsListUrl = (+ projectId: string,+ tableId: string,+ params?: WarehouseTablesCheckSuiteRunsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/warehouse_tables/${tableId}/check_suite_runs/?${stringifiedParams}`+ : `/api/projects/${projectId}/warehouse_tables/${tableId}/check_suite_runs/`+}++/**+ * Read-only reports for this subject's check-suite executions.+ */+export const warehouseTablesCheckSuiteRunsList = async (+ projectId: string,+ tableId: string,+ params?: WarehouseTablesCheckSuiteRunsListParams,+ options?: RequestInit+): Promise<PaginatedDataQualitySuiteRunListApi> => {+ return apiMutator<PaginatedDataQualitySuiteRunListApi>(+ getWarehouseTablesCheckSuiteRunsListUrl(projectId, tableId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseTablesCheckSuiteRunsRetrieveUrl = (projectId: string, tableId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/check_suite_runs/${id}/`+}++/**+ * Read-only reports for this subject's check-suite executions.+ */+export const warehouseTablesCheckSuiteRunsRetrieve = async (+ projectId: string,+ tableId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getWarehouseTablesCheckSuiteRunsRetrieveUrl(projectId, tableId, id), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseTablesCheckSuiteRunsCheckRunsListUrl = (projectId: string, tableId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/check_suite_runs/${id}/check_runs/`+}++/**+ * Every check execution in this suite run.+ */+export const warehouseTablesCheckSuiteRunsCheckRunsList = async (+ projectId: string,+ tableId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualityCheckRunApi[]> => {+ return apiMutator<DataQualityCheckRunApi[]>(+ getWarehouseTablesCheckSuiteRunsCheckRunsListUrl(projectId, tableId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getWarehouseTablesChecksListUrl = (+ projectId: string,+ tableId: string,+ params?: WarehouseTablesChecksListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/?${stringifiedParams}`+ : `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseTablesChecksList = async (+ projectId: string,+ tableId: string,+ params?: WarehouseTablesChecksListParams,+ options?: RequestInit+): Promise<PaginatedDataQualityCheckListApi> => {+ return apiMutator<PaginatedDataQualityCheckListApi>(getWarehouseTablesChecksListUrl(projectId, tableId, params), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseTablesChecksCreateUrl = (projectId: string, tableId: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/`+}++/**+ * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.+ */+export const warehouseTablesChecksCreate = async (+ projectId: string,+ tableId: string,+ dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getWarehouseTablesChecksCreateUrl(projectId, tableId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataQualityCheckApi),+ })+}++export const getWarehouseTablesChecksRetrieveUrl = (projectId: string, tableId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseTablesChecksRetrieve = async (+ projectId: string,+ tableId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getWarehouseTablesChecksRetrieveUrl(projectId, tableId, id), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseTablesChecksUpdateUrl = (projectId: string, tableId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseTablesChecksUpdate = async (+ projectId: string,+ tableId: string,+ id: string,+ dataQualityCheckApi: NonReadonly<DataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getWarehouseTablesChecksUpdateUrl(projectId, tableId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataQualityCheckApi),+ })+}++export const getWarehouseTablesChecksPartialUpdateUrl = (projectId: string, tableId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseTablesChecksPartialUpdate = async (+ projectId: string,+ tableId: string,+ id: string,+ patchedDataQualityCheckApi?: NonReadonly<PatchedDataQualityCheckApi>,+ options?: RequestInit+): Promise<DataQualityCheckApi> => {+ return apiMutator<DataQualityCheckApi>(getWarehouseTablesChecksPartialUpdateUrl(projectId, tableId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedDataQualityCheckApi),+ })+}++export const getWarehouseTablesChecksDestroyUrl = (projectId: string, tableId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/`+}++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseTablesChecksDestroy = async (+ projectId: string,+ tableId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getWarehouseTablesChecksDestroyUrl(projectId, tableId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getWarehouseTablesChecksRunCreateUrl = (projectId: string, tableId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/run/`+}++/**+ * Run this check now. Returns the suite run to poll for the report.+ */+export const warehouseTablesChecksRunCreate = async (+ projectId: string,+ tableId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getWarehouseTablesChecksRunCreateUrl(projectId, tableId, id), {+ ...options,+ method: 'POST',+ })+}++export const getWarehouseTablesChecksRunsListUrl = (projectId: string, tableId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/${id}/runs/`+}++/**+ * Recent run history for this check, newest first.+ */+export const warehouseTablesChecksRunsList = async (+ projectId: string,+ tableId: string,+ id: string,+ options?: RequestInit+): Promise<DataQualityCheckRunApi[]> => {+ return apiMutator<DataQualityCheckRunApi[]>(getWarehouseTablesChecksRunsListUrl(projectId, tableId, id), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseTablesChecksCheckTypesListUrl = (projectId: string, tableId: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/check_types/`+}++/**+ * The check types this project can author, with the JSON schema of each type's config.+ */+export const warehouseTablesChecksCheckTypesList = async (+ projectId: string,+ tableId: string,+ options?: RequestInit+): Promise<DataQualityCheckTypeApi[]> => {+ return apiMutator<DataQualityCheckTypeApi[]>(getWarehouseTablesChecksCheckTypesListUrl(projectId, tableId), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseTablesChecksHealthRetrieveUrl = (projectId: string, tableId: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/health/`+}++/**+ * Health rollup for this table or view, from the denormalized status of its checks.+ */+export const warehouseTablesChecksHealthRetrieve = async (+ projectId: string,+ tableId: string,+ options?: RequestInit+): Promise<DataQualitySubjectHealthApi> => {+ return apiMutator<DataQualitySubjectHealthApi>(getWarehouseTablesChecksHealthRetrieveUrl(projectId, tableId), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseTablesChecksRunAllCreateUrl = (projectId: string, tableId: string) => {+ return `/api/projects/${projectId}/warehouse_tables/${tableId}/checks/run_all/`+}++/**+ * Run every enabled check on this table or view. Returns the suite run to poll.+ */+export const warehouseTablesChecksRunAllCreate = async (+ projectId: string,+ tableId: string,+ options?: RequestInit+): Promise<DataQualitySuiteRunApi> => {+ return apiMutator<DataQualitySuiteRunApi>(getWarehouseTablesChecksRunAllCreateUrl(projectId, tableId), {+ ...options,+ method: 'POST',+ })+}diff --git a/products/data_quality/frontend/generated/api.zod.ts b/products/data_quality/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..78415dc3c92f--- /dev/null+++ b/products/data_quality/frontend/generated/api.zod.ts@@ -0,0 +1,432 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Create a check on this table or view, or refine the one already carrying the same fingerprint. Re-creating a semantically identical check returns 200 and the existing row, never a duplicate.+ */+export const warehouseSavedQueriesChecksCreateBodyNameMax = 128++export const warehouseSavedQueriesChecksCreateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const warehouseSavedQueriesChecksCreateBodyColumnNameMax = 400++export const warehouseSavedQueriesChecksCreateBodyAiModelMax = 128++export const warehouseSavedQueriesChecksCreateBodyConfidenceMin = 0+export const warehouseSavedQueriesChecksCreateBodyConfidenceMax = 1++export const WarehouseSavedQueriesChecksCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(warehouseSavedQueriesChecksCreateBodyNameMax)+ .regex(warehouseSavedQueriesChecksCreateBodyNameRegExp)+ .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(warehouseSavedQueriesChecksCreateBodyColumnNameMax)+ .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(warehouseSavedQueriesChecksCreateBodyAiModelMax)+ .optional()+ .describe('Model that generated the check, if AI-authored.'),+ confidence: zod+ .number()+ .min(warehouseSavedQueriesChecksCreateBodyConfidenceMin)+ .max(warehouseSavedQueriesChecksCreateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the check, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+ })+ .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseSavedQueriesChecksUpdateBodyNameMax = 128++export const warehouseSavedQueriesChecksUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const warehouseSavedQueriesChecksUpdateBodyColumnNameMax = 400++export const warehouseSavedQueriesChecksUpdateBodyAiModelMax = 128++export const warehouseSavedQueriesChecksUpdateBodyConfidenceMin = 0+export const warehouseSavedQueriesChecksUpdateBodyConfidenceMax = 1++export const WarehouseSavedQueriesChecksUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(warehouseSavedQueriesChecksUpdateBodyNameMax)+ .regex(warehouseSavedQueriesChecksUpdateBodyNameRegExp)+ .optional()+ .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),+ description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ column_name: zod+ .string()+ .max(warehouseSavedQueriesChecksUpdateBodyColumnNameMax)+ .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(warehouseSavedQueriesChecksUpdateBodyAiModelMax)+ .optional()+ .describe('Model that generated the check, if AI-authored.'),+ confidence: zod+ .number()+ .min(warehouseSavedQueriesChecksUpdateBodyConfidenceMin)+ .max(warehouseSavedQueriesChecksUpdateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the check, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+ })+ .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseSavedQueriesChecksPartialUpdateBodyNameMax = 128++export const warehouseSavedQueriesChecksPartialUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const warehouseSavedQueriesChecksPartialUpdateBodyColumnNameMax = 400++export const warehouseSavedQueriesChecksPartialUpdateBodyAiModelMax = 128++export const warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMin = 0+export const warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMax = 1++export const WarehouseSavedQueriesChecksPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(warehouseSavedQueriesChecksPartialUpdateBodyNameMax)+ .regex(warehouseSavedQueriesChecksPartialUpdateBodyNameRegExp)+ .optional()+ .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),+ description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ column_name: zod+ .string()+ .max(warehouseSavedQueriesChecksPartialUpdateBodyColumnNameMax)+ .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(warehouseSavedQueriesChecksPartialUpdateBodyAiModelMax)+ .optional()+ .describe('Model that generated the check, if AI-authored.'),+ confidence: zod+ .number()+ .min(warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMin)+ .max(warehouseSavedQueriesChecksPartialUpdateBodyConfidenceMax)+ .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.')++/**+ * 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 warehouseTablesChecksCreateBodyNameMax = 128++export const warehouseTablesChecksCreateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const warehouseTablesChecksCreateBodyColumnNameMax = 400++export const warehouseTablesChecksCreateBodyAiModelMax = 128++export const warehouseTablesChecksCreateBodyConfidenceMin = 0+export const warehouseTablesChecksCreateBodyConfidenceMax = 1++export const WarehouseTablesChecksCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(warehouseTablesChecksCreateBodyNameMax)+ .regex(warehouseTablesChecksCreateBodyNameRegExp)+ .optional()+ .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),+ description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ column_name: zod+ .string()+ .max(warehouseTablesChecksCreateBodyColumnNameMax)+ .optional()+ .describe('Column the check applies to. Omit for table-scoped types like row_count.'),+ check_type: zod+ .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])+ .describe(+ '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'+ )+ .describe(+ 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'+ ),+ config: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe("Type-specific configuration, validated against the check type's JSON schema."),+ severity: zod+ .enum(['error', 'warn'])+ .describe('\* `error` - error\n\* `warn` - warn')+ .optional()+ .describe(+ "'error' failures mark the subject failing and notify; 'warn' failures only surface.\n\n\* `error` - error\n\* `warn` - warn"+ ),+ enabled: zod.boolean().optional().describe('Disabled checks are never run by any trigger.'),+ tags: zod.array(zod.string()).optional().describe('Free-form string labels for grouping and filtering.'),+ created_source: zod+ .enum(['user', 'ai_generated'])+ .describe('\* `user` - user\n\* `ai_generated` - ai_generated')+ .optional()+ .describe(+ "Whether a human ('user') or an agent ('ai_generated') authored this check.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"+ ),+ ai_model: zod+ .string()+ .max(warehouseTablesChecksCreateBodyAiModelMax)+ .optional()+ .describe('Model that generated the check, if AI-authored.'),+ confidence: zod+ .number()+ .min(warehouseTablesChecksCreateBodyConfidenceMin)+ .max(warehouseTablesChecksCreateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the check, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+ })+ .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseTablesChecksUpdateBodyNameMax = 128++export const warehouseTablesChecksUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const warehouseTablesChecksUpdateBodyColumnNameMax = 400++export const warehouseTablesChecksUpdateBodyAiModelMax = 128++export const warehouseTablesChecksUpdateBodyConfidenceMin = 0+export const warehouseTablesChecksUpdateBodyConfidenceMax = 1++export const WarehouseTablesChecksUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(warehouseTablesChecksUpdateBodyNameMax)+ .regex(warehouseTablesChecksUpdateBodyNameRegExp)+ .optional()+ .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),+ description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ column_name: zod+ .string()+ .max(warehouseTablesChecksUpdateBodyColumnNameMax)+ .optional()+ .describe('Column the check applies to. Omit for table-scoped types like row_count.'),+ check_type: zod+ .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])+ .describe(+ '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'+ )+ .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(warehouseTablesChecksUpdateBodyAiModelMax)+ .optional()+ .describe('Model that generated the check, if AI-authored.'),+ confidence: zod+ .number()+ .min(warehouseTablesChecksUpdateBodyConfidenceMin)+ .max(warehouseTablesChecksUpdateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the check, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+ })+ .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')++/**+ * CRUD for one subject's checks, plus the actions that run them and report on them.+ */+export const warehouseTablesChecksPartialUpdateBodyNameMax = 128++export const warehouseTablesChecksPartialUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const warehouseTablesChecksPartialUpdateBodyColumnNameMax = 400++export const warehouseTablesChecksPartialUpdateBodyAiModelMax = 128++export const warehouseTablesChecksPartialUpdateBodyConfidenceMin = 0+export const warehouseTablesChecksPartialUpdateBodyConfidenceMax = 1++export const WarehouseTablesChecksPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(warehouseTablesChecksPartialUpdateBodyNameMax)+ .regex(warehouseTablesChecksPartialUpdateBodyNameRegExp)+ .optional()+ .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),+ description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ column_name: zod+ .string()+ .max(warehouseTablesChecksPartialUpdateBodyColumnNameMax)+ .optional()+ .describe('Column the check applies to. Omit for table-scoped types like row_count.'),+ check_type: zod+ .enum(['not_null', 'unique', 'accepted_values', 'relationships', 'row_count', 'freshness', 'custom_sql'])+ .describe(+ '\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'+ )+ .optional()+ .describe(+ 'Which assertion to make. Determines the shape of config; see \/check_types\/.\n\n\* `not_null` - not_null\n\* `unique` - unique\n\* `accepted_values` - accepted_values\n\* `relationships` - relationships\n\* `row_count` - row_count\n\* `freshness` - freshness\n\* `custom_sql` - custom_sql'+ ),+ config: zod+ .record(zod.string(), zod.unknown())+ .optional()+ .describe("Type-specific configuration, validated against the check type's JSON schema."),+ severity: zod+ .enum(['error', 'warn'])+ .describe('\* `error` - error\n\* `warn` - warn')+ .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(warehouseTablesChecksPartialUpdateBodyAiModelMax)+ .optional()+ .describe('Model that generated the check, if AI-authored.'),+ confidence: zod+ .number()+ .min(warehouseTablesChecksPartialUpdateBodyConfidenceMin)+ .max(warehouseTablesChecksPartialUpdateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the check, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+ })+ .describe('The subject is implied by the URL (the parent saved query or table), never part of the body.')diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.pyindex 65b1b123afc5..560c19fd6805 100644--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py@@ -12,6 +12,7 @@ from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serialifrom opentelemetry import tracefrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -32,6 +33,8 @@ from posthog.utils import convert_property_value, flattenfrom products.batch_exports.backend.facade.models import BatchExportRunfrom products.cdp.backend.facade.models import HogFunction, HogFunctionState, HogFunctionTypefrom products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery+from products.data_quality.backend.presentation.serializers import DataQualityGateConfigSerializer+from products.data_quality.backend.presentation.views import data_quality_gate_responsefrom products.data_warehouse.backend.facade.api import get_managed_warehouse_data_status, get_source_schema_statusesfrom products.data_warehouse.backend.facade.models import TeamDataWarehouseConfigfrom products.data_warehouse.backend.presentation.managed_warehouse_data_status import (@@ -889,6 +892,24 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):first_dashboard = config.overview_dashboards.order_by("id").first()return Response({"dashboard_id": first_dashboard.id if first_dashboard else None})+ @extend_schema(+ description="Read or update the team's data quality gate: whether a materialization whose "+ "error-severity checks fail is published.",+ request=DataQualityGateConfigSerializer,+ responses={200: DataQualityGateConfigSerializer},+ )+ @action(methods=["GET", "PATCH"], detail=False, required_scopes=["warehouse_view:write"])+ def data_quality_gate(self, request: Request, **kwargs) -> Response:+ # This is a project-wide setting, so writing it needs project-wide warehouse editor access.+ # The generic warehouse_view:write permission is otherwise satisfied by an object-level editor+ # grant on a single view, which must not be enough to flip a team-wide gate.+ if request.method == "PATCH" and not self.user_access_control.check_access_level_for_resource(+ "warehouse_view", "editor"+ ):+ raise PermissionDenied("You need editor access to data warehouse views to change this setting.")+ # Owned by the data_quality product; this viewset only lends it the warehouse surface.+ return data_quality_gate_response(self.team, request)+# --- Managed warehouse provisioning (proxied to duckgres, see managed_warehouse.py) ---@extend_schema(diff --git a/products/data_warehouse/backend/routes.py b/products/data_warehouse/backend/routes.pyindex 9ab5fca2f768..c343eaf142e0 100644--- a/products/data_warehouse/backend/routes.py+++ b/products/data_warehouse/backend/routes.py@@ -1,6 +1,7 @@from posthog.api.routing import RouterRegistryimport products.data_warehouse.backend.presentation.views.fix_hogql as fix_hogql+from products.data_quality.backend.presentation import views as data_quality_viewsfrom products.data_warehouse.backend.presentation.views import (column_annotation,data_modeling_job,@@ -18,19 +19,48 @@ from products.data_warehouse.backend.presentation.views import (def register_routes(routers: RouterRegistry) -> None:- routers.projects.register(r"warehouse_tables", table.TableViewSet, "project_warehouse_tables", ["team_id"])+ tables_router = routers.projects.register(+ r"warehouse_tables", table.TableViewSet, "project_warehouse_tables", ["team_id"]+ )routers.projects.register(r"warehouse_saved_query_folders",saved_query.DataWarehouseSavedQueryFolderViewSet,"project_warehouse_saved_query_folders",["team_id"],)- routers.projects.register(+ saved_queries_router = routers.projects.register(r"warehouse_saved_queries",saved_query.DataWarehouseSavedQueryViewSet,"project_warehouse_saved_queries",["team_id"],)+ # Data quality checks hang off the subjects they audit, the way run/materialize/resume do.+ # The viewsets are owned by the data_quality product; this product owns the sub-route+ # (dashboards -> sharing precedent).+ saved_queries_router.register(+ r"checks",+ data_quality_views.SavedQueryCheckViewSet,+ "project_warehouse_saved_query_checks",+ ["team_id", "saved_query_id"],+ )+ saved_queries_router.register(+ r"check_suite_runs",+ data_quality_views.SavedQuerySuiteRunViewSet,+ "project_warehouse_saved_query_check_suite_runs",+ ["team_id", "saved_query_id"],+ )+ tables_router.register(+ r"checks",+ data_quality_views.TableCheckViewSet,+ "project_warehouse_table_checks",+ ["team_id", "table_id"],+ )+ tables_router.register(+ r"check_suite_runs",+ data_quality_views.TableSuiteRunViewSet,+ "project_warehouse_table_check_suite_runs",+ ["team_id", "table_id"],+ )routers.projects.register(r"warehouse_view_links", view_link.ViewLinkViewSet, "project_warehouse_view_links", ["team_id"])diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex b54b3f7b177d..bb45d8e195f7 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -86,6 +86,22 @@ export interface CheckSchemaNameResponseApi {available: boolean}+/**+ * The team-level materialization gate. Checks always run and warn; this only toggles blocking.+ */+export interface DataQualityGateConfigApi {+ /** When true, a materialization whose error-severity checks fail is not published; the previous version keeps serving and downstream models are skipped. */+ gate_materialization_on_checks: boolean+}++/**+ * The team-level materialization gate. Checks always run and warn; this only toggles blocking.+ */+export interface PatchedDataQualityGateConfigApi {+ /** When true, a materialization whose error-severity checks fail is not published; the previous version keeps serving and downstream models are skipped. */+ gate_materialization_on_checks?: boolean+}+export interface DeleteWarehouseOrgResponseApi {/** Deletion lifecycle message from the provisioner */status?: stringdiff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex 166a9841d448..2ba15841efe7 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -15,6 +15,7 @@ import type {CreateTableFromUploadApi,DataModelingJobApi,DataModelingJobsListParams,+ DataQualityGateConfigApi,DataWarehouseCheckDatabaseNameRetrieveParams,DataWarehouseCheckSchemaNameRetrieveParams,DataWarehouseExpressionApi,@@ -49,6 +50,7 @@ import type {PaginatedTableListApi,PaginatedViewLinkListApi,PaginatedWarehouseColumnAnnotationListApi,+ PatchedDataQualityGateConfigApi,PatchedDataWarehouseExpressionApi,PatchedDataWarehouseSavedQueryApi,PatchedDataWarehouseSavedQueryColumnAnnotationApi,@@ -303,6 +305,43 @@ export const dataWarehouseDataOpsDashboardRetrieve = async (})}+export const getDataWarehouseDataQualityGateRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_warehouse/data_quality_gate/`+}++/**+ * Read or update the team's data quality gate: whether a materialization whose error-severity checks fail is published.+ */+export const dataWarehouseDataQualityGateRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<DataQualityGateConfigApi> => {+ return apiMutator<DataQualityGateConfigApi>(getDataWarehouseDataQualityGateRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getDataWarehouseDataQualityGatePartialUpdateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_warehouse/data_quality_gate/`+}++/**+ * Read or update the team's data quality gate: whether a materialization whose error-severity checks fail is published.+ */+export const dataWarehouseDataQualityGatePartialUpdate = async (+ projectId: string,+ patchedDataQualityGateConfigApi?: PatchedDataQualityGateConfigApi,+ options?: RequestInit+): Promise<DataQualityGateConfigApi> => {+ return apiMutator<DataQualityGateConfigApi>(getDataWarehouseDataQualityGatePartialUpdateUrl(projectId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedDataQualityGateConfigApi),+ })+}+export const getDataWarehouseDeleteOrgDestroyUrl = (projectId: string) => {return `/api/projects/${projectId}/data_warehouse/delete-org/`}diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.tsindex 2bbde0ac3d46..857a18010e6c 100644--- a/products/data_warehouse/frontend/generated/api.zod.ts+++ b/products/data_warehouse/frontend/generated/api.zod.ts@@ -9,6 +9,20 @@*/import * as zod from 'zod'+/**+ * Read or update the team's data quality gate: whether a materialization whose error-severity checks fail is published.+ */+export const DataWarehouseDataQualityGatePartialUpdateBody = /* @__PURE__ */ zod+ .object({+ gate_materialization_on_checks: zod+ .boolean()+ .optional()+ .describe(+ 'When true, a materialization whose error-severity checks fail is not published; the previous version keeps serving and downstream models are skipped.'+ ),+ })+ .describe('The team-level materialization gate. Checks always run and warn; this only toggles blocking.')+/*** Onboard this project onto the organization's existing managed warehouse.*diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex 38e741ccf2c0..3b469f224cf1 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -36,6 +36,12 @@ tools:data-warehouse-data-ops-dashboard-retrieve:operation: data_warehouse_data_ops_dashboard_retrieveenabled: false+ data-warehouse-data-quality-gate-partial-update:+ operation: data_warehouse_data_quality_gate_partial_update+ enabled: false+ data-warehouse-data-quality-gate-retrieve:+ operation: data_warehouse_data_quality_gate_retrieve+ enabled: falsedata-warehouse-delete-org-destroy:operation: data_warehouse_delete_org_destroyenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 841b52d4c067..0c7ac3efafaa 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16152,6 +16152,28 @@ export namespace Schemas {available: boolean;}+ /**+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql+ */+ export type CheckTypeEnum = typeof CheckTypeEnum[keyof typeof CheckTypeEnum];+++ export const CheckTypeEnum = {+ NotNull: 'not_null',+ Unique: 'unique',+ AcceptedValues: 'accepted_values',+ Relationships: 'relationships',+ RowCount: 'row_count',+ Freshness: 'freshness',+ CustomSql: 'custom_sql',+ } as const;+/*** * `abandoned` - Abandoned* * `off-topic` - Off-topic@@ -19963,6 +19985,248 @@ export namespace Schemas {readonly rows_expected: number | null;}+ /**+ * Type-specific configuration, validated against the check type's JSON schema.+ */+ export type DataQualityCheckConfig = { [key: string]: unknown };++ /**+ * * `table` - table+ * * `view` - view+ */+ export type SubjectTypeEnum = typeof SubjectTypeEnum[keyof typeof SubjectTypeEnum];+++ export const SubjectTypeEnum = {+ Table: 'table',+ View: 'view',+ } as const;++ /**+ * * `error` - error+ * * `warn` - warn+ */+ export type DataQualityCheckSeverityEnum = typeof DataQualityCheckSeverityEnum[keyof typeof DataQualityCheckSeverityEnum];+++ export const DataQualityCheckSeverityEnum = {+ Error: 'error',+ Warn: 'warn',+ } as const;++ /**+ * The subject is implied by the URL (the parent saved query or table), never part of the body.+ */+ export interface DataQualityCheck {+ readonly id: string;+ /**+ * Optional identifier-safe handle, unique per project. Omit to address the check by id.+ * @maxLength 128+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$+ */+ name?: string;+ /** Why this check exists and what a failure means. */+ description?: string;+ /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).+ *+ * * `table` - table+ * * `view` - view */+ readonly subject_type: SubjectTypeEnum;+ /**+ * Id of the table or view being checked -- the parent resource in the URL.+ * @nullable+ */+ readonly subject_uuid: string | null;+ /** Queryable name of the subject, refreshed on every run. */+ readonly subject_name: string;+ /** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */+ readonly subject_status: string;+ /**+ * Column the check applies to. Omit for table-scoped types like row_count.+ * @maxLength 400+ */+ column_name?: string;+ /** Which assertion to make. Determines the shape of config; see /check_types/.+ *+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql */+ check_type: CheckTypeEnum;+ /** Type-specific configuration, validated against the check type's JSON schema. */+ config?: DataQualityCheckConfig;+ /** 'error' failures mark the subject failing and notify; 'warn' failures only surface.+ *+ * * `error` - error+ * * `warn` - warn */+ severity?: DataQualityCheckSeverityEnum;+ /** Disabled checks are never run by any trigger. */+ enabled?: boolean;+ /** Free-form string labels for grouping and filtering. */+ tags?: string[];+ /**+ * Email of the human accountable for this check, or null.+ * @nullable+ */+ readonly owner: string | null;+ /**+ * When the check last executed.+ * @nullable+ */+ readonly last_run_at: string | null;+ /** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */+ readonly last_status: string;+ /** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */+ readonly fingerprint: string;+ /** Whether a human ('user') or an agent ('ai_generated') authored this check.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnum;+ /**+ * Model that generated the check, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string;+ /**+ * AI author's confidence in the check, 0-1.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ confidence?: number | null;+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string;+ /** User who first created this check. */+ readonly created_by: UserBasic;+ readonly created_at: string;+ /** @nullable */+ readonly updated_at: string | null;+ }++ export interface DataQualityCheckRun {+ readonly id: string;+ /**+ * The definition executed. Nulled rather than cascaded so history outlives hard deletes.+ * @nullable+ */+ readonly quality_check: string | null;+ readonly suite_run: string;+ readonly subject_type: SubjectTypeEnum;+ 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: CheckTypeEnum;+ readonly column_name: string;+ /** passed, failed, errored, or skipped. */+ readonly status: string;+ /**+ * Rows violating the assertion. Null for bounds checks like row_count.+ * @nullable+ */+ readonly failed_row_count: number | null;+ /**+ * The check's headline number, recorded on passes too.+ * @nullable+ */+ readonly observed_value: number | null;+ /** The HogQL that ran. Re-run it to see the offending rows. */+ readonly compiled_query: string;+ /** Compilation or execution failure, when status is 'errored'. */+ readonly error: string;+ /** @nullable */+ readonly duration_ms: number | null;+ /** @nullable */+ readonly started_at: string | null;+ /** @nullable */+ readonly finished_at: string | null;+ readonly created_at: string;+ }++ /**+ * JSON schema the config object is validated against.+ */+ export type DataQualityCheckTypeConfigSchema = { [key: string]: unknown };++ /**+ * One entry of the check-type catalog, so an agent can author config without guessing.+ */+ export interface DataQualityCheckType {+ /** 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: DataQualityCheckTypeConfigSchema;+ }++ /**+ * The team-level materialization gate. Checks always run and warn; this only toggles blocking.+ */+ export interface DataQualityGateConfig {+ /** When true, a materialization whose error-severity checks fail is not published; the previous version keeps serving and downstream models are skipped. */+ gate_materialization_on_checks: boolean;+ }++ /**+ * Per-subject rollup, the same rule the information_schema.data_quality_health table uses.+ */+ export interface DataQualitySubjectHealth {+ /** '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 DataQualitySuiteRun {+ 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; null for a check-scoped or multi-subject run.+ * @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 RequiredTableStatus {/** Name of the required source table (e.g. 'campaign', 'campaign_stats') */table_name: string;@@ -49438,6 +49702,24 @@ export namespace Schemas {results: DataModelingJob[];}+ export interface PaginatedDataQualityCheckList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: DataQualityCheck[];+ }++ export interface PaginatedDataQualitySuiteRunList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: DataQualitySuiteRun[];+ }+export interface PaginatedDataWarehouseExpressionList {count: number;/** @nullable */@@ -56101,6 +56383,112 @@ export namespace Schemas {readonly created_by?: UserBasic;}+ /**+ * Type-specific configuration, validated against the check type's JSON schema.+ */+ export type PatchedDataQualityCheckConfig = { [key: string]: unknown };++ /**+ * The subject is implied by the URL (the parent saved query or table), never part of the body.+ */+ export interface PatchedDataQualityCheck {+ readonly id?: string;+ /**+ * Optional identifier-safe handle, unique per project. Omit to address the check by id.+ * @maxLength 128+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$+ */+ name?: string;+ /** Why this check exists and what a failure means. */+ description?: string;+ /** Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).+ *+ * * `table` - table+ * * `view` - view */+ readonly subject_type?: SubjectTypeEnum;+ /**+ * Id of the table or view being checked -- the parent resource in the URL.+ * @nullable+ */+ readonly subject_uuid?: string | null;+ /** Queryable name of the subject, refreshed on every run. */+ readonly subject_name?: string;+ /** 'orphaned' once the subject stops resolving. Orphaned checks are skipped, not deleted. */+ readonly subject_status?: string;+ /**+ * Column the check applies to. Omit for table-scoped types like row_count.+ * @maxLength 400+ */+ column_name?: string;+ /** Which assertion to make. Determines the shape of config; see /check_types/.+ *+ * * `not_null` - not_null+ * * `unique` - unique+ * * `accepted_values` - accepted_values+ * * `relationships` - relationships+ * * `row_count` - row_count+ * * `freshness` - freshness+ * * `custom_sql` - custom_sql */+ check_type?: CheckTypeEnum;+ /** Type-specific configuration, validated against the check type's JSON schema. */+ config?: PatchedDataQualityCheckConfig;+ /** 'error' failures mark the subject failing and notify; 'warn' failures only surface.+ *+ * * `error` - error+ * * `warn` - warn */+ severity?: DataQualityCheckSeverityEnum;+ /** Disabled checks are never run by any trigger. */+ enabled?: boolean;+ /** Free-form string labels for grouping and filtering. */+ tags?: string[];+ /**+ * Email of the human accountable for this check, or null.+ * @nullable+ */+ readonly owner?: string | null;+ /**+ * When the check last executed.+ * @nullable+ */+ readonly last_run_at?: string | null;+ /** Outcome of the newest run: passed, failed, errored, skipped, or empty if never run. */+ readonly last_status?: string;+ /** sha256 of the subject, type, column, and config. Re-creating the same check upserts. */+ readonly fingerprint?: string;+ /** Whether a human ('user') or an agent ('ai_generated') authored this check.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnum;+ /**+ * Model that generated the check, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string;+ /**+ * AI author's confidence in the check, 0-1.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ confidence?: number | null;+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string;+ /** User who first created this check. */+ readonly created_by?: UserBasic;+ readonly created_at?: string;+ /** @nullable */+ readonly updated_at?: string | null;+ }++ /**+ * The team-level materialization gate. Checks always run and warn; this only toggles blocking.+ */+ export interface PatchedDataQualityGateConfig {+ /** When true, a materialization whose error-severity checks fail is not published; the previous version keeps serving and downstream models are skipped. */+ gate_materialization_on_checks?: boolean;+ }+export interface PatchedDataWarehouseExpression {readonly id?: string;/**@@ -92386,6 +92774,28 @@ export namespace Schemas {search?: string;};+ export type WarehouseSavedQueriesCheckSuiteRunsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type WarehouseSavedQueriesChecksListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type WarehouseSavedQueryDraftsListParams = {/*** Number of results to return per page.@@ -92412,6 +92822,28 @@ export namespace Schemas {search?: string;};+ export type WarehouseTablesCheckSuiteRunsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type WarehouseTablesChecksListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+/*** How the file will be read when the table is created.*/diff --git a/services/mcp/src/generated/data_quality/api.schemas.ts b/services/mcp/src/generated/data_quality/api.schemas.tsnew file mode 100644index 000000000000..d5346490d930--- /dev/null+++ b/services/mcp/src/generated/data_quality/api.schemas.ts@@ -0,0 +1,8 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 10 enabled ops+ * OpenAPI spec version: 1.0.0+ */diff --git a/services/mcp/src/generated/data_quality/api.ts b/services/mcp/src/generated/data_quality/api.tsnew file mode 100644index 000000000000..e2fb99ac0809--- /dev/null+++ b/services/mcp/src/generated/data_quality/api.ts@@ -0,0 +1,316 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 10 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Read-only reports for batches of check executions.+ */+export const DataQualityCheckSuiteRunsRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this data quality suite run.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Every check execution in this suite run.+ */+export const DataQualityCheckSuiteRunsCheckRunsListParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this data quality suite run.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Create a check, 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 DataQualityChecksCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const DataQualityChecksCreateQueryParams = /* @__PURE__ */ zod.object({+ check_type: zod.string().optional().describe('Filter the list to one check type.'),+ subject_type: zod.string().optional().describe("Filter the list to 'table' or 'view' subjects."),+ subject_uuid: zod.string().optional().describe('Filter the list to one table or view.'),+})++export const dataQualityChecksCreateBodyNameMax = 128++export const dataQualityChecksCreateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataQualityChecksCreateBodyColumnNameMax = 400++export const dataQualityChecksCreateBodyScheduleIntervalMinutesMin = -2147483648+export const dataQualityChecksCreateBodyScheduleIntervalMinutesMax = 2147483647++export const dataQualityChecksCreateBodyAiModelMax = 128++export const dataQualityChecksCreateBodyConfidenceMin = 0+export const dataQualityChecksCreateBodyConfidenceMax = 1++export const DataQualityChecksCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(dataQualityChecksCreateBodyNameMax)+ .regex(dataQualityChecksCreateBodyNameRegExp)+ .optional()+ .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),+ description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ subject_type: zod+ .enum(['table', 'view'])+ .describe('\* `table` - table\n\* `view` - view')+ .describe(+ "Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).\n\n\* `table` - table\n\* `view` - view"+ ),+ subject_uuid: zod.string().describe('Id of the table or view being checked.'),+ column_name: zod+ .string()+ .max(dataQualityChecksCreateBodyColumnNameMax)+ .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.unknown().optional().describe('Free-form labels for grouping and filtering.'),+ run_on_materialization: zod+ .boolean()+ .optional()+ .describe('Run after the view materializes. Never delays or fails the materialization itself.'),+ schedule_interval_minutes: zod+ .number()+ .min(dataQualityChecksCreateBodyScheduleIntervalMinutesMin)+ .max(dataQualityChecksCreateBodyScheduleIntervalMinutesMax)+ .nullish()+ .describe('Independent cadence in minutes. Omit for no schedule of its own.'),+ 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(dataQualityChecksCreateBodyAiModelMax)+ .optional()+ .describe('Model that generated the check, if AI-authored.'),+ confidence: zod+ .number()+ .min(dataQualityChecksCreateBodyConfidenceMin)+ .max(dataQualityChecksCreateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the check, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+})++/**+ * CRUD for data quality checks, plus the actions that run them and report on them.+ */+export const DataQualityChecksPartialUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this data quality check.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const dataQualityChecksPartialUpdateBodyNameMax = 128++export const dataQualityChecksPartialUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataQualityChecksPartialUpdateBodyColumnNameMax = 400++export const dataQualityChecksPartialUpdateBodyScheduleIntervalMinutesMin = -2147483648+export const dataQualityChecksPartialUpdateBodyScheduleIntervalMinutesMax = 2147483647++export const dataQualityChecksPartialUpdateBodyAiModelMax = 128++export const dataQualityChecksPartialUpdateBodyConfidenceMin = 0+export const dataQualityChecksPartialUpdateBodyConfidenceMax = 1++export const DataQualityChecksPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(dataQualityChecksPartialUpdateBodyNameMax)+ .regex(dataQualityChecksPartialUpdateBodyNameRegExp)+ .optional()+ .describe('Optional identifier-safe handle, unique per project. Omit to address the check by id.'),+ description: zod.string().optional().describe('Why this check exists and what a failure means.'),+ subject_type: zod+ .enum(['table', 'view'])+ .describe('\* `table` - table\n\* `view` - view')+ .optional()+ .describe(+ "Kind of catalog object being checked: 'table' (a synced warehouse table) or 'view' (a saved query).\n\n\* `table` - table\n\* `view` - view"+ ),+ subject_uuid: zod.string().optional().describe('Id of the table or view being checked.'),+ column_name: zod+ .string()+ .max(dataQualityChecksPartialUpdateBodyColumnNameMax)+ .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.unknown().optional().describe('Free-form labels for grouping and filtering.'),+ run_on_materialization: zod+ .boolean()+ .optional()+ .describe('Run after the view materializes. Never delays or fails the materialization itself.'),+ schedule_interval_minutes: zod+ .number()+ .min(dataQualityChecksPartialUpdateBodyScheduleIntervalMinutesMin)+ .max(dataQualityChecksPartialUpdateBodyScheduleIntervalMinutesMax)+ .nullish()+ .describe('Independent cadence in minutes. Omit for no schedule of its own.'),+ 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(dataQualityChecksPartialUpdateBodyAiModelMax)+ .optional()+ .describe('Model that generated the check, if AI-authored.'),+ confidence: zod+ .number()+ .min(dataQualityChecksPartialUpdateBodyConfidenceMin)+ .max(dataQualityChecksPartialUpdateBodyConfidenceMax)+ .nullish()+ .describe("AI author's confidence in the check, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+})++/**+ * CRUD for data quality checks, plus the actions that run them and report on them.+ */+export const DataQualityChecksDestroyParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this data quality check.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Run this check now. Returns the suite run to poll for the report.+ */+export const DataQualityChecksRunCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this data quality check.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Recent run history for this check, newest first.+ */+export const DataQualityChecksRunsListParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this data quality check.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * The check types this project can author, with the JSON schema of each type's config.+ */+export const DataQualityChecksCheckTypesListParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Health rollup for one table or view, from the denormalized status of its checks.+ */+export const DataQualityChecksHealthRetrieveParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const DataQualityChecksHealthRetrieveQueryParams = /* @__PURE__ */ zod.object({+ subject_type: zod.enum(['table', 'view']).describe("'table' or 'view'.\n\n\* `table` - table\n\* `view` - view"),+ subject_uuid: zod.string().describe('Id of the table or view to roll up.'),+})++/**+ * Run every enabled check on a table or view. Returns the suite run to poll for the report.+ */+export const DataQualityChecksRunForSubjectCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const DataQualityChecksRunForSubjectCreateBody = /* @__PURE__ */ zod.object({+ subject_type: zod+ .enum(['table', 'view'])+ .describe('\* `table` - table\n\* `view` - view')+ .describe("'table' or 'view'.\n\n\* `table` - table\n\* `view` - view"),+ subject_uuid: zod.string().describe('Id of the table or view whose checks should run.'),+})diff --git a/tach.toml b/tach.tomlindex 43977adc0908..3c990b67fc4c 100644--- a/tach.toml+++ b/tach.toml@@ -333,6 +333,7 @@ depends_on = ["ee","posthog","products.cdp",+ "products.data_quality","products.data_modeling","products.revenue_analytics", "products.warehouse_sources", "products.data_tools", "products.batch_exports","products.warehouse_sources_queue",@@ -1309,6 +1310,7 @@ from = [[[interfaces]]expose = ["backend\\.facade.*",+ "backend\\.presentation\\.serializers.*","backend\\.presentation\\.views.*",]from = [